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: void gfs2_clear_rgrpd(struct gfs2_sbd *sdp)
{
struct rb_node *n;
struct gfs2_rgrpd *rgd;
struct gfs2_glock *gl;
while ((n = rb_first(&sdp->sd_rindex_tree))) {
rgd = rb_entry(n, struct gfs2_rgrpd, rd_node);
gl = rgd->rd_gl;
rb_erase(n, &sdp->sd_rindex_tree);
if (gl) {
spin_lock(&gl->gl_lockref.lock);
gl->gl_object = NULL;
spin_unlock(&gl->gl_lockref.lock);
gfs2_glock_add_to_lru(gl);
gfs2_glock_put(gl);
}
gfs2_free_clones(rgd);
kfree(rgd->rd_bits);
return_all_reservations(rgd);
kmem_cache_free(gfs2_rgrpd_cachep, rgd);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'GFS2: don't set rgrp gl_object until it's inserted into rgrp tree
Before this patch, function read_rindex_entry would set a rgrp
glock's gl_object pointer to itself before inserting the rgrp into
the rgrp rbtree. The problem is: if another process was also reading
the rgrp in, and had already inserted its newly created rgrp, then
the second call to read_rindex_entry would overwrite that value,
then return a bad return code to the caller. Later, other functions
would reference the now-freed rgrp memory by way of gl_object.
In some cases, that could result in gfs2_rgrp_brelse being called
twice for the same rgrp: once for the failed attempt and once for
the "real" rgrp release. Eventually the kernel would panic.
There are also a number of other things that could go wrong when
a kernel module is accessing freed storage. For example, this could
result in rgrp corruption because the fake rgrp would point to a
fake bitmap in memory too, causing gfs2_inplace_reserve to search
some random memory for free blocks, and find some, since we were
never setting rgd->rd_bits to NULL before freeing it.
This patch fixes the problem by not setting gl_object until we
have successfully inserted the rgrp into the rbtree. Also, it sets
rd_bits to NULL as it frees them, which will ensure any accidental
access to the wrong rgrp will result in a kernel panic rather than
file system corruption, which is preferred.
Signed-off-by: Bob Peterson <[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 rds_recv_track_latency(struct rds_sock *rs, char __user *optval,
int optlen)
{
struct rds_rx_trace_so trace;
int i;
if (optlen != sizeof(struct rds_rx_trace_so))
return -EFAULT;
if (copy_from_user(&trace, optval, sizeof(trace)))
return -EFAULT;
rs->rs_rx_traces = trace.rx_traces;
for (i = 0; i < rs->rs_rx_traces; i++) {
if (trace.rx_trace_pos[i] > RDS_MSG_RX_DGRAM_TRACE_MAX) {
rs->rs_rx_traces = 0;
return -EFAULT;
}
rs->rs_rx_trace[i] = trace.rx_trace_pos[i];
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'RDS: validate the requested traces user input against max supported
Larger than supported value can lead to array read/write overflow.
Reported-by: Colin Ian King <[email protected]>
Signed-off-by: Santosh Shilimkar <[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 aac_send_raw_srb(struct aac_dev* dev, void __user * arg)
{
struct fib* srbfib;
int status;
struct aac_srb *srbcmd = NULL;
struct aac_hba_cmd_req *hbacmd = NULL;
struct user_aac_srb *user_srbcmd = NULL;
struct user_aac_srb __user *user_srb = arg;
struct aac_srb_reply __user *user_reply;
u32 chn;
u32 fibsize = 0;
u32 flags = 0;
s32 rcode = 0;
u32 data_dir;
void __user *sg_user[HBA_MAX_SG_EMBEDDED];
void *sg_list[HBA_MAX_SG_EMBEDDED];
u32 sg_count[HBA_MAX_SG_EMBEDDED];
u32 sg_indx = 0;
u32 byte_count = 0;
u32 actual_fibsize64, actual_fibsize = 0;
int i;
int is_native_device;
u64 address;
if (dev->in_reset) {
dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n"));
return -EBUSY;
}
if (!capable(CAP_SYS_ADMIN)){
dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n"));
return -EPERM;
}
/*
* Allocate and initialize a Fib then setup a SRB command
*/
if (!(srbfib = aac_fib_alloc(dev))) {
return -ENOMEM;
}
memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */
if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){
dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n"));
rcode = -EFAULT;
goto cleanup;
}
if ((fibsize < (sizeof(struct user_aac_srb) - sizeof(struct user_sgentry))) ||
(fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr)))) {
rcode = -EINVAL;
goto cleanup;
}
user_srbcmd = kmalloc(fibsize, GFP_KERNEL);
if (!user_srbcmd) {
dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n"));
rcode = -ENOMEM;
goto cleanup;
}
if(copy_from_user(user_srbcmd, user_srb,fibsize)){
dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n"));
rcode = -EFAULT;
goto cleanup;
}
flags = user_srbcmd->flags; /* from user in cpu order */
switch (flags & (SRB_DataIn | SRB_DataOut)) {
case SRB_DataOut:
data_dir = DMA_TO_DEVICE;
break;
case (SRB_DataIn | SRB_DataOut):
data_dir = DMA_BIDIRECTIONAL;
break;
case SRB_DataIn:
data_dir = DMA_FROM_DEVICE;
break;
default:
data_dir = DMA_NONE;
}
if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) {
dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n",
user_srbcmd->sg.count));
rcode = -EINVAL;
goto cleanup;
}
if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) {
dprintk((KERN_DEBUG"aacraid:SG with no direction specified\n"));
rcode = -EINVAL;
goto cleanup;
}
actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) +
((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry));
actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) *
(sizeof(struct sgentry64) - sizeof(struct sgentry));
/* User made a mistake - should not continue */
if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) {
dprintk((KERN_DEBUG"aacraid: Bad Size specified in "
"Raw SRB command calculated fibsize=%lu;%lu "
"user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu "
"issued fibsize=%d\n",
actual_fibsize, actual_fibsize64, user_srbcmd->sg.count,
sizeof(struct aac_srb), sizeof(struct sgentry),
sizeof(struct sgentry64), fibsize));
rcode = -EINVAL;
goto cleanup;
}
chn = user_srbcmd->channel;
if (chn < AAC_MAX_BUSES && user_srbcmd->id < AAC_MAX_TARGETS &&
dev->hba_map[chn][user_srbcmd->id].devtype ==
AAC_DEVTYPE_NATIVE_RAW) {
is_native_device = 1;
hbacmd = (struct aac_hba_cmd_req *)srbfib->hw_fib_va;
memset(hbacmd, 0, 96); /* sizeof(*hbacmd) is not necessary */
/* iu_type is a parameter of aac_hba_send */
switch (data_dir) {
case DMA_TO_DEVICE:
hbacmd->byte1 = 2;
break;
case DMA_FROM_DEVICE:
case DMA_BIDIRECTIONAL:
hbacmd->byte1 = 1;
break;
case DMA_NONE:
default:
break;
}
hbacmd->lun[1] = cpu_to_le32(user_srbcmd->lun);
hbacmd->it_nexus = dev->hba_map[chn][user_srbcmd->id].rmw_nexus;
/*
* we fill in reply_qid later in aac_src_deliver_message
* we fill in iu_type, request_id later in aac_hba_send
* we fill in emb_data_desc_count, data_length later
* in sg list build
*/
memcpy(hbacmd->cdb, user_srbcmd->cdb, sizeof(hbacmd->cdb));
address = (u64)srbfib->hw_error_pa;
hbacmd->error_ptr_hi = cpu_to_le32((u32)(address >> 32));
hbacmd->error_ptr_lo = cpu_to_le32((u32)(address & 0xffffffff));
hbacmd->error_length = cpu_to_le32(FW_ERROR_BUFFER_SIZE);
hbacmd->emb_data_desc_count =
cpu_to_le32(user_srbcmd->sg.count);
srbfib->hbacmd_size = 64 +
user_srbcmd->sg.count * sizeof(struct aac_hba_sgl);
} else {
is_native_device = 0;
aac_fib_init(srbfib);
/* raw_srb FIB is not FastResponseCapable */
srbfib->hw_fib_va->header.XferState &=
~cpu_to_le32(FastResponseCapable);
srbcmd = (struct aac_srb *) fib_data(srbfib);
// Fix up srb for endian and force some values
srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this
srbcmd->channel = cpu_to_le32(user_srbcmd->channel);
srbcmd->id = cpu_to_le32(user_srbcmd->id);
srbcmd->lun = cpu_to_le32(user_srbcmd->lun);
srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout);
srbcmd->flags = cpu_to_le32(flags);
srbcmd->retry_limit = 0; // Obsolete parameter
srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size);
memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb));
}
byte_count = 0;
if (is_native_device) {
struct user_sgmap *usg32 = &user_srbcmd->sg;
struct user_sgmap64 *usg64 =
(struct user_sgmap64 *)&user_srbcmd->sg;
for (i = 0; i < usg32->count; i++) {
void *p;
u64 addr;
sg_count[i] = (actual_fibsize64 == fibsize) ?
usg64->sg[i].count : usg32->sg[i].count;
if (sg_count[i] >
(dev->scsi_host_ptr->max_sectors << 9)) {
pr_err("aacraid: upsg->sg[%d].count=%u>%u\n",
i, sg_count[i],
dev->scsi_host_ptr->max_sectors << 9);
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(sg_count[i], GFP_KERNEL);
if (!p) {
rcode = -ENOMEM;
goto cleanup;
}
if (actual_fibsize64 == fibsize) {
addr = (u64)usg64->sg[i].addr[0];
addr += ((u64)usg64->sg[i].addr[1]) << 32;
} else {
addr = (u64)usg32->sg[i].addr;
}
sg_user[i] = (void __user *)(uintptr_t)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if (copy_from_user(p, sg_user[i],
sg_count[i])) {
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, sg_count[i],
data_dir);
hbacmd->sge[i].addr_hi = cpu_to_le32((u32)(addr>>32));
hbacmd->sge[i].addr_lo = cpu_to_le32(
(u32)(addr & 0xffffffff));
hbacmd->sge[i].len = cpu_to_le32(sg_count[i]);
hbacmd->sge[i].flags = 0;
byte_count += sg_count[i];
}
if (usg32->count > 0) /* embedded sglist */
hbacmd->sge[usg32->count-1].flags =
cpu_to_le32(0x40000000);
hbacmd->data_length = cpu_to_le32(byte_count);
status = aac_hba_send(HBA_IU_TYPE_SCSI_CMD_REQ, srbfib,
NULL, NULL);
} else if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) {
struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg;
struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg;
/*
* This should also catch if user used the 32 bit sgmap
*/
if (actual_fibsize64 == fibsize) {
actual_fibsize = actual_fibsize64;
for (i = 0; i < upsg->count; i++) {
u64 addr;
void* p;
sg_count[i] = upsg->sg[i].count;
if (sg_count[i] >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(sg_count[i], GFP_KERNEL);
if(!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
sg_count[i], i, upsg->count));
rcode = -ENOMEM;
goto cleanup;
}
addr = (u64)upsg->sg[i].addr[0];
addr += ((u64)upsg->sg[i].addr[1]) << 32;
sg_user[i] = (void __user *)(uintptr_t)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if (copy_from_user(p, sg_user[i],
sg_count[i])){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p,
sg_count[i], data_dir);
psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff);
psg->sg[i].addr[1] = cpu_to_le32(addr>>32);
byte_count += sg_count[i];
psg->sg[i].count = cpu_to_le32(sg_count[i]);
}
} else {
struct user_sgmap* usg;
usg = kmemdup(upsg,
actual_fibsize - sizeof(struct aac_srb)
+ sizeof(struct sgmap), GFP_KERNEL);
if (!usg) {
dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n"));
rcode = -ENOMEM;
goto cleanup;
}
actual_fibsize = actual_fibsize64;
for (i = 0; i < usg->count; i++) {
u64 addr;
void* p;
sg_count[i] = usg->sg[i].count;
if (sg_count[i] >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
kfree(usg);
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(sg_count[i], GFP_KERNEL);
if(!p) {
dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
sg_count[i], i, usg->count));
kfree(usg);
rcode = -ENOMEM;
goto cleanup;
}
sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if (copy_from_user(p, sg_user[i],
sg_count[i])) {
kfree (usg);
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p,
sg_count[i], data_dir);
psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff);
psg->sg[i].addr[1] = cpu_to_le32(addr>>32);
byte_count += sg_count[i];
psg->sg[i].count = cpu_to_le32(sg_count[i]);
}
kfree (usg);
}
srbcmd->count = cpu_to_le32(byte_count);
if (user_srbcmd->sg.count)
psg->count = cpu_to_le32(sg_indx+1);
else
psg->count = 0;
status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL);
} else {
struct user_sgmap* upsg = &user_srbcmd->sg;
struct sgmap* psg = &srbcmd->sg;
if (actual_fibsize64 == fibsize) {
struct user_sgmap64* usg = (struct user_sgmap64 *)upsg;
for (i = 0; i < upsg->count; i++) {
uintptr_t addr;
void* p;
sg_count[i] = usg->sg[i].count;
if (sg_count[i] >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(sg_count[i], GFP_KERNEL|GFP_DMA32);
if (!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
sg_count[i], i, usg->count));
rcode = -ENOMEM;
goto cleanup;
}
addr = (u64)usg->sg[i].addr[0];
addr += ((u64)usg->sg[i].addr[1]) << 32;
sg_user[i] = (void __user *)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if (copy_from_user(p, sg_user[i],
sg_count[i])){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir);
psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff);
byte_count += usg->sg[i].count;
psg->sg[i].count = cpu_to_le32(sg_count[i]);
}
} else {
for (i = 0; i < upsg->count; i++) {
dma_addr_t addr;
void* p;
sg_count[i] = upsg->sg[i].count;
if (sg_count[i] >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(sg_count[i], GFP_KERNEL|GFP_DMA32);
if (!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
sg_count[i], i, upsg->count));
rcode = -ENOMEM;
goto cleanup;
}
sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if (copy_from_user(p, sg_user[i],
sg_count[i])) {
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p,
sg_count[i], data_dir);
psg->sg[i].addr = cpu_to_le32(addr);
byte_count += sg_count[i];
psg->sg[i].count = cpu_to_le32(sg_count[i]);
}
}
srbcmd->count = cpu_to_le32(byte_count);
if (user_srbcmd->sg.count)
psg->count = cpu_to_le32(sg_indx+1);
else
psg->count = 0;
status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL);
}
if (status == -ERESTARTSYS) {
rcode = -ERESTARTSYS;
goto cleanup;
}
if (status != 0) {
dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n"));
rcode = -ENXIO;
goto cleanup;
}
if (flags & SRB_DataIn) {
for(i = 0 ; i <= sg_indx; i++){
if (copy_to_user(sg_user[i], sg_list[i], sg_count[i])) {
dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
}
user_reply = arg + fibsize;
if (is_native_device) {
struct aac_hba_resp *err =
&((struct aac_native_hba *)srbfib->hw_fib_va)->resp.err;
struct aac_srb_reply reply;
reply.status = ST_OK;
if (srbfib->flags & FIB_CONTEXT_FLAG_FASTRESP) {
/* fast response */
reply.srb_status = SRB_STATUS_SUCCESS;
reply.scsi_status = 0;
reply.data_xfer_length = byte_count;
reply.sense_data_size = 0;
memset(reply.sense_data, 0, AAC_SENSE_BUFFERSIZE);
} else {
reply.srb_status = err->service_response;
reply.scsi_status = err->status;
reply.data_xfer_length = byte_count -
le32_to_cpu(err->residual_count);
reply.sense_data_size = err->sense_response_data_len;
memcpy(reply.sense_data, err->sense_response_buf,
AAC_SENSE_BUFFERSIZE);
}
if (copy_to_user(user_reply, &reply,
sizeof(struct aac_srb_reply))) {
dprintk((KERN_DEBUG"aacraid: Copy to user failed\n"));
rcode = -EFAULT;
goto cleanup;
}
} else {
struct aac_srb_reply *reply;
reply = (struct aac_srb_reply *) fib_data(srbfib);
if (copy_to_user(user_reply, reply,
sizeof(struct aac_srb_reply))) {
dprintk((KERN_DEBUG"aacraid: Copy to user failed\n"));
rcode = -EFAULT;
goto cleanup;
}
}
cleanup:
kfree(user_srbcmd);
if (rcode != -ERESTARTSYS) {
for (i = 0; i <= sg_indx; i++)
kfree(sg_list[i]);
aac_fib_complete(srbfib);
aac_fib_free(srbfib);
}
return rcode;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'scsi: aacraid: Don't copy uninitialized stack memory to userspace
Both aac_send_raw_srb() and aac_get_hba_info() may copy stack allocated
structs to userspace without initializing all members of these
structs. Clear out this memory to prevent information leaks.
Fixes: 423400e64d377 ("scsi: aacraid: Include HBA direct interface")
Fixes: c799d519bf088 ("scsi: aacraid: Retrieve HBA host information ioctl")
Signed-off-by: Seth Forshee <[email protected]>
Reviewed-by: Johannes Thumshirn <[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 struct ad5755_platform_data *ad5755_parse_dt(struct device *dev)
{
struct device_node *np = dev->of_node;
struct device_node *pp;
struct ad5755_platform_data *pdata;
unsigned int tmp;
unsigned int tmparray[3];
int devnr, i;
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return NULL;
pdata->ext_dc_dc_compenstation_resistor =
of_property_read_bool(np, "adi,ext-dc-dc-compenstation-resistor");
if (!of_property_read_u32(np, "adi,dc-dc-phase", &tmp))
pdata->dc_dc_phase = tmp;
else
pdata->dc_dc_phase = AD5755_DC_DC_PHASE_ALL_SAME_EDGE;
pdata->dc_dc_freq = AD5755_DC_DC_FREQ_410kHZ;
if (!of_property_read_u32(np, "adi,dc-dc-freq-hz", &tmp)) {
for (i = 0; i < ARRAY_SIZE(ad5755_dcdc_freq_table); i++) {
if (tmp == ad5755_dcdc_freq_table[i][0]) {
pdata->dc_dc_freq = ad5755_dcdc_freq_table[i][1];
break;
}
}
if (i == ARRAY_SIZE(ad5755_dcdc_freq_table)) {
dev_err(dev,
"adi,dc-dc-freq out of range selecting 410kHz");
}
}
pdata->dc_dc_maxv = AD5755_DC_DC_MAXV_23V;
if (!of_property_read_u32(np, "adi,dc-dc-max-microvolt", &tmp)) {
for (i = 0; i < ARRAY_SIZE(ad5755_dcdc_maxv_table); i++) {
if (tmp == ad5755_dcdc_maxv_table[i][0]) {
pdata->dc_dc_maxv = ad5755_dcdc_maxv_table[i][1];
break;
}
}
if (i == ARRAY_SIZE(ad5755_dcdc_maxv_table)) {
dev_err(dev,
"adi,dc-dc-maxv out of range selecting 23V");
}
}
devnr = 0;
for_each_child_of_node(np, pp) {
if (devnr > AD5755_NUM_CHANNELS) {
dev_err(dev,
"There is to many channels defined in DT\n");
goto error_out;
}
if (!of_property_read_u32(pp, "adi,mode", &tmp))
pdata->dac[devnr].mode = tmp;
else
pdata->dac[devnr].mode = AD5755_MODE_CURRENT_4mA_20mA;
pdata->dac[devnr].ext_current_sense_resistor =
of_property_read_bool(pp, "adi,ext-current-sense-resistor");
pdata->dac[devnr].enable_voltage_overrange =
of_property_read_bool(pp, "adi,enable-voltage-overrange");
if (!of_property_read_u32_array(pp, "adi,slew", tmparray, 3)) {
pdata->dac[devnr].slew.enable = tmparray[0];
pdata->dac[devnr].slew.rate = AD5755_SLEW_RATE_64k;
for (i = 0; i < ARRAY_SIZE(ad5755_slew_rate_table); i++) {
if (tmparray[1] == ad5755_slew_rate_table[i][0]) {
pdata->dac[devnr].slew.rate =
ad5755_slew_rate_table[i][1];
break;
}
}
if (i == ARRAY_SIZE(ad5755_slew_rate_table)) {
dev_err(dev,
"channel %d slew rate out of range selecting 64kHz",
devnr);
}
pdata->dac[devnr].slew.step_size = AD5755_SLEW_STEP_SIZE_1;
for (i = 0; i < ARRAY_SIZE(ad5755_slew_step_table); i++) {
if (tmparray[2] == ad5755_slew_step_table[i][0]) {
pdata->dac[devnr].slew.step_size =
ad5755_slew_step_table[i][1];
break;
}
}
if (i == ARRAY_SIZE(ad5755_slew_step_table)) {
dev_err(dev,
"channel %d slew step size out of range selecting 1 LSB",
devnr);
}
} else {
pdata->dac[devnr].slew.enable = false;
pdata->dac[devnr].slew.rate = AD5755_SLEW_RATE_64k;
pdata->dac[devnr].slew.step_size =
AD5755_SLEW_STEP_SIZE_1;
}
devnr++;
}
return pdata;
error_out:
devm_kfree(dev, pdata);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'iio: ad5755: fix off-by-one on devnr limit check
The comparison for devnr limits is off-by-one, the current check
allows 0 to AD5755_NUM_CHANNELS and the limit should be in fact
0 to AD5755_NUM_CHANNELS - 1. This can lead to an out of bounds
write to pdata->dac[devnr]. Fix this by replacing > with >= on the
comparison.
Signed-off-by: Colin Ian King <[email protected]>
Fixes: c947459979c6 ("iio: ad5755: add support for dt bindings")
Signed-off-by: Jonathan Cameron <[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 arc_emac_tx(struct sk_buff *skb, struct net_device *ndev)
{
struct arc_emac_priv *priv = netdev_priv(ndev);
unsigned int len, *txbd_curr = &priv->txbd_curr;
struct net_device_stats *stats = &ndev->stats;
__le32 *info = &priv->txbd[*txbd_curr].info;
dma_addr_t addr;
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
len = max_t(unsigned int, ETH_ZLEN, skb->len);
if (unlikely(!arc_emac_tx_avail(priv))) {
netif_stop_queue(ndev);
netdev_err(ndev, "BUG! Tx Ring full when queue awake!\n");
return NETDEV_TX_BUSY;
}
addr = dma_map_single(&ndev->dev, (void *)skb->data, len,
DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(&ndev->dev, addr))) {
stats->tx_dropped++;
stats->tx_errors++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
dma_unmap_addr_set(&priv->tx_buff[*txbd_curr], addr, addr);
dma_unmap_len_set(&priv->tx_buff[*txbd_curr], len, len);
priv->tx_buff[*txbd_curr].skb = skb;
priv->txbd[*txbd_curr].data = cpu_to_le32(addr);
/* Make sure pointer to data buffer is set */
wmb();
skb_tx_timestamp(skb);
*info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len);
/* Increment index to point to the next BD */
*txbd_curr = (*txbd_curr + 1) % TX_BD_NUM;
/* Ensure that tx_clean() sees the new txbd_curr before
* checking the queue status. This prevents an unneeded wake
* of the queue in tx_clean().
*/
smp_mb();
if (!arc_emac_tx_avail(priv)) {
netif_stop_queue(ndev);
/* Refresh tx_dirty */
smp_mb();
if (arc_emac_tx_avail(priv))
netif_start_queue(ndev);
}
arc_reg_set(priv, R_STATUS, TXPL_MASK);
return NETDEV_TX_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'net: arc_emac: fix koops caused by sk_buff free
There is a race between arc_emac_tx() and arc_emac_tx_clean().
sk_buff got freed by arc_emac_tx_clean() while arc_emac_tx()
submitting sk_buff.
In order to free sk_buff arc_emac_tx_clean() checks:
if ((info & FOR_EMAC) || !txbd->data)
break;
...
dev_kfree_skb_irq(skb);
If condition false, arc_emac_tx_clean() free sk_buff.
In order to submit txbd, arc_emac_tx() do:
priv->tx_buff[*txbd_curr].skb = skb;
...
priv->txbd[*txbd_curr].data = cpu_to_le32(addr);
...
... <== arc_emac_tx_clean() check condition here
... <== (info & FOR_EMAC) is false
... <== !txbd->data is false
...
*info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len);
In order to reproduce the situation,
run device:
# iperf -s
run on host:
# iperf -t 600 -c <device-ip-addr>
[ 28.396284] ------------[ cut here ]------------
[ 28.400912] kernel BUG at .../net/core/skbuff.c:1355!
[ 28.414019] Internal error: Oops - BUG: 0 [#1] SMP ARM
[ 28.419150] Modules linked in:
[ 28.422219] CPU: 0 PID: 0 Comm: swapper/0 Tainted: G B 4.4.0+ #120
[ 28.429516] Hardware name: Rockchip (Device Tree)
[ 28.434216] task: c0665070 ti: c0660000 task.ti: c0660000
[ 28.439622] PC is at skb_put+0x10/0x54
[ 28.443381] LR is at arc_emac_poll+0x260/0x474
[ 28.447821] pc : [<c03af580>] lr : [<c028fec4>] psr: a0070113
[ 28.447821] sp : c0661e58 ip : eea68502 fp : ef377000
[ 28.459280] r10: 0000012c r9 : f08b2000 r8 : eeb57100
[ 28.464498] r7 : 00000000 r6 : ef376594 r5 : 00000077 r4 : ef376000
[ 28.471015] r3 : 0030488b r2 : ef13e880 r1 : 000005ee r0 : eeb57100
[ 28.477534] Flags: NzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
[ 28.484658] Control: 10c5387d Table: 8eaf004a DAC: 00000051
[ 28.490396] Process swapper/0 (pid: 0, stack limit = 0xc0660210)
[ 28.496393] Stack: (0xc0661e58 to 0xc0662000)
[ 28.500745] 1e40: 00000002 00000000
[ 28.508913] 1e60: 00000000 ef376520 00000028 f08b23b8 00000000 ef376520 ef7b6900 c028fc64
[ 28.517082] 1e80: 2f158000 c0661ea8 c0661eb0 0000012c c065e900 c03bdeac ffff95e9 c0662100
[ 28.525250] 1ea0: c0663924 00000028 c0661ea8 c0661ea8 c0661eb0 c0661eb0 0000001e c0660000
[ 28.533417] 1ec0: 40000003 00000008 c0695a00 0000000a c066208c 00000100 c0661ee0 c0027410
[ 28.541584] 1ee0: ef0fb700 2f158000 00200000 ffff95e8 00000004 c0662100 c0662080 00000003
[ 28.549751] 1f00: 00000000 00000000 00000000 c065b45c 0000001e ef005000 c0647a30 00000000
[ 28.557919] 1f20: 00000000 c0027798 00000000 c005cf40 f0802100 c0662ffc c0661f60 f0803100
[ 28.566088] 1f40: c0661fb8 c00093bc c000ffb4 60070013 ffffffff c0661f94 c0661fb8 c00137d4
[ 28.574267] 1f60: 00000001 00000000 00000000 c001ffa0 00000000 c0660000 00000000 c065a364
[ 28.582441] 1f80: c0661fb8 c0647a30 00000000 00000000 00000000 c0661fb0 c000ffb0 c000ffb4
[ 28.590608] 1fa0: 60070013 ffffffff 00000051 00000000 00000000 c005496c c0662400 c061bc40
[ 28.598776] 1fc0: ffffffff ffffffff 00000000 c061b680 00000000 c0647a30 00000000 c0695294
[ 28.606943] 1fe0: c0662488 c0647a2c c066619c 6000406a 413fc090 6000807c 00000000 00000000
[ 28.615127] [<c03af580>] (skb_put) from [<ef376520>] (0xef376520)
[ 28.621218] Code: e5902054 e590c090 e3520000 0a000000 (e7f001f2)
[ 28.627307] ---[ end trace 4824734e2243fdb6 ]---
[ 34.377068] Internal error: Oops: 17 [#1] SMP ARM
[ 34.382854] Modules linked in:
[ 34.385947] CPU: 0 PID: 3 Comm: ksoftirqd/0 Not tainted 4.4.0+ #120
[ 34.392219] Hardware name: Rockchip (Device Tree)
[ 34.396937] task: ef02d040 ti: ef05c000 task.ti: ef05c000
[ 34.402376] PC is at __dev_kfree_skb_irq+0x4/0x80
[ 34.407121] LR is at arc_emac_poll+0x130/0x474
[ 34.411583] pc : [<c03bb640>] lr : [<c028fd94>] psr: 60030013
[ 34.411583] sp : ef05de68 ip : 0008e83c fp : ef377000
[ 34.423062] r10: c001bec4 r9 : 00000000 r8 : f08b24c8
[ 34.428296] r7 : f08b2400 r6 : 00000075 r5 : 00000019 r4 : ef376000
[ 34.434827] r3 : 00060000 r2 : 00000042 r1 : 00000001 r0 : 00000000
[ 34.441365] Flags: nZCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none
[ 34.448507] Control: 10c5387d Table: 8f25c04a DAC: 00000051
[ 34.454262] Process ksoftirqd/0 (pid: 3, stack limit = 0xef05c210)
[ 34.460449] Stack: (0xef05de68 to 0xef05e000)
[ 34.464827] de60: ef376000 c028fd94 00000000 c0669480 c0669480 ef376520
[ 34.473022] de80: 00000028 00000001 00002ae4 ef376520 ef7b6900 c028fc64 2f158000 ef05dec0
[ 34.481215] dea0: ef05dec8 0000012c c065e900 c03bdeac ffff983f c0662100 c0663924 00000028
[ 34.489409] dec0: ef05dec0 ef05dec0 ef05dec8 ef05dec8 ef7b6000 ef05c000 40000003 00000008
[ 34.497600] dee0: c0695a00 0000000a c066208c 00000100 ef05def8 c0027410 ef7b6000 40000000
[ 34.505795] df00: 04208040 ffff983e 00000004 c0662100 c0662080 00000003 ef05c000 ef027340
[ 34.513985] df20: ef05c000 c0666c2c 00000000 00000001 00000002 00000000 00000000 c0027568
[ 34.522176] df40: ef027340 c003ef48 ef027300 00000000 ef027340 c003edd4 00000000 00000000
[ 34.530367] df60: 00000000 c003c37c ffffff7f 00000001 00000000 ef027340 00000000 00030003
[ 34.538559] df80: ef05df80 ef05df80 00000000 00000000 ef05df90 ef05df90 ef05dfac ef027300
[ 34.546750] dfa0: c003c2a4 00000000 00000000 c000f578 00000000 00000000 00000000 00000000
[ 34.554939] dfc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
[ 34.563129] dfe0: 00000000 00000000 00000000 00000000 00000013 00000000 ffffffff dfff7fff
[ 34.571360] [<c03bb640>] (__dev_kfree_skb_irq) from [<c028fd94>] (arc_emac_poll+0x130/0x474)
[ 34.579840] [<c028fd94>] (arc_emac_poll) from [<c03bdeac>] (net_rx_action+0xdc/0x28c)
[ 34.587712] [<c03bdeac>] (net_rx_action) from [<c0027410>] (__do_softirq+0xcc/0x1f8)
[ 34.595482] [<c0027410>] (__do_softirq) from [<c0027568>] (run_ksoftirqd+0x2c/0x50)
[ 34.603168] [<c0027568>] (run_ksoftirqd) from [<c003ef48>] (smpboot_thread_fn+0x174/0x18c)
[ 34.611466] [<c003ef48>] (smpboot_thread_fn) from [<c003c37c>] (kthread+0xd8/0xec)
[ 34.619075] [<c003c37c>] (kthread) from [<c000f578>] (ret_from_fork+0x14/0x3c)
[ 34.626317] Code: e8bd8010 e3a00000 e12fff1e e92d4010 (e59030a4)
[ 34.632572] ---[ end trace cca5a3d86a82249a ]---
Signed-off-by: Alexander Kochetkov <[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: MagickExport void *DetachBlob(BlobInfo *blob_info)
{
void
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
blob_info->custom_stream=(CustomStreamInfo *) NULL;
return(data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-399'], 'message': 'https://github.com/ImageMagick/ImageMagick6/issues/43'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: long WebPImage::getHeaderOffset(byte *data, long data_size,
byte *header, long header_size) {
long pos = -1;
for (long i=0; i < data_size - header_size; i++) {
if (memcmp(header, &data[i], header_size) == 0) {
pos = i;
break;
}
}
return pos;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Change WebpImage methods to use size_t'</s> |
<s>[INST] Given the following code containing errors, provide 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 Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const 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);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1552'</s> |
<s>[INST] Given the following code containing errors, provide 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 ieee802154_create(struct net *net, struct socket *sock,
int protocol, int kern)
{
struct sock *sk;
int rc;
struct proto *proto;
const struct proto_ops *ops;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
switch (sock->type) {
case SOCK_RAW:
proto = &ieee802154_raw_prot;
ops = &ieee802154_raw_ops;
break;
case SOCK_DGRAM:
proto = &ieee802154_dgram_prot;
ops = &ieee802154_dgram_ops;
break;
default:
rc = -ESOCKTNOSUPPORT;
goto out;
}
rc = -ENOMEM;
sk = sk_alloc(net, PF_IEEE802154, GFP_KERNEL, proto, kern);
if (!sk)
goto out;
rc = 0;
sock->ops = ops;
sock_init_data(sock, sk);
/* FIXME: sk->sk_destruct */
sk->sk_family = PF_IEEE802154;
/* Checksums on by default */
sock_set_flag(sk, SOCK_ZAPPED);
if (sk->sk_prot->hash) {
rc = sk->sk_prot->hash(sk);
if (rc) {
sk_common_release(sk);
goto out;
}
}
if (sk->sk_prot->init) {
rc = sk->sk_prot->init(sk);
if (rc)
sk_common_release(sk);
}
out:
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-276'], 'message': 'ieee802154: enforce CAP_NET_RAW for raw sockets
When creating a raw AF_IEEE802154 socket, CAP_NET_RAW needs to be
checked first.
Signed-off-by: Ori Nimron <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
Acked-by: Stefan Schmidt <[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: base_sock_create(struct net *net, struct socket *sock, int protocol, int kern)
{
struct sock *sk;
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto, kern);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &base_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = MISDN_OPEN;
mISDN_sock_link(&base_sockets, sk);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862'], 'message': 'mISDN: enforce CAP_NET_RAW for raw sockets
When creating a raw AF_ISDN socket, CAP_NET_RAW needs to be checked
first.
Signed-off-by: Ori Nimron <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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: S3BootScriptLabelInternal (
IN BOOLEAN BeforeOrAfter,
IN OUT VOID **Position OPTIONAL,
IN UINT32 InformationLength,
IN CONST CHAR8 *Information
)
{
UINT8 Length;
UINT8 *Script;
EFI_BOOT_SCRIPT_INFORMATION ScriptInformation;
Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_INFORMATION) + InformationLength);
Script = S3BootScriptGetEntryAddAddress (Length);
if (Script == NULL) {
return RETURN_OUT_OF_RESOURCES;
}
//
// Build script data
//
ScriptInformation.OpCode = S3_BOOT_SCRIPT_LIB_LABEL_OPCODE;
ScriptInformation.Length = Length;
ScriptInformation.InformationLength = InformationLength;
CopyMem ((VOID*)Script, (VOID*)&ScriptInformation, sizeof (EFI_BOOT_SCRIPT_INFORMATION));
CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION)), (VOID *) Information, (UINTN) InformationLength);
SyncBootScript (Script);
return S3BootScriptMoveLastOpcode (BeforeOrAfter, Position);
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/PiDxeS3BootScriptLib: Fix potential numeric truncation (CVE-2019-14563)
REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2001
For S3BootScriptLib APIs:
S3BootScriptSaveIoWrite
S3BootScriptSaveMemWrite
S3BootScriptSavePciCfgWrite
S3BootScriptSavePciCfg2Write
S3BootScriptSaveSmbusExecute
S3BootScriptSaveInformation
S3BootScriptSaveInformationAsciiString
S3BootScriptLabel (happen in S3BootScriptLabelInternal())
possible numeric truncations will happen that may lead to S3 boot script
entry with improper size being returned to store the boot script data.
This commit will add checks to prevent this kind of issue.
Please note that the remaining S3BootScriptLib APIs:
S3BootScriptSaveIoReadWrite
S3BootScriptSaveMemReadWrite
S3BootScriptSavePciCfgReadWrite
S3BootScriptSavePciCfg2ReadWrite
S3BootScriptSaveStall
S3BootScriptSaveDispatch2
S3BootScriptSaveDispatch
S3BootScriptSaveMemPoll
S3BootScriptSaveIoPoll
S3BootScriptSavePciPoll
S3BootScriptSavePci2Poll
S3BootScriptCloseTable
S3BootScriptExecute
S3BootScriptMoveLastOpcode
S3BootScriptCompare
are not affected by such numeric truncation.
Signed-off-by: Hao A Wu <[email protected]>
Reviewed-by: Laszlo Ersek <[email protected]>
Reviewed-by: Eric Dong <[email protected]>
Acked-by: Jian J 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: S3BootScriptSavePciCfg2Write (
IN S3_BOOT_SCRIPT_LIB_WIDTH Width,
IN UINT16 Segment,
IN UINT64 Address,
IN UINTN Count,
IN VOID *Buffer
)
{
UINT8 Length;
UINT8 *Script;
UINT8 WidthInByte;
EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE ScriptPciWrite2;
if (Width == S3BootScriptWidthUint64 ||
Width == S3BootScriptWidthFifoUint64 ||
Width == S3BootScriptWidthFillUint64) {
return EFI_INVALID_PARAMETER;
}
WidthInByte = (UINT8) (0x01 << (Width & 0x03));
Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE) + (WidthInByte * Count));
Script = S3BootScriptGetEntryAddAddress (Length);
if (Script == NULL) {
return RETURN_OUT_OF_RESOURCES;
}
//
// Build script data
//
ScriptPciWrite2.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE;
ScriptPciWrite2.Length = Length;
ScriptPciWrite2.Width = Width;
ScriptPciWrite2.Address = Address;
ScriptPciWrite2.Segment = Segment;
ScriptPciWrite2.Count = (UINT32)Count;
CopyMem ((VOID*)Script, (VOID*)&ScriptPciWrite2, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE));
CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)), Buffer, WidthInByte * Count);
SyncBootScript (Script);
return RETURN_SUCCESS;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/PiDxeS3BootScriptLib: Fix potential numeric truncation (CVE-2019-14563)
REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2001
For S3BootScriptLib APIs:
S3BootScriptSaveIoWrite
S3BootScriptSaveMemWrite
S3BootScriptSavePciCfgWrite
S3BootScriptSavePciCfg2Write
S3BootScriptSaveSmbusExecute
S3BootScriptSaveInformation
S3BootScriptSaveInformationAsciiString
S3BootScriptLabel (happen in S3BootScriptLabelInternal())
possible numeric truncations will happen that may lead to S3 boot script
entry with improper size being returned to store the boot script data.
This commit will add checks to prevent this kind of issue.
Please note that the remaining S3BootScriptLib APIs:
S3BootScriptSaveIoReadWrite
S3BootScriptSaveMemReadWrite
S3BootScriptSavePciCfgReadWrite
S3BootScriptSavePciCfg2ReadWrite
S3BootScriptSaveStall
S3BootScriptSaveDispatch2
S3BootScriptSaveDispatch
S3BootScriptSaveMemPoll
S3BootScriptSaveIoPoll
S3BootScriptSavePciPoll
S3BootScriptSavePci2Poll
S3BootScriptCloseTable
S3BootScriptExecute
S3BootScriptMoveLastOpcode
S3BootScriptCompare
are not affected by such numeric truncation.
Signed-off-by: Hao A Wu <[email protected]>
Reviewed-by: Laszlo Ersek <[email protected]>
Reviewed-by: Eric Dong <[email protected]>
Acked-by: Jian J 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: S3BootScriptSaveMemWrite (
IN S3_BOOT_SCRIPT_LIB_WIDTH Width,
IN UINT64 Address,
IN UINTN Count,
IN VOID *Buffer
)
{
UINT8 Length;
UINT8 *Script;
UINT8 WidthInByte;
EFI_BOOT_SCRIPT_MEM_WRITE ScriptMemWrite;
WidthInByte = (UINT8) (0x01 << (Width & 0x03));
Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_WRITE) + (WidthInByte * Count));
Script = S3BootScriptGetEntryAddAddress (Length);
if (Script == NULL) {
return RETURN_OUT_OF_RESOURCES;
}
//
// Build script data
//
ScriptMemWrite.OpCode = EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE;
ScriptMemWrite.Length = Length;
ScriptMemWrite.Width = Width;
ScriptMemWrite.Address = Address;
ScriptMemWrite.Count = (UINT32) Count;
CopyMem ((VOID*)Script, (VOID*)&ScriptMemWrite, sizeof(EFI_BOOT_SCRIPT_MEM_WRITE));
CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_WRITE)), Buffer, WidthInByte * Count);
SyncBootScript (Script);
return RETURN_SUCCESS;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/PiDxeS3BootScriptLib: Fix potential numeric truncation (CVE-2019-14563)
REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2001
For S3BootScriptLib APIs:
S3BootScriptSaveIoWrite
S3BootScriptSaveMemWrite
S3BootScriptSavePciCfgWrite
S3BootScriptSavePciCfg2Write
S3BootScriptSaveSmbusExecute
S3BootScriptSaveInformation
S3BootScriptSaveInformationAsciiString
S3BootScriptLabel (happen in S3BootScriptLabelInternal())
possible numeric truncations will happen that may lead to S3 boot script
entry with improper size being returned to store the boot script data.
This commit will add checks to prevent this kind of issue.
Please note that the remaining S3BootScriptLib APIs:
S3BootScriptSaveIoReadWrite
S3BootScriptSaveMemReadWrite
S3BootScriptSavePciCfgReadWrite
S3BootScriptSavePciCfg2ReadWrite
S3BootScriptSaveStall
S3BootScriptSaveDispatch2
S3BootScriptSaveDispatch
S3BootScriptSaveMemPoll
S3BootScriptSaveIoPoll
S3BootScriptSavePciPoll
S3BootScriptSavePci2Poll
S3BootScriptCloseTable
S3BootScriptExecute
S3BootScriptMoveLastOpcode
S3BootScriptCompare
are not affected by such numeric truncation.
Signed-off-by: Hao A Wu <[email protected]>
Reviewed-by: Laszlo Ersek <[email protected]>
Reviewed-by: Eric Dong <[email protected]>
Acked-by: Jian J 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: S3BootScriptSavePciCfgWrite (
IN S3_BOOT_SCRIPT_LIB_WIDTH Width,
IN UINT64 Address,
IN UINTN Count,
IN VOID *Buffer
)
{
UINT8 Length;
UINT8 *Script;
UINT8 WidthInByte;
EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE ScriptPciWrite;
if (Width == S3BootScriptWidthUint64 ||
Width == S3BootScriptWidthFifoUint64 ||
Width == S3BootScriptWidthFillUint64) {
return EFI_INVALID_PARAMETER;
}
WidthInByte = (UINT8) (0x01 << (Width & 0x03));
Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE) + (WidthInByte * Count));
Script = S3BootScriptGetEntryAddAddress (Length);
if (Script == NULL) {
return RETURN_OUT_OF_RESOURCES;
}
//
// Build script data
//
ScriptPciWrite.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE;
ScriptPciWrite.Length = Length;
ScriptPciWrite.Width = Width;
ScriptPciWrite.Address = Address;
ScriptPciWrite.Count = (UINT32) Count;
CopyMem ((VOID*)Script, (VOID*)&ScriptPciWrite, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE));
CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)), Buffer, WidthInByte * Count);
SyncBootScript (Script);
return RETURN_SUCCESS;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/PiDxeS3BootScriptLib: Fix potential numeric truncation (CVE-2019-14563)
REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2001
For S3BootScriptLib APIs:
S3BootScriptSaveIoWrite
S3BootScriptSaveMemWrite
S3BootScriptSavePciCfgWrite
S3BootScriptSavePciCfg2Write
S3BootScriptSaveSmbusExecute
S3BootScriptSaveInformation
S3BootScriptSaveInformationAsciiString
S3BootScriptLabel (happen in S3BootScriptLabelInternal())
possible numeric truncations will happen that may lead to S3 boot script
entry with improper size being returned to store the boot script data.
This commit will add checks to prevent this kind of issue.
Please note that the remaining S3BootScriptLib APIs:
S3BootScriptSaveIoReadWrite
S3BootScriptSaveMemReadWrite
S3BootScriptSavePciCfgReadWrite
S3BootScriptSavePciCfg2ReadWrite
S3BootScriptSaveStall
S3BootScriptSaveDispatch2
S3BootScriptSaveDispatch
S3BootScriptSaveMemPoll
S3BootScriptSaveIoPoll
S3BootScriptSavePciPoll
S3BootScriptSavePci2Poll
S3BootScriptCloseTable
S3BootScriptExecute
S3BootScriptMoveLastOpcode
S3BootScriptCompare
are not affected by such numeric truncation.
Signed-off-by: Hao A Wu <[email protected]>
Reviewed-by: Laszlo Ersek <[email protected]>
Reviewed-by: Eric Dong <[email protected]>
Acked-by: Jian J 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 int hclge_shaper_para_calc(u32 ir, u8 shaper_level,
u8 *ir_b, u8 *ir_u, u8 *ir_s)
{
#define DIVISOR_CLK (1000 * 8)
#define DIVISOR_IR_B_126 (126 * DIVISOR_CLK)
const u16 tick_array[HCLGE_SHAPER_LVL_CNT] = {
6 * 256, /* Prioriy level */
6 * 32, /* Prioriy group level */
6 * 8, /* Port level */
6 * 256 /* Qset level */
};
u8 ir_u_calc = 0;
u8 ir_s_calc = 0;
u32 ir_calc;
u32 tick;
/* Calc tick */
if (shaper_level >= HCLGE_SHAPER_LVL_CNT)
return -EINVAL;
tick = tick_array[shaper_level];
/**
* Calc the speed if ir_b = 126, ir_u = 0 and ir_s = 0
* the formula is changed to:
* 126 * 1 * 8
* ir_calc = ---------------- * 1000
* tick * 1
*/
ir_calc = (DIVISOR_IR_B_126 + (tick >> 1) - 1) / tick;
if (ir_calc == ir) {
*ir_b = 126;
*ir_u = 0;
*ir_s = 0;
return 0;
} else if (ir_calc > ir) {
/* Increasing the denominator to select ir_s value */
while (ir_calc > ir) {
ir_s_calc++;
ir_calc = DIVISOR_IR_B_126 / (tick * (1 << ir_s_calc));
}
if (ir_calc == ir)
*ir_b = 126;
else
*ir_b = (ir * tick * (1 << ir_s_calc) +
(DIVISOR_CLK >> 1)) / DIVISOR_CLK;
} else {
/* Increasing the numerator to select ir_u value */
u32 numerator;
while (ir_calc < ir) {
ir_u_calc++;
numerator = DIVISOR_IR_B_126 * (1 << ir_u_calc);
ir_calc = (numerator + (tick >> 1)) / tick;
}
if (ir_calc == ir) {
*ir_b = 126;
} else {
u32 denominator = (DIVISOR_CLK * (1 << --ir_u_calc));
*ir_b = (ir * tick + (denominator >> 1)) / denominator;
}
}
*ir_u = ir_u_calc;
*ir_s = ir_s_calc;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'net: hns3: add some error checking in hclge_tm module
When hdev->tx_sch_mode is HCLGE_FLAG_VNET_BASE_SCH_MODE, the
hclge_tm_schd_mode_vnet_base_cfg calls hclge_tm_pri_schd_mode_cfg
with vport->vport_id as pri_id, which is used as index for
hdev->tm_info.tc_info, it will cause out of bound access issue
if vport_id is equal to or larger than HNAE3_MAX_TC.
Also hardware only support maximum speed of HCLGE_ETHER_MAX_RATE.
So this patch adds two checks for above cases.
Fixes: 848440544b41 ("net: hns3: Add support of TX Scheduler & Shaper to HNS3 driver")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: Peng Li <[email protected]>
Signed-off-by: Huazhong Tan <[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 build_audio_procunit(struct mixer_build *state, int unitid,
void *raw_desc, struct procunit_info *list,
char *name)
{
struct uac_processing_unit_descriptor *desc = raw_desc;
int num_ins = desc->bNrInPins;
struct usb_mixer_elem_info *cval;
struct snd_kcontrol *kctl;
int i, err, nameid, type, len;
struct procunit_info *info;
struct procunit_value_info *valinfo;
const struct usbmix_name_map *map;
static struct procunit_value_info default_value_info[] = {
{ 0x01, "Switch", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_info default_info = {
0, NULL, default_value_info
};
if (desc->bLength < 13 || desc->bLength < 13 + num_ins ||
desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {
usb_audio_err(state->chip, "invalid %s descriptor (id %d)\n", name, unitid);
return -EINVAL;
}
for (i = 0; i < num_ins; i++) {
err = parse_audio_unit(state, desc->baSourceID[i]);
if (err < 0)
return err;
}
type = le16_to_cpu(desc->wProcessType);
for (info = list; info && info->type; info++)
if (info->type == type)
break;
if (!info || !info->type)
info = &default_info;
for (valinfo = info->values; valinfo->control; valinfo++) {
__u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
if (state->mixer->protocol == UAC_VERSION_1) {
if (!(controls[valinfo->control / 8] &
(1 << ((valinfo->control % 8) - 1))))
continue;
} else { /* UAC_VERSION_2/3 */
if (!uac_v2v3_control_is_readable(controls[valinfo->control / 8],
valinfo->control))
continue;
}
map = find_map(state->map, unitid, valinfo->control);
if (check_ignored_ctl(map))
continue;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (!cval)
return -ENOMEM;
snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
cval->control = valinfo->control;
cval->val_type = valinfo->val_type;
cval->channels = 1;
if (state->mixer->protocol > UAC_VERSION_1 &&
!uac_v2v3_control_is_writeable(controls[valinfo->control / 8],
valinfo->control))
cval->master_readonly = 1;
/* get min/max values */
switch (type) {
case UAC_PROCESS_UP_DOWNMIX: {
bool mode_sel = false;
switch (state->mixer->protocol) {
case UAC_VERSION_1:
case UAC_VERSION_2:
default:
if (cval->control == UAC_UD_MODE_SELECT)
mode_sel = true;
break;
case UAC_VERSION_3:
if (cval->control == UAC3_UD_MODE_SELECT)
mode_sel = true;
break;
}
if (mode_sel) {
__u8 *control_spec = uac_processing_unit_specific(desc,
state->mixer->protocol);
cval->min = 1;
cval->max = control_spec[0];
cval->res = 1;
cval->initialized = 1;
break;
}
get_min_max(cval, valinfo->min_value);
break;
}
case USB_XU_CLOCK_RATE:
/*
* E-Mu USB 0404/0202/TrackerPre/0204
* samplerate control quirk
*/
cval->min = 0;
cval->max = 5;
cval->res = 1;
cval->initialized = 1;
break;
default:
get_min_max(cval, valinfo->min_value);
break;
}
kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
if (!kctl) {
kfree(cval);
return -ENOMEM;
}
kctl->private_free = snd_usb_mixer_elem_free;
if (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name))) {
/* nothing */ ;
} else if (info->name) {
strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
} else {
nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
len = 0;
if (nameid)
len = snd_usb_copy_string_desc(state->chip,
nameid,
kctl->id.name,
sizeof(kctl->id.name));
if (!len)
strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
}
append_ctl_name(kctl, " ");
append_ctl_name(kctl, valinfo->suffix);
usb_audio_dbg(state->chip,
"[%d] PU [%s] ch = %d, val = %d/%d\n",
cval->head.id, kctl->id.name, cval->channels,
cval->min, cval->max);
err = snd_usb_mixer_add_control(&cval->head, kctl);
if (err < 0)
return err;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'ALSA: usb-audio: Avoid access before bLength check in build_audio_procunit()
The parser for the processing unit reads bNrInPins field before the
bLength sanity check, which may lead to an out-of-bound access when a
malformed descriptor is given. Fix it by assignment after the bLength
check.
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[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 giveup_all(struct task_struct *tsk)
{
unsigned long usermsr;
if (!tsk->thread.regs)
return;
usermsr = tsk->thread.regs->msr;
if ((usermsr & msr_all_available) == 0)
return;
msr_check_and_set(msr_all_available);
check_if_tm_restore_required(tsk);
WARN_ON((usermsr & MSR_VSX) && !((usermsr & MSR_FP) && (usermsr & MSR_VEC)));
#ifdef CONFIG_PPC_FPU
if (usermsr & MSR_FP)
__giveup_fpu(tsk);
#endif
#ifdef CONFIG_ALTIVEC
if (usermsr & MSR_VEC)
__giveup_altivec(tsk);
#endif
#ifdef CONFIG_SPE
if (usermsr & MSR_SPE)
__giveup_spe(tsk);
#endif
msr_check_and_clear(msr_all_available);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862'], 'message': 'powerpc/tm: Fix FP/VMX unavailable exceptions inside a transaction
When we take an FP unavailable exception in a transaction we have to
account for the hardware FP TM checkpointed registers being
incorrect. In this case for this process we know the current and
checkpointed FP registers must be the same (since FP wasn't used
inside the transaction) hence in the thread_struct we copy the current
FP registers to the checkpointed ones.
This copy is done in tm_reclaim_thread(). We use thread->ckpt_regs.msr
to determine if FP was on when in userspace. thread->ckpt_regs.msr
represents the state of the MSR when exiting userspace. This is setup
by check_if_tm_restore_required().
Unfortunatley there is an optimisation in giveup_all() which returns
early if tsk->thread.regs->msr (via local variable `usermsr`) has
FP=VEC=VSX=SPE=0. This optimisation means that
check_if_tm_restore_required() is not called and hence
thread->ckpt_regs.msr is not updated and will contain an old value.
This can happen if due to load_fp=255 we start a userspace process
with MSR FP=1 and then we are context switched out. In this case
thread->ckpt_regs.msr will contain FP=1. If that same process is then
context switched in and load_fp overflows, MSR will have FP=0. If that
process now enters a transaction and does an FP instruction, the FP
unavailable will not update thread->ckpt_regs.msr (the bug) and MSR
FP=1 will be retained in thread->ckpt_regs.msr. tm_reclaim_thread()
will then not perform the required memcpy and the checkpointed FP regs
in the thread struct will contain the wrong values.
The code path for this happening is:
Userspace: Kernel
Start userspace
with MSR FP/VEC/VSX/SPE=0 TM=1
< -----
...
tbegin
bne
fp instruction
FP unavailable
---- >
fp_unavailable_tm()
tm_reclaim_current()
tm_reclaim_thread()
giveup_all()
return early since FP/VMX/VSX=0
/* ckpt MSR not updated (Incorrect) */
tm_reclaim()
/* thread_struct ckpt FP regs contain junk (OK) */
/* Sees ckpt MSR FP=1 (Incorrect) */
no memcpy() performed
/* thread_struct ckpt FP regs not fixed (Incorrect) */
tm_recheckpoint()
/* Put junk in hardware checkpoint FP regs */
....
< -----
Return to userspace
with MSR TM=1 FP=1
with junk in the FP TM checkpoint
TM rollback
reads FP junk
This is a data integrity problem for the current process as the FP
registers are corrupted. It's also a security problem as the FP
registers from one process may be leaked to another.
This patch moves up check_if_tm_restore_required() in giveup_all() to
ensure thread->ckpt_regs.msr is updated correctly.
A simple testcase to replicate this will be posted to
tools/testing/selftests/powerpc/tm/tm-poison.c
Similarly for VMX.
This fixes CVE-2019-15030.
Fixes: f48e91e87e67 ("powerpc/tm: Fix FP and VMX register corruption")
Cc: [email protected] # 4.12+
Signed-off-by: Gustavo Romero <[email protected]>
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[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 hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2],
unsigned char multicast_spec, u8 protocol_version)
{
struct hsr_priv *hsr;
struct hsr_port *port;
int res;
hsr = netdev_priv(hsr_dev);
INIT_LIST_HEAD(&hsr->ports);
INIT_LIST_HEAD(&hsr->node_db);
INIT_LIST_HEAD(&hsr->self_node_db);
ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr);
/* Make sure we recognize frames from ourselves in hsr_rcv() */
res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr,
slave[1]->dev_addr);
if (res < 0)
return res;
spin_lock_init(&hsr->seqnr_lock);
/* Overflow soon to find bugs easier: */
hsr->sequence_nr = HSR_SEQNR_START;
hsr->sup_sequence_nr = HSR_SUP_SEQNR_START;
timer_setup(&hsr->announce_timer, hsr_announce, 0);
timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0);
ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr);
hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec;
hsr->protVersion = protocol_version;
/* FIXME: should I modify the value of these?
*
* - hsr_dev->flags - i.e.
* IFF_MASTER/SLAVE?
* - hsr_dev->priv_flags - i.e.
* IFF_EBRIDGE?
* IFF_TX_SKB_SHARING?
* IFF_HSR_MASTER/SLAVE?
*/
/* Make sure the 1st call to netif_carrier_on() gets through */
netif_carrier_off(hsr_dev);
res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER);
if (res)
return res;
res = register_netdevice(hsr_dev);
if (res)
goto fail;
res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A);
if (res)
goto fail;
res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B);
if (res)
goto fail;
mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD));
return 0;
fail:
hsr_for_each_port(hsr, port)
hsr_del_port(port);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772', 'CWE-269', 'CWE-401'], 'message': 'net: hsr: fix memory leak in hsr_dev_finalize()
If hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER) failed to
add port, it directly returns res and forgets to free the node
that allocated in hsr_create_self_node(), and forgets to delete
the node->mac_list linked in hsr->self_node_db.
BUG: memory leak
unreferenced object 0xffff8881cfa0c780 (size 64):
comm "syz-executor.0", pid 2077, jiffies 4294717969 (age 2415.377s)
hex dump (first 32 bytes):
e0 c7 a0 cf 81 88 ff ff 00 02 00 00 00 00 ad de ................
00 e6 49 cd 81 88 ff ff c0 9b 87 d0 81 88 ff ff ..I.............
backtrace:
[<00000000e2ff5070>] hsr_dev_finalize+0x736/0x960 [hsr]
[<000000003ed2e597>] hsr_newlink+0x2b2/0x3e0 [hsr]
[<000000003fa8c6b6>] __rtnl_newlink+0xf1f/0x1600 net/core/rtnetlink.c:3182
[<000000001247a7ad>] rtnl_newlink+0x66/0x90 net/core/rtnetlink.c:3240
[<00000000e7d1b61d>] rtnetlink_rcv_msg+0x54e/0xb90 net/core/rtnetlink.c:5130
[<000000005556bd3a>] netlink_rcv_skb+0x129/0x340 net/netlink/af_netlink.c:2477
[<00000000741d5ee6>] netlink_unicast_kernel net/netlink/af_netlink.c:1310 [inline]
[<00000000741d5ee6>] netlink_unicast+0x49a/0x650 net/netlink/af_netlink.c:1336
[<000000009d56f9b7>] netlink_sendmsg+0x88b/0xdf0 net/netlink/af_netlink.c:1917
[<0000000046b35c59>] sock_sendmsg_nosec net/socket.c:621 [inline]
[<0000000046b35c59>] sock_sendmsg+0xc3/0x100 net/socket.c:631
[<00000000d208adc9>] __sys_sendto+0x33e/0x560 net/socket.c:1786
[<00000000b582837a>] __do_sys_sendto net/socket.c:1798 [inline]
[<00000000b582837a>] __se_sys_sendto net/socket.c:1794 [inline]
[<00000000b582837a>] __x64_sys_sendto+0xdd/0x1b0 net/socket.c:1794
[<00000000c866801d>] do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
[<00000000fea382d9>] entry_SYSCALL_64_after_hwframe+0x49/0xbe
[<00000000e01dacb3>] 0xffffffffffffffff
Fixes: c5a759117210 ("net/hsr: Use list_head (and rcu) instead of array for slave devices.")
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: Mao Wenan <[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 inline bool tm_active_with_altivec(struct task_struct *tsk) { return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts
When in userspace and MSR FP=0 the hardware FP state is unrelated to
the current process. This is extended for transactions where if tbegin
is run with FP=0, the hardware checkpoint FP state will also be
unrelated to the current process. Due to this, we need to ensure this
hardware checkpoint is updated with the correct state before we enable
FP for this process.
Unfortunately we get this wrong when returning to a process from a
hardware interrupt. A process that starts a transaction with FP=0 can
take an interrupt. When the kernel returns back to that process, we
change to FP=1 but with hardware checkpoint FP state not updated. If
this transaction is then rolled back, the FP registers now contain the
wrong state.
The process looks like this:
Userspace: Kernel
Start userspace
with MSR FP=0 TM=1
< -----
...
tbegin
bne
Hardware interrupt
---- >
<do_IRQ...>
....
ret_from_except
restore_math()
/* sees FP=0 */
restore_fp()
tm_active_with_fp()
/* sees FP=1 (Incorrect) */
load_fp_state()
FP = 0 -> 1
< -----
Return to userspace
with MSR TM=1 FP=1
with junk in the FP TM checkpoint
TM rollback
reads FP junk
When returning from the hardware exception, tm_active_with_fp() is
incorrectly making restore_fp() call load_fp_state() which is setting
FP=1.
The fix is to remove tm_active_with_fp().
tm_active_with_fp() is attempting to handle the case where FP state
has been changed inside a transaction. In this case the checkpointed
and transactional FP state is different and hence we must restore the
FP state (ie. we can't do lazy FP restore inside a transaction that's
used FP). It's safe to remove tm_active_with_fp() as this case is
handled by restore_tm_state(). restore_tm_state() detects if FP has
been using inside a transaction and will set load_fp and call
restore_math() to ensure the FP state (checkpoint and transaction) is
restored.
This is a data integrity problem for the current process as the FP
registers are corrupted. It's also a security problem as the FP
registers from one process may be leaked to another.
Similarly for VMX.
A simple testcase to replicate this will be posted to
tools/testing/selftests/powerpc/tm/tm-poison.c
This fixes CVE-2019-15031.
Fixes: a7771176b439 ("powerpc: Don't enable FP/Altivec if not checkpointed")
Cc: [email protected] # 4.15+
Signed-off-by: Gustavo Romero <[email protected]>
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[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 restore_fp(struct task_struct *tsk)
{
if (tsk->thread.load_fp || tm_active_with_fp(tsk)) {
load_fp_state(¤t->thread.fp_state);
current->thread.load_fp++;
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts
When in userspace and MSR FP=0 the hardware FP state is unrelated to
the current process. This is extended for transactions where if tbegin
is run with FP=0, the hardware checkpoint FP state will also be
unrelated to the current process. Due to this, we need to ensure this
hardware checkpoint is updated with the correct state before we enable
FP for this process.
Unfortunately we get this wrong when returning to a process from a
hardware interrupt. A process that starts a transaction with FP=0 can
take an interrupt. When the kernel returns back to that process, we
change to FP=1 but with hardware checkpoint FP state not updated. If
this transaction is then rolled back, the FP registers now contain the
wrong state.
The process looks like this:
Userspace: Kernel
Start userspace
with MSR FP=0 TM=1
< -----
...
tbegin
bne
Hardware interrupt
---- >
<do_IRQ...>
....
ret_from_except
restore_math()
/* sees FP=0 */
restore_fp()
tm_active_with_fp()
/* sees FP=1 (Incorrect) */
load_fp_state()
FP = 0 -> 1
< -----
Return to userspace
with MSR TM=1 FP=1
with junk in the FP TM checkpoint
TM rollback
reads FP junk
When returning from the hardware exception, tm_active_with_fp() is
incorrectly making restore_fp() call load_fp_state() which is setting
FP=1.
The fix is to remove tm_active_with_fp().
tm_active_with_fp() is attempting to handle the case where FP state
has been changed inside a transaction. In this case the checkpointed
and transactional FP state is different and hence we must restore the
FP state (ie. we can't do lazy FP restore inside a transaction that's
used FP). It's safe to remove tm_active_with_fp() as this case is
handled by restore_tm_state(). restore_tm_state() detects if FP has
been using inside a transaction and will set load_fp and call
restore_math() to ensure the FP state (checkpoint and transaction) is
restored.
This is a data integrity problem for the current process as the FP
registers are corrupted. It's also a security problem as the FP
registers from one process may be leaked to another.
Similarly for VMX.
A simple testcase to replicate this will be posted to
tools/testing/selftests/powerpc/tm/tm-poison.c
This fixes CVE-2019-15031.
Fixes: a7771176b439 ("powerpc: Don't enable FP/Altivec if not checkpointed")
Cc: [email protected] # 4.15+
Signed-off-by: Gustavo Romero <[email protected]>
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[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 restore_altivec(struct task_struct *tsk)
{
if (cpu_has_feature(CPU_FTR_ALTIVEC) &&
(tsk->thread.load_vec || tm_active_with_altivec(tsk))) {
load_vr_state(&tsk->thread.vr_state);
tsk->thread.used_vr = 1;
tsk->thread.load_vec++;
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts
When in userspace and MSR FP=0 the hardware FP state is unrelated to
the current process. This is extended for transactions where if tbegin
is run with FP=0, the hardware checkpoint FP state will also be
unrelated to the current process. Due to this, we need to ensure this
hardware checkpoint is updated with the correct state before we enable
FP for this process.
Unfortunately we get this wrong when returning to a process from a
hardware interrupt. A process that starts a transaction with FP=0 can
take an interrupt. When the kernel returns back to that process, we
change to FP=1 but with hardware checkpoint FP state not updated. If
this transaction is then rolled back, the FP registers now contain the
wrong state.
The process looks like this:
Userspace: Kernel
Start userspace
with MSR FP=0 TM=1
< -----
...
tbegin
bne
Hardware interrupt
---- >
<do_IRQ...>
....
ret_from_except
restore_math()
/* sees FP=0 */
restore_fp()
tm_active_with_fp()
/* sees FP=1 (Incorrect) */
load_fp_state()
FP = 0 -> 1
< -----
Return to userspace
with MSR TM=1 FP=1
with junk in the FP TM checkpoint
TM rollback
reads FP junk
When returning from the hardware exception, tm_active_with_fp() is
incorrectly making restore_fp() call load_fp_state() which is setting
FP=1.
The fix is to remove tm_active_with_fp().
tm_active_with_fp() is attempting to handle the case where FP state
has been changed inside a transaction. In this case the checkpointed
and transactional FP state is different and hence we must restore the
FP state (ie. we can't do lazy FP restore inside a transaction that's
used FP). It's safe to remove tm_active_with_fp() as this case is
handled by restore_tm_state(). restore_tm_state() detects if FP has
been using inside a transaction and will set load_fp and call
restore_math() to ensure the FP state (checkpoint and transaction) is
restored.
This is a data integrity problem for the current process as the FP
registers are corrupted. It's also a security problem as the FP
registers from one process may be leaked to another.
Similarly for VMX.
A simple testcase to replicate this will be posted to
tools/testing/selftests/powerpc/tm/tm-poison.c
This fixes CVE-2019-15031.
Fixes: a7771176b439 ("powerpc: Don't enable FP/Altivec if not checkpointed")
Cc: [email protected] # 4.15+
Signed-off-by: Gustavo Romero <[email protected]>
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[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 int restore_altivec(struct task_struct *tsk) { return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts
When in userspace and MSR FP=0 the hardware FP state is unrelated to
the current process. This is extended for transactions where if tbegin
is run with FP=0, the hardware checkpoint FP state will also be
unrelated to the current process. Due to this, we need to ensure this
hardware checkpoint is updated with the correct state before we enable
FP for this process.
Unfortunately we get this wrong when returning to a process from a
hardware interrupt. A process that starts a transaction with FP=0 can
take an interrupt. When the kernel returns back to that process, we
change to FP=1 but with hardware checkpoint FP state not updated. If
this transaction is then rolled back, the FP registers now contain the
wrong state.
The process looks like this:
Userspace: Kernel
Start userspace
with MSR FP=0 TM=1
< -----
...
tbegin
bne
Hardware interrupt
---- >
<do_IRQ...>
....
ret_from_except
restore_math()
/* sees FP=0 */
restore_fp()
tm_active_with_fp()
/* sees FP=1 (Incorrect) */
load_fp_state()
FP = 0 -> 1
< -----
Return to userspace
with MSR TM=1 FP=1
with junk in the FP TM checkpoint
TM rollback
reads FP junk
When returning from the hardware exception, tm_active_with_fp() is
incorrectly making restore_fp() call load_fp_state() which is setting
FP=1.
The fix is to remove tm_active_with_fp().
tm_active_with_fp() is attempting to handle the case where FP state
has been changed inside a transaction. In this case the checkpointed
and transactional FP state is different and hence we must restore the
FP state (ie. we can't do lazy FP restore inside a transaction that's
used FP). It's safe to remove tm_active_with_fp() as this case is
handled by restore_tm_state(). restore_tm_state() detects if FP has
been using inside a transaction and will set load_fp and call
restore_math() to ensure the FP state (checkpoint and transaction) is
restored.
This is a data integrity problem for the current process as the FP
registers are corrupted. It's also a security problem as the FP
registers from one process may be leaked to another.
Similarly for VMX.
A simple testcase to replicate this will be posted to
tools/testing/selftests/powerpc/tm/tm-poison.c
This fixes CVE-2019-15031.
Fixes: a7771176b439 ("powerpc: Don't enable FP/Altivec if not checkpointed")
Cc: [email protected] # 4.15+
Signed-off-by: Gustavo Romero <[email protected]>
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[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: rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|dao-truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
ND_TCHECK(cp[0]);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rpl_dio_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp;
const char *dagid_str;
ND_TCHECK(*dio);
dagid_str = ip6addr_string (ndo, dio->rpl_dagid);
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]",
dagid_str,
dio->rpl_dtsn,
dio->rpl_instanceid,
EXTRACT_16BITS(&dio->rpl_dagrank),
RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"",
tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)),
RPL_DIO_PRF(dio->rpl_mopprf)));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1];
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': '(for 4.9.3) CVE-2018-16300/BGP: prevent stack exhaustion
Enforce a limit on how many times bgp_attr_print() can recurse.
This fixes a stack exhaustion discovered by Include Security working
under the Mozilla SOS program in 2018 by means of code audit.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
if (cp == NULL) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14469/ISAKMP: Add a missing bounds check
In ikev1_n_print() check bounds before trying to fetch the replay detection
status.
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: vrrp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len,
register const u_char *bp2, int ttl)
{
int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */
const char *type_s;
ND_TCHECK(bp[0]);
version = (bp[0] & 0xf0) >> 4;
type = bp[0] & 0x0f;
type_s = tok2str(type2str, "unknown type (%u)", type);
ND_PRINT((ndo, "VRRPv%u, %s", version, type_s));
if (ttl != 255)
ND_PRINT((ndo, ", (ttl %u)", ttl));
if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT)
return;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2]));
ND_TCHECK(bp[5]);
if (version == 2) {
auth_type = bp[4];
ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type)));
ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len));
} else { /* version == 3 */
uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5];
ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len));
}
if (ndo->ndo_vflag) {
int naddrs = bp[3];
int i;
char c;
if (version == 2 && ND_TTEST2(bp[0], len)) {
struct cksum_vec vec[1];
vec[0].ptr = bp;
vec[0].len = len;
if (in_cksum(vec, 1))
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
if (version == 3 && ND_TTEST2(bp[0], len)) {
uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp,
len, len, IPPROTO_VRRP);
if (cksum)
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
ND_PRINT((ndo, ", addrs"));
if (naddrs > 1)
ND_PRINT((ndo, "(%d)", naddrs));
ND_PRINT((ndo, ":"));
c = ' ';
bp += 8;
for (i = 0; i < naddrs; i++) {
ND_TCHECK(bp[3]);
ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp)));
c = ',';
bp += 4;
}
if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */
ND_TCHECK(bp[7]);
ND_PRINT((ndo, " auth \""));
if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
}
}
return;
trunc:
ND_PRINT((ndo, "[|vrrp]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14463/VRRP: Add a missing bounds check
In vrrp_print().
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: get_next_file(FILE *VFile, char *ptr)
{
char *ret;
ret = fgets(ptr, PATH_MAX, VFile);
if (!ret)
return NULL;
if (ptr[strlen(ptr) - 1] == '\n')
ptr[strlen(ptr) - 1] = '\0';
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': '(for 4.9.3) CVE-2018-14879/fix -V to fail invalid input safely
get_next_file() did not check the return value of strlen() and
underflowed an array index if the line read by fgets() from the file
started with \0. This caused an out-of-bounds read and could cause a
write. Add the missing check.
This vulnerability was discovered by Brian Carpenter & Geeknik Labs.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-16227/IEEE 802.11: add a missing bounds check
ieee802_11_print() tried to access the Mesh Flags subfield of the Mesh
Control field to find the size of the latter and increment the expected
802.11 header length before checking it is fully present in the input
buffer. Add an intermediate bounds check to make it safe.
This fixes a buffer over-read discovered by Ryan Ackroyd.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mfr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int tlen,idx,hdr_len = 0;
uint16_t sequence_num;
uint8_t ie_type,ie_len;
const uint8_t *tptr;
/*
* FRF.16 Link Integrity Control Frame
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | B | E | C=1| 0 0 0 0 | EA |
* +----+----+----+----+----+----+----+----+
* | 0 0 0 0 0 0 0 0 |
* +----+----+----+----+----+----+----+----+
* | message type |
* +----+----+----+----+----+----+----+----+
*/
ND_TCHECK2(*p, 4); /* minimum frame header length */
if ((p[0] & MFR_BEC_MASK) == MFR_CTRL_FRAME && p[1] == 0) {
ND_PRINT((ndo, "FRF.16 Control, Flags [%s], %s, length %u",
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK)),
tok2str(mfr_ctrl_msg_values,"Unknown Message (0x%02x)",p[2]),
length));
tptr = p + 3;
tlen = length -3;
hdr_len = 3;
if (!ndo->ndo_vflag)
return hdr_len;
while (tlen>sizeof(struct ie_tlv_header_t)) {
ND_TCHECK2(*tptr, sizeof(struct ie_tlv_header_t));
ie_type=tptr[0];
ie_len=tptr[1];
ND_PRINT((ndo, "\n\tIE %s (%u), length %u: ",
tok2str(mfr_ctrl_ie_values,"Unknown",ie_type),
ie_type,
ie_len));
/* infinite loop check */
if (ie_type == 0 || ie_len <= sizeof(struct ie_tlv_header_t))
return hdr_len;
ND_TCHECK2(*tptr, ie_len);
tptr+=sizeof(struct ie_tlv_header_t);
/* tlv len includes header */
ie_len-=sizeof(struct ie_tlv_header_t);
tlen-=sizeof(struct ie_tlv_header_t);
switch (ie_type) {
case MFR_CTRL_IE_MAGIC_NUM:
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(tptr)));
break;
case MFR_CTRL_IE_BUNDLE_ID: /* same message format */
case MFR_CTRL_IE_LINK_ID:
for (idx = 0; idx < ie_len && idx < MFR_ID_STRING_MAXLEN; idx++) {
if (*(tptr+idx) != 0) /* don't print null termination */
safeputchar(ndo, *(tptr + idx));
else
break;
}
break;
case MFR_CTRL_IE_TIMESTAMP:
if (ie_len == sizeof(struct timeval)) {
ts_print(ndo, (const struct timeval *)tptr);
break;
}
/* fall through and hexdump if no unix timestamp */
/*
* FIXME those are the defined IEs that lack a decoder
* you are welcome to contribute code ;-)
*/
case MFR_CTRL_IE_VENDOR_EXT:
case MFR_CTRL_IE_CAUSE:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", ie_len);
break;
}
/* do we want to see a hexdump of the IE ? */
if (ndo->ndo_vflag > 1 )
print_unknown_data(ndo, tptr, "\n\t ", ie_len);
tlen-=ie_len;
tptr+=ie_len;
}
return hdr_len;
}
/*
* FRF.16 Fragmentation Frame
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | B | E | C=0|seq. (high 4 bits) | EA |
* +----+----+----+----+----+----+----+----+
* | sequence (low 8 bits) |
* +----+----+----+----+----+----+----+----+
* | DLCI (6 bits) | CR | EA |
* +----+----+----+----+----+----+----+----+
* | DLCI (4 bits) |FECN|BECN| DE | EA |
* +----+----+----+----+----+----+----+----+
*/
sequence_num = (p[0]&0x1e)<<7 | p[1];
/* whole packet or first fragment ? */
if ((p[0] & MFR_BEC_MASK) == MFR_FRAG_FRAME ||
(p[0] & MFR_BEC_MASK) == MFR_B_BIT) {
ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s], ",
sequence_num,
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK))));
hdr_len = 2;
fr_print(ndo, p+hdr_len,length-hdr_len);
return hdr_len;
}
/* must be a middle or the last fragment */
ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s]",
sequence_num,
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK))));
print_unknown_data(ndo, p, "\n\t", length);
return hdr_len;
trunc:
ND_PRINT((ndo, "[|mfr]"));
return length;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14468/FRF.16: Add a missing length check.
The specification says in a well-formed Magic Number information element
the data is exactly 4 bytes long. In mfr_print() check this before trying
to read those 4 bytes.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ldp_pdu_print(netdissect_options *ndo,
register const u_char *pptr)
{
const struct ldp_common_header *ldp_com_header;
const struct ldp_msg_header *ldp_msg_header;
const u_char *tptr,*msg_tptr;
u_short tlen;
u_short pdu_len,msg_len,msg_type,msg_tlen;
int hexdump,processed;
ldp_com_header = (const struct ldp_common_header *)pptr;
ND_TCHECK(*ldp_com_header);
/*
* Sanity checking of the header.
*/
if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) {
ND_PRINT((ndo, "%sLDP version %u packet not supported",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
EXTRACT_16BITS(&ldp_com_header->version)));
return 0;
}
pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length);
if (pdu_len < sizeof(const struct ldp_common_header)-4) {
/* length too short */
ND_PRINT((ndo, "%sLDP, pdu-length: %u (too short, < %u)",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
pdu_len,
(u_int)(sizeof(const struct ldp_common_header)-4)));
return 0;
}
/* print the LSR-ID, label-space & length */
ND_PRINT((ndo, "%sLDP, Label-Space-ID: %s:%u, pdu-length: %u",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
ipaddr_string(ndo, &ldp_com_header->lsr_id),
EXTRACT_16BITS(&ldp_com_header->label_space),
pdu_len));
/* bail out if non-verbose */
if (ndo->ndo_vflag < 1)
return 0;
/* ok they seem to want to know everything - lets fully decode it */
tptr = pptr + sizeof(const struct ldp_common_header);
tlen = pdu_len - (sizeof(const struct ldp_common_header)-4); /* Type & Length fields not included */
while(tlen>0) {
/* did we capture enough for fully decoding the msg header ? */
ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header));
ldp_msg_header = (const struct ldp_msg_header *)tptr;
msg_len=EXTRACT_16BITS(ldp_msg_header->length);
msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type));
if (msg_len < sizeof(struct ldp_msg_header)-4) {
/* length too short */
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u (too short, < %u)",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
(u_int)(sizeof(struct ldp_msg_header)-4)));
return 0;
}
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
EXTRACT_32BITS(&ldp_msg_header->id),
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? "continue processing" : "ignore"));
msg_tptr=tptr+sizeof(struct ldp_msg_header);
msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */
/* did we capture enough for fully decoding the message ? */
ND_TCHECK2(*tptr, msg_len);
hexdump=FALSE;
switch(msg_type) {
case LDP_MSG_NOTIF:
case LDP_MSG_HELLO:
case LDP_MSG_INIT:
case LDP_MSG_KEEPALIVE:
case LDP_MSG_ADDRESS:
case LDP_MSG_LABEL_MAPPING:
case LDP_MSG_ADDRESS_WITHDRAW:
case LDP_MSG_LABEL_WITHDRAW:
while(msg_tlen >= 4) {
processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen);
if (processed == 0)
break;
msg_tlen-=processed;
msg_tptr+=processed;
}
break;
/*
* FIXME those are the defined messages that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_MSG_LABEL_REQUEST:
case LDP_MSG_LABEL_RELEASE:
case LDP_MSG_LABEL_ABORT_REQUEST:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, msg_tptr, "\n\t ", msg_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), "\n\t ",
msg_len);
tptr += msg_len+4;
tlen -= msg_len+4;
}
return pdu_len+4;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14461/LDP: Fix a bounds check
In ldp_tlv_print(), the FT Session TLV length must be 12, not 8 (RFC3479)
This fixes a buffer over-read discovered by Konrad Rieck and
Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
Moreover:
Add and use tstr[].
Add a comment.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump;
u_int offset;
u_int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
if (tlen < sizeof(const struct lmp_common_header)) {
ND_PRINT((ndo, " (too short)"));
return;
}
if (tlen > len) {
ND_PRINT((ndo, " (too long)"));
tlen = len;
}
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
if (lmp_obj_len < 4) {
ND_PRINT((ndo, " (too short)"));
return;
}
if ((lmp_obj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
return;
}
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
if (obj_tlen != 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
break;
case LMP_CTYPE_UNMD:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)"
"\n\t Remote Link-ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))
hexdump=TRUE;
break;
case LMP_CTYPE_IPV6:
if (obj_tlen < 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36))
hexdump=TRUE;
break;
case LMP_CTYPE_UNMD:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)"
"\n\t Remote Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))
hexdump=TRUE;
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 20) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
/* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */
while (offset+20 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF));
offset+=20;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
while (offset+16 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=16;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
link_type = EXTRACT_8BITS(obj_tptr);
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
switch (link_type) {
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 2))));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 7))));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check
In lmp_print_data_link_subobjs().
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rx_cache_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = EXTRACT_32BITS(&rxh->callNumber);
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId);
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14466/Rx: fix an over-read bug
In rx_cache_insert() and rx_cache_find() properly read the serviceId
field of the rx_header structure as a 16-bit integer. When those
functions tried to read 32 bits the extra 16 bits could be outside of
the bounds checked in rx_print() for the rx_header structure, as
serviceId is the last field in that structure.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14467/BGP: Fix BGP_CAPCODE_MP.
Add a bounds check and a comment to bgp_capabilities_print().
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length)
{
int plenbytes;
char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")];
if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 &&
is_ipv4_mapped_address(&prefix[1])) {
struct in_addr addr;
u_int plen;
plen = prefix[0]-96;
if (32 < plen)
return -1;
max_length -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN)
return -3;
memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen);
plenbytes += 1 + IPV4_MAPPED_HEADING_LEN;
} else {
plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf));
}
ND_PRINT((ndo, "%s", buf));
return plenbytes;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-16228/HNCP: make buffer access safer
print_prefix() has a buffer and does not initialize it. It may call
decode_prefix6(), which also does not initialize the buffer on invalid
input. When that happens, make sure to return from print_prefix() before
trying to print the [still uninitialized] buffer.
This fixes a buffer over-read discovered by Wang Junjie of 360 ESG
Codesafe Team.
Add a test using the capture file supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: print_trans(netdissect_options *ndo,
const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)
{
u_int bcc;
const char *f1, *f2, *f3, *f4;
const u_char *data, *param;
const u_char *w = words + 1;
int datalen, paramlen;
if (request) {
ND_TCHECK2(w[12 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 9 * 2);
param = buf + EXTRACT_LE_16BITS(w + 10 * 2);
datalen = EXTRACT_LE_16BITS(w + 11 * 2);
data = buf + EXTRACT_LE_16BITS(w + 12 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n";
f2 = "|Name=[S]\n";
f3 = "|Param ";
f4 = "|Data ";
} else {
ND_TCHECK2(w[7 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 3 * 2);
param = buf + EXTRACT_LE_16BITS(w + 4 * 2);
datalen = EXTRACT_LE_16BITS(w + 6 * 2);
data = buf + EXTRACT_LE_16BITS(w + 7 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n";
f2 = "|Unknown ";
f3 = "|Param ";
f4 = "|Data ";
}
smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),
unicodestr);
ND_TCHECK2(*data1, 2);
bcc = EXTRACT_LE_16BITS(data1);
ND_PRINT((ndo, "smb_bcc=%u\n", bcc));
if (bcc > 0) {
smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);
if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) {
print_browse(ndo, param, paramlen, data, datalen);
return;
}
if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) {
print_ipc(ndo, param, paramlen, data, datalen);
return;
}
if (paramlen)
smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);
if (datalen)
smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) SMB: Add two missing bounds checks'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,
int total_subobj_len, int offset)
{
int hexdump = FALSE;
int subobj_type, subobj_len;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_8BITS(obj_tptr + offset);
subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
if (subobj_len < 4) {
ND_PRINT((ndo, " (too short)"));
break;
}
if ((subobj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
break;
}
if (total_subobj_len < subobj_len) {
ND_PRINT((ndo, " (goes past the end of the object)"));
break;
}
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 2)),
EXTRACT_8BITS(obj_tptr + offset + 2)));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 3)),
EXTRACT_8BITS(obj_tptr + offset + 3)));
ND_TCHECK_32BITS(obj_tptr + offset + 4);
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
return (hexdump);
trunc:
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-120', 'CWE-119', 'CWE-787'], 'message': '(for 4.9.3) LMP: Add some missing bounds checks
In lmp_print_data_link_subobjs(), these problems were identified
through code review.
Moreover:
Add and use tstr[].
Update two tests outputs accordingly.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
{
struct smb_rqst rqst;
struct smb2_negotiate_req *req;
struct smb2_negotiate_rsp *rsp;
struct kvec iov[1];
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
struct TCP_Server_Info *server = ses->server;
int blob_offset, blob_length;
char *security_blob;
int flags = CIFS_NEG_OP;
unsigned int total_len;
cifs_dbg(FYI, "Negotiate protocol\n");
if (!server) {
WARN(1, "%s: server is NULL!\n", __func__);
return -EIO;
}
rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len);
if (rc)
return rc;
req->sync_hdr.SessionId = 0;
memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
if (strcmp(ses->server->vals->version_string,
SMB3ANY_VERSION_STRING) == 0) {
req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
req->DialectCount = cpu_to_le16(2);
total_len += 4;
} else if (strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0) {
req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
req->DialectCount = cpu_to_le16(4);
total_len += 8;
} else {
/* otherwise send specific dialect */
req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
req->DialectCount = cpu_to_le16(1);
total_len += 2;
}
/* only one of SMB2 signing flags may be set in SMB2 request */
if (ses->sign)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
else if (global_secflags & CIFSSEC_MAY_SIGN)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
else
req->SecurityMode = 0;
req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
/* ClientGUID must be zero for SMB2.02 dialect */
if (ses->server->vals->protocol_id == SMB20_PROT_ID)
memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
else {
memcpy(req->ClientGUID, server->client_guid,
SMB2_CLIENT_GUID_SIZE);
if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
(strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0))
assemble_neg_contexts(req, &total_len);
}
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
/*
* No tcon so can't do
* cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
*/
if (rc == -EOPNOTSUPP) {
cifs_dbg(VFS, "Dialect not supported by server. Consider "
"specifying vers=1.0 or vers=2.0 on mount for accessing"
" older servers\n");
goto neg_exit;
} else if (rc != 0)
goto neg_exit;
if (strcmp(ses->server->vals->version_string,
SMB3ANY_VERSION_STRING) == 0) {
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
cifs_dbg(VFS,
"SMB2 dialect returned but not requested\n");
return -EIO;
} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
cifs_dbg(VFS,
"SMB2.1 dialect returned but not requested\n");
return -EIO;
}
} else if (strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0) {
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
cifs_dbg(VFS,
"SMB2 dialect returned but not requested\n");
return -EIO;
} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
/* ops set to 3.0 by default for default so update */
ses->server->ops = &smb21_operations;
} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
ses->server->ops = &smb311_operations;
} else if (le16_to_cpu(rsp->DialectRevision) !=
ses->server->vals->protocol_id) {
/* if requested single dialect ensure returned dialect matched */
cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
le16_to_cpu(rsp->DialectRevision));
return -EIO;
}
cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
else {
cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
le16_to_cpu(rsp->DialectRevision));
rc = -EIO;
goto neg_exit;
}
server->dialect = le16_to_cpu(rsp->DialectRevision);
/*
* Keep a copy of the hash after negprot. This hash will be
* the starting hash value for all sessions made from this
* server.
*/
memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
SMB2_PREAUTH_HASH_SIZE);
/* SMB2 only has an extended negflavor */
server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
/* set it to the maximum buffer size value we can send with 1 credit */
server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
SMB2_MAX_BUFFER_SIZE);
server->max_read = le32_to_cpu(rsp->MaxReadSize);
server->max_write = le32_to_cpu(rsp->MaxWriteSize);
server->sec_mode = le16_to_cpu(rsp->SecurityMode);
if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
server->sec_mode);
server->capabilities = le32_to_cpu(rsp->Capabilities);
/* Internal types */
server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
(struct smb2_sync_hdr *)rsp);
/*
* See MS-SMB2 section 2.2.4: if no blob, client picks default which
* for us will be
* ses->sectype = RawNTLMSSP;
* but for time being this is our only auth choice so doesn't matter.
* We just found a server which sets blob length to zero expecting raw.
*/
if (blob_length == 0) {
cifs_dbg(FYI, "missing security blob on negprot\n");
server->sec_ntlmssp = true;
}
rc = cifs_enable_signing(server, ses->sign);
if (rc)
goto neg_exit;
if (blob_length) {
rc = decode_negTokenInit(security_blob, blob_length, server);
if (rc == 1)
rc = 0;
else if (rc == 0)
rc = -EIO;
}
if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
if (rsp->NegotiateContextCount)
rc = smb311_decode_neg_context(rsp, server,
rsp_iov.iov_len);
else
cifs_dbg(VFS, "Missing expected negotiate contexts\n");
}
neg_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'cifs: Fix lease buffer length error
There is a KASAN slab-out-of-bounds:
BUG: KASAN: slab-out-of-bounds in _copy_from_iter_full+0x783/0xaa0
Read of size 80 at addr ffff88810c35e180 by task mount.cifs/539
CPU: 1 PID: 539 Comm: mount.cifs Not tainted 4.19 #10
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
rel-1.12.0-0-ga698c8995f-prebuilt.qemu.org 04/01/2014
Call Trace:
dump_stack+0xdd/0x12a
print_address_description+0xa7/0x540
kasan_report+0x1ff/0x550
check_memory_region+0x2f1/0x310
memcpy+0x2f/0x80
_copy_from_iter_full+0x783/0xaa0
tcp_sendmsg_locked+0x1840/0x4140
tcp_sendmsg+0x37/0x60
inet_sendmsg+0x18c/0x490
sock_sendmsg+0xae/0x130
smb_send_kvec+0x29c/0x520
__smb_send_rqst+0x3ef/0xc60
smb_send_rqst+0x25a/0x2e0
compound_send_recv+0x9e8/0x2af0
cifs_send_recv+0x24/0x30
SMB2_open+0x35e/0x1620
open_shroot+0x27b/0x490
smb2_open_op_close+0x4e1/0x590
smb2_query_path_info+0x2ac/0x650
cifs_get_inode_info+0x1058/0x28f0
cifs_root_iget+0x3bb/0xf80
cifs_smb3_do_mount+0xe00/0x14c0
cifs_do_mount+0x15/0x20
mount_fs+0x5e/0x290
vfs_kern_mount+0x88/0x460
do_mount+0x398/0x31e0
ksys_mount+0xc6/0x150
__x64_sys_mount+0xea/0x190
do_syscall_64+0x122/0x590
entry_SYSCALL_64_after_hwframe+0x44/0xa9
It can be reproduced by the following step:
1. samba configured with: server max protocol = SMB2_10
2. mount -o vers=default
When parse the mount version parameter, the 'ops' and 'vals'
was setted to smb30, if negotiate result is smb21, just
update the 'ops' to smb21, but the 'vals' is still smb30.
When add lease context, the iov_base is allocated with smb21
ops, but the iov_len is initiallited with the smb30. Because
the iov_len is longer than iov_base, when send the message,
copy array out of bounds.
we need to keep the 'ops' and 'vals' consistent.
Fixes: 9764c02fcbad ("SMB3: Add support for multidialect negotiate (SMB2.1 and later)")
Fixes: d5c7076b772a ("smb3: add smb3.1.1 to default dialect list")
Signed-off-by: ZhangXiaoxu <[email protected]>
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]>
Reviewed-by: Pavel Shilovsky <[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 apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,
char **err_str, char **err_desc) {
apr_uri_t uri;
const char *c_host = NULL;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc = apr_psprintf(r->pool, "Logout URL malformed: %s", url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if (strstr(url, "/") != url) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-601'], 'message': '2.4.0.2 oops
Signed-off-by: Hans Zandbelt <[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: pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,
char *errbuf, int *err)
{
bpf_u_int32 magic_int;
size_t amt_read;
bpf_u_int32 total_length;
bpf_u_int32 byte_order_magic;
struct block_header *bhdrp;
struct section_header_block *shbp;
pcap_t *p;
int swapped = 0;
struct pcap_ng_sf *ps;
int status;
struct block_cursor cursor;
struct interface_description_block *idbp;
/*
* Assume no read errors.
*/
*err = 0;
/*
* Check whether the first 4 bytes of the file are the block
* type for a pcapng savefile.
*/
memcpy(&magic_int, magic, sizeof(magic_int));
if (magic_int != BT_SHB) {
/*
* XXX - check whether this looks like what the block
* type would be after being munged by mapping between
* UN*X and DOS/Windows text file format and, if it
* does, look for the byte-order magic number in
* the appropriate place and, if we find it, report
* this as possibly being a pcapng file transferred
* between UN*X and Windows in text file format?
*/
return (NULL); /* nope */
}
/*
* OK, they are. However, that's just \n\r\r\n, so it could,
* conceivably, be an ordinary text file.
*
* It could not, however, conceivably be any other type of
* capture file, so we can read the rest of the putative
* Section Header Block; put the block type in the common
* header, read the rest of the common header and the
* fixed-length portion of the SHB, and look for the byte-order
* magic value.
*/
amt_read = fread(&total_length, 1, sizeof(total_length), fp);
if (amt_read < sizeof(total_length)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
if (amt_read < sizeof(byte_order_magic)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
if (byte_order_magic != BYTE_ORDER_MAGIC) {
byte_order_magic = SWAPLONG(byte_order_magic);
if (byte_order_magic != BYTE_ORDER_MAGIC) {
/*
* Not a pcapng file.
*/
return (NULL);
}
swapped = 1;
total_length = SWAPLONG(total_length);
}
/*
* Check the sanity of the total length.
*/
if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Section Header Block in pcapng dump file has a length of %u < %" PRIsize,
total_length,
sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer));
*err = 1;
return (NULL);
}
/*
* Make sure it's not too big.
*/
if (total_length > INITIAL_MAX_BLOCKSIZE) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"pcapng block size %u > maximum %u",
total_length, INITIAL_MAX_BLOCKSIZE);
*err = 1;
return (NULL);
}
/*
* OK, this is a good pcapng file.
* Allocate a pcap_t for it.
*/
p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf));
if (p == NULL) {
/* Allocation failed. */
*err = 1;
return (NULL);
}
p->swapped = swapped;
ps = p->priv;
/*
* What precision does the user want?
*/
switch (precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
ps->user_tsresol = 1000000;
break;
case PCAP_TSTAMP_PRECISION_NANO:
ps->user_tsresol = 1000000000;
break;
default:
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unknown time stamp resolution %u", precision);
free(p);
*err = 1;
return (NULL);
}
p->opt.tstamp_precision = precision;
/*
* Allocate a buffer into which to read blocks. We default to
* the maximum of:
*
* the total length of the SHB for which we read the header;
*
* 2K, which should be more than large enough for an Enhanced
* Packet Block containing a full-size Ethernet frame, and
* leaving room for some options.
*
* If we find a bigger block, we reallocate the buffer, up to
* the maximum size. We start out with a maximum size of
* INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types
* with a maximum snapshot that results in a larger maximum
* block length, we boost the maximum.
*/
p->bufsize = 2048;
if (p->bufsize < total_length)
p->bufsize = total_length;
p->buffer = malloc(p->bufsize);
if (p->buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
free(p);
*err = 1;
return (NULL);
}
ps->max_blocksize = INITIAL_MAX_BLOCKSIZE;
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the SHB.
*/
bhdrp = (struct block_header *)p->buffer;
shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header));
bhdrp->block_type = magic_int;
bhdrp->total_length = total_length;
shbp->byte_order_magic = byte_order_magic;
if (read_bytes(fp,
(u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
1, errbuf) == -1)
goto fail;
if (p->swapped) {
/*
* Byte-swap the fields we've read.
*/
shbp->major_version = SWAPSHORT(shbp->major_version);
shbp->minor_version = SWAPSHORT(shbp->minor_version);
/*
* XXX - we don't care about the section length.
*/
}
/* currently only SHB version 1.0 is supported */
if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR &&
shbp->minor_version == PCAP_NG_VERSION_MINOR)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unsupported pcapng savefile version %u.%u",
shbp->major_version, shbp->minor_version);
goto fail;
}
p->version_major = shbp->major_version;
p->version_minor = shbp->minor_version;
/*
* Save the time stamp resolution the user requested.
*/
p->opt.tstamp_precision = precision;
/*
* Now start looking for an Interface Description Block.
*/
for (;;) {
/*
* Read the next block.
*/
status = read_block(fp, p, &cursor, errbuf);
if (status == 0) {
/* EOF - no IDB in this file */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has no Interface Description Blocks");
goto fail;
}
if (status == -1)
goto fail; /* error */
switch (cursor.block_type) {
case BT_IDB:
/*
* Get a pointer to the fixed-length portion of the
* IDB.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
errbuf);
if (idbp == NULL)
goto fail; /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, errbuf))
goto fail;
goto done;
case BT_EPB:
case BT_SPB:
case BT_PB:
/*
* Saw a packet before we saw any IDBs. That's
* not valid, as we don't know what link-layer
* encapsulation the packet has.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has a packet block before any Interface Description Blocks");
goto fail;
default:
/*
* Just ignore it.
*/
break;
}
}
done:
p->tzoff = 0; /* XXX - not used in pcap */
p->linktype = linktype_to_dlt(idbp->linktype);
p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen);
p->linktype_ext = 0;
/*
* If the maximum block size for a packet with the maximum
* snapshot length for this DLT_ is bigger than the current
* maximum block size, increase the maximum.
*/
if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize)
ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype));
p->next_packet_op = pcap_ng_next_packet;
p->cleanup_op = pcap_ng_cleanup;
return (p);
fail:
free(ps->ifaces);
free(p->buffer);
free(p);
*err = 1;
return (NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-770'], 'message': 'do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, size_t sourcelen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
pcap_t *fp; // pcap_t main variable
int nread;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_openreply *openreply; // open reply message
if (plen > sourcelen - 1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
goto error;
}
nread = sock_recv(pars->sockctrl, source, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
source[nread] = '\0';
plen -= nread;
// XXX - make sure it's *not* a URL; we don't support opening
// remote devices here.
// Open the selected device
// This is a fake open, since we do that only to get the needed parameters, then we close the device again
if ((fp = pcap_open_live(source,
1500 /* fake snaplen */,
0 /* no promis */,
1000 /* fake timeout */,
errmsgbuf)) == NULL)
goto error;
// Now, I can send a RPCAP open reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(openreply, 0, sizeof(struct rpcap_openreply));
openreply->linktype = htonl(pcap_datalink(fp));
openreply->tzoff = 0; /* This is always 0 for live captures */
// We're done with the pcap_t.
pcap_close(fp);
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-918'], 'message': 'In the open request, reject capture sources that are URLs.
You shouldn't be able to ask a server to open a remote device on some
*other* server; just open it yourself.
This addresses Include Security issue F13: [libpcap] Remote Packet
Capture Daemon Allows Opening Capture URLs.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
HANDLE Token;
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "LogonUser() failed");
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
if (setuid(user->pw_uid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setuid");
return -1;
}
/* if (setgid(user->pw_gid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
return -1;
}
*/
return 0;
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-345', 'CWE-787'], 'message': 'On UN*X, don't tell the client why authentication failed.
"no such user" tells the client that the user ID isn't valid and,
therefore, that it needn't bother trying to do password cracking for
that user ID; just saying that the authentication failed dosn't give
them that hint.
This resolves the third problem in Include Security issue F11: [libpcap]
Remote Packet Capture Daemon Multiple Authentication Improvements.
The Windows LogonUser() API returns ERROR_LOGON_FAILURE for both cases,
so the Windows code doesn't have this issue. Just return the same
"Authentication failed" message on Windows to the user.
For various authentication failures *other* than "no such user" and
"password not valid", log a message, as there's a problem that may need
debugging. We don't need to tell the end user what the problem is, as
they may not bother reporting it and, even if they do, they may not give
the full error 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: SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, char **buf, int *buf_type)
{
struct smb_rqst rqst;
int resp_buftype, rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_read_rsp *rsp = NULL;
struct kvec iov[1];
struct kvec rsp_iov;
unsigned int total_len;
int flags = CIFS_LOG_ERROR;
struct cifs_ses *ses = io_parms->tcon->ses;
*nbytes = 0;
rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
if (rc)
return rc;
if (smb3_encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
if (rc) {
if (rc != -ENODATA) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
cifs_dbg(VFS, "Send error in read = %d\n", rc);
trace_smb3_read_err(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length,
rc);
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, 0);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc == -ENODATA ? 0 : rc;
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length);
*nbytes = le32_to_cpu(rsp->DataLength);
if ((*nbytes > CIFS_MAX_MSGSIZE) ||
(*nbytes > io_parms->length)) {
cifs_dbg(FYI, "bad length %d for count %d\n",
*nbytes, io_parms->length);
rc = -EIO;
*nbytes = 0;
}
if (*buf) {
memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
} else if (resp_buftype != CIFS_NO_BUFFER) {
*buf = rsp_iov.iov_base;
if (resp_buftype == CIFS_SMALL_BUFFER)
*buf_type = CIFS_SMALL_BUFFER;
else if (resp_buftype == CIFS_LARGE_BUFFER)
*buf_type = CIFS_LARGE_BUFFER;
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-241'], 'message': 'cifs: Fix use-after-free in SMB2_read
There is a KASAN use-after-free:
BUG: KASAN: use-after-free in SMB2_read+0x1136/0x1190
Read of size 8 at addr ffff8880b4e45e50 by task ln/1009
Should not release the 'req' because it will use in the trace.
Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging")
Signed-off-by: ZhangXiaoxu <[email protected]>
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]> 4.18+
Reviewed-by: Pavel Shilovsky <[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 genl_register_family(struct genl_family *family)
{
int err, i;
int start = GENL_START_ALLOC, end = GENL_MAX_ID;
err = genl_validate_ops(family);
if (err)
return err;
genl_lock_all();
if (genl_family_find_byname(family->name)) {
err = -EEXIST;
goto errout_locked;
}
/*
* Sadly, a few cases need to be special-cased
* due to them having previously abused the API
* and having used their family ID also as their
* multicast group ID, so we use reserved IDs
* for both to be sure we can do that mapping.
*/
if (family == &genl_ctrl) {
/* and this needs to be special for initial family lookups */
start = end = GENL_ID_CTRL;
} else if (strcmp(family->name, "pmcraid") == 0) {
start = end = GENL_ID_PMCRAID;
} else if (strcmp(family->name, "VFS_DQUOT") == 0) {
start = end = GENL_ID_VFS_DQUOT;
}
if (family->maxattr && !family->parallel_ops) {
family->attrbuf = kmalloc_array(family->maxattr + 1,
sizeof(struct nlattr *),
GFP_KERNEL);
if (family->attrbuf == NULL) {
err = -ENOMEM;
goto errout_locked;
}
} else
family->attrbuf = NULL;
family->id = idr_alloc(&genl_fam_idr, family,
start, end + 1, GFP_KERNEL);
if (family->id < 0) {
err = family->id;
goto errout_locked;
}
err = genl_validate_assign_mc_groups(family);
if (err)
goto errout_remove;
genl_unlock_all();
/* send all events */
genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0);
for (i = 0; i < family->n_mcgrps; i++)
genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family,
&family->mcgrps[i], family->mcgrp_offset + i);
return 0;
errout_remove:
idr_remove(&genl_fam_idr, family->id);
kfree(family->attrbuf);
errout_locked:
genl_unlock_all();
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'genetlink: Fix a memory leak on error path
In genl_register_family(), when idr_alloc() fails,
we forget to free the memory we possibly allocate for
family->attrbuf.
Reported-by: Hulk Robot <[email protected]>
Fixes: 2ae0f17df1cd ("genetlink: use idr to track families")
Signed-off-by: YueHaibing <[email protected]>
Reviewed-by: Kirill Tkhai <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void rtl_p2p_noa_ie(struct ieee80211_hw *hw, void *data,
unsigned int len)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct ieee80211_mgmt *mgmt = data;
struct rtl_p2p_ps_info *p2pinfo = &(rtlpriv->psc.p2p_ps_info);
u8 *pos, *end, *ie;
u16 noa_len;
static u8 p2p_oui_ie_type[4] = {0x50, 0x6f, 0x9a, 0x09};
u8 noa_num, index , i, noa_index = 0;
bool find_p2p_ie = false , find_p2p_ps_ie = false;
pos = (u8 *)mgmt->u.beacon.variable;
end = data + len;
ie = NULL;
while (pos + 1 < end) {
if (pos + 2 + pos[1] > end)
return;
if (pos[0] == 221 && pos[1] > 4) {
if (memcmp(&pos[2], p2p_oui_ie_type, 4) == 0) {
ie = pos + 2+4;
break;
}
}
pos += 2 + pos[1];
}
if (ie == NULL)
return;
find_p2p_ie = true;
/*to find noa ie*/
while (ie + 1 < end) {
noa_len = READEF2BYTE((__le16 *)&ie[1]);
if (ie + 3 + ie[1] > end)
return;
if (ie[0] == 12) {
find_p2p_ps_ie = true;
if ((noa_len - 2) % 13 != 0) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"P2P notice of absence: invalid length.%d\n",
noa_len);
return;
} else {
noa_num = (noa_len - 2) / 13;
}
noa_index = ie[3];
if (rtlpriv->psc.p2p_ps_info.p2p_ps_mode ==
P2P_PS_NONE || noa_index != p2pinfo->noa_index) {
RT_TRACE(rtlpriv, COMP_FW, DBG_LOUD,
"update NOA ie.\n");
p2pinfo->noa_index = noa_index;
p2pinfo->opp_ps = (ie[4] >> 7);
p2pinfo->ctwindow = ie[4] & 0x7F;
p2pinfo->noa_num = noa_num;
index = 5;
for (i = 0; i < noa_num; i++) {
p2pinfo->noa_count_type[i] =
READEF1BYTE(ie+index);
index += 1;
p2pinfo->noa_duration[i] =
READEF4BYTE((__le32 *)ie+index);
index += 4;
p2pinfo->noa_interval[i] =
READEF4BYTE((__le32 *)ie+index);
index += 4;
p2pinfo->noa_start_time[i] =
READEF4BYTE((__le32 *)ie+index);
index += 4;
}
if (p2pinfo->opp_ps == 1) {
p2pinfo->p2p_ps_mode = P2P_PS_CTWINDOW;
/* Driver should wait LPS entering
* CTWindow
*/
if (rtlpriv->psc.fw_current_inpsmode)
rtl_p2p_ps_cmd(hw,
P2P_PS_ENABLE);
} else if (p2pinfo->noa_num > 0) {
p2pinfo->p2p_ps_mode = P2P_PS_NOA;
rtl_p2p_ps_cmd(hw, P2P_PS_ENABLE);
} else if (p2pinfo->p2p_ps_mode > P2P_PS_NONE) {
rtl_p2p_ps_cmd(hw, P2P_PS_DISABLE);
}
}
break;
}
ie += 3 + noa_len;
}
if (find_p2p_ie == true) {
if ((p2pinfo->p2p_ps_mode > P2P_PS_NONE) &&
(find_p2p_ps_ie == false))
rtl_p2p_ps_cmd(hw, P2P_PS_DISABLE);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'rtlwifi: Fix potential overflow on P2P code
Nicolas Waisman noticed that even though noa_len is checked for
a compatible length it's still possible to overrun the buffers
of p2pinfo since there's no check on the upper bound of noa_num.
Bound noa_num against P2P_MAX_NOA_NUM.
Reported-by: Nicolas Waisman <[email protected]>
Signed-off-by: Laura Abbott <[email protected]>
Acked-by: Ping-Ke Shih <[email protected]>
Signed-off-by: Kalle Valo <[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 pf_detect(void)
{
struct pf_unit *pf = units;
int k, unit;
printk("%s: %s version %s, major %d, cluster %d, nice %d\n",
name, name, PF_VERSION, major, cluster, nice);
par_drv = pi_register_driver(name);
if (!par_drv) {
pr_err("failed to register %s driver\n", name);
return -1;
}
k = 0;
if (pf_drive_count == 0) {
if (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF,
verbose, pf->name)) {
if (!pf_probe(pf) && pf->disk) {
pf->present = 1;
k++;
} else
pi_release(pf->pi);
}
} else
for (unit = 0; unit < PF_UNITS; unit++, pf++) {
int *conf = *drives[unit];
if (!conf[D_PRT])
continue;
if (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD],
conf[D_UNI], conf[D_PRO], conf[D_DLY],
pf_scratch, PI_PF, verbose, pf->name)) {
if (pf->disk && !pf_probe(pf)) {
pf->present = 1;
k++;
} else
pi_release(pf->pi);
}
}
if (k)
return 0;
printk("%s: No ATAPI disk detected\n", name);
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
blk_cleanup_queue(pf->disk->queue);
pf->disk->queue = NULL;
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
}
pi_unregister_driver(par_drv);
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'paride/pf: Fix potential NULL pointer dereference
Syzkaller report this:
pf: pf version 1.04, major 47, cluster 64, nice 0
pf: No ATAPI disk detected
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pf_init+0x7af/0x1000 [pf]
Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34
RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788
RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59
R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000
R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020
FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1e50000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp
c
ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp
td
glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace 7a818cf5f210d79e ]---
If alloc_disk fails in pf_init_units, pf->disk will be
NULL, however in pf_detect and pf_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[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 __exit pf_exit(void)
{
struct pf_unit *pf;
int unit;
unregister_blkdev(major, name);
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
if (pf->present)
del_gendisk(pf->disk);
blk_cleanup_queue(pf->disk->queue);
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
if (pf->present)
pi_release(pf->pi);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'paride/pf: Fix potential NULL pointer dereference
Syzkaller report this:
pf: pf version 1.04, major 47, cluster 64, nice 0
pf: No ATAPI disk detected
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pf_init+0x7af/0x1000 [pf]
Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34
RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788
RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59
R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000
R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020
FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1e50000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp
c
ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp
td
glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace 7a818cf5f210d79e ]---
If alloc_disk fails in pf_init_units, pf->disk will be
NULL, however in pf_detect and pf_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[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 pcd_init_units(void)
{
struct pcd_unit *cd;
int unit;
pcd_drive_count = 0;
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
struct gendisk *disk = alloc_disk(1);
if (!disk)
continue;
disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops,
1, BLK_MQ_F_SHOULD_MERGE);
if (IS_ERR(disk->queue)) {
disk->queue = NULL;
continue;
}
INIT_LIST_HEAD(&cd->rq_list);
disk->queue->queuedata = cd;
blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH);
cd->disk = disk;
cd->pi = &cd->pia;
cd->present = 0;
cd->last_sense = 0;
cd->changed = 1;
cd->drive = (*drives[unit])[D_SLV];
if ((*drives[unit])[D_PRT])
pcd_drive_count++;
cd->name = &cd->info.name[0];
snprintf(cd->name, sizeof(cd->info.name), "%s%d", name, unit);
cd->info.ops = &pcd_dops;
cd->info.handle = cd;
cd->info.speed = 0;
cd->info.capacity = 1;
cd->info.mask = 0;
disk->major = major;
disk->first_minor = unit;
strcpy(disk->disk_name, cd->name); /* umm... */
disk->fops = &pcd_bdops;
disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'paride/pcd: Fix potential NULL pointer dereference and mem leak
Syzkaller report this:
pcd: pcd version 1.07, major 46, nice 0
pcd0: Autoprobe failed
pcd: No CD-ROM drive found
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pcd_init+0x95c/0x1000 [pcd]
Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2
RSP: 0018:ffff8881e84df880 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935
RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8
R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000
R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003
FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1508000
? 0xffffffffc1508000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd
ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace d873691c3cd69f56 ]---
If alloc_disk fails in pcd_init_units, cd->disk will be
NULL, however in pcd_detect and pcd_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[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 __exit pcd_exit(void)
{
struct pcd_unit *cd;
int unit;
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (cd->present) {
del_gendisk(cd->disk);
pi_release(cd->pi);
unregister_cdrom(&cd->info);
}
blk_cleanup_queue(cd->disk->queue);
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
unregister_blkdev(major, name);
pi_unregister_driver(par_drv);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'paride/pcd: Fix potential NULL pointer dereference and mem leak
Syzkaller report this:
pcd: pcd version 1.07, major 46, nice 0
pcd0: Autoprobe failed
pcd: No CD-ROM drive found
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pcd_init+0x95c/0x1000 [pcd]
Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2
RSP: 0018:ffff8881e84df880 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935
RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8
R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000
R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003
FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1508000
? 0xffffffffc1508000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd
ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace d873691c3cd69f56 ]---
If alloc_disk fails in pcd_init_units, cd->disk will be
NULL, however in pcd_detect and pcd_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[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: _gcry_mpi_ec_mul_point (mpi_point_t result,
gcry_mpi_t scalar, mpi_point_t point,
mpi_ec_t ctx)
{
gcry_mpi_t x1, y1, z1, k, h, yy;
unsigned int i, loops;
mpi_point_struct p1, p2, p1inv;
if (ctx->model == MPI_EC_EDWARDS
|| (ctx->model == MPI_EC_WEIERSTRASS
&& mpi_is_secure (scalar)))
{
/* Simple left to right binary method. Algorithm 3.27 from
* {author={Hankerson, Darrel and Menezes, Alfred J. and Vanstone, Scott},
* title = {Guide to Elliptic Curve Cryptography},
* year = {2003}, isbn = {038795273X},
* url = {http://www.cacr.math.uwaterloo.ca/ecc/},
* publisher = {Springer-Verlag New York, Inc.}} */
unsigned int nbits;
int j;
nbits = mpi_get_nbits (scalar);
if (ctx->model == MPI_EC_WEIERSTRASS)
{
mpi_set_ui (result->x, 1);
mpi_set_ui (result->y, 1);
mpi_set_ui (result->z, 0);
}
else
{
mpi_set_ui (result->x, 0);
mpi_set_ui (result->y, 1);
mpi_set_ui (result->z, 1);
point_resize (point, ctx);
}
if (mpi_is_secure (scalar))
{
/* If SCALAR is in secure memory we assume that it is the
secret key we use constant time operation. */
mpi_point_struct tmppnt;
point_init (&tmppnt);
point_resize (result, ctx);
point_resize (&tmppnt, ctx);
for (j=nbits-1; j >= 0; j--)
{
_gcry_mpi_ec_dup_point (result, result, ctx);
_gcry_mpi_ec_add_points (&tmppnt, result, point, ctx);
point_swap_cond (result, &tmppnt, mpi_test_bit (scalar, j), ctx);
}
point_free (&tmppnt);
}
else
{
if (ctx->model == MPI_EC_EDWARDS)
{
point_resize (result, ctx);
point_resize (point, ctx);
}
for (j=nbits-1; j >= 0; j--)
{
_gcry_mpi_ec_dup_point (result, result, ctx);
if (mpi_test_bit (scalar, j))
_gcry_mpi_ec_add_points (result, result, point, ctx);
}
}
return;
}
else if (ctx->model == MPI_EC_MONTGOMERY)
{
unsigned int nbits;
int j;
mpi_point_struct p1_, p2_;
mpi_point_t q1, q2, prd, sum;
unsigned long sw;
mpi_size_t rsize;
/* Compute scalar point multiplication with Montgomery Ladder.
Note that we don't use Y-coordinate in the points at all.
RESULT->Y will be filled by zero. */
nbits = mpi_get_nbits (scalar);
point_init (&p1);
point_init (&p2);
point_init (&p1_);
point_init (&p2_);
mpi_set_ui (p1.x, 1);
mpi_free (p2.x);
p2.x = mpi_copy (point->x);
mpi_set_ui (p2.z, 1);
point_resize (&p1, ctx);
point_resize (&p2, ctx);
point_resize (&p1_, ctx);
point_resize (&p2_, ctx);
mpi_resize (point->x, ctx->p->nlimbs);
point->x->nlimbs = ctx->p->nlimbs;
q1 = &p1;
q2 = &p2;
prd = &p1_;
sum = &p2_;
for (j=nbits-1; j >= 0; j--)
{
mpi_point_t t;
sw = mpi_test_bit (scalar, j);
point_swap_cond (q1, q2, sw, ctx);
montgomery_ladder (prd, sum, q1, q2, point->x, ctx);
point_swap_cond (prd, sum, sw, ctx);
t = q1; q1 = prd; prd = t;
t = q2; q2 = sum; sum = t;
}
mpi_clear (result->y);
sw = (nbits & 1);
point_swap_cond (&p1, &p1_, sw, ctx);
rsize = p1.z->nlimbs;
MPN_NORMALIZE (p1.z->d, rsize);
if (rsize == 0)
{
mpi_set_ui (result->x, 1);
mpi_set_ui (result->z, 0);
}
else
{
z1 = mpi_new (0);
ec_invm (z1, p1.z, ctx);
ec_mulm (result->x, p1.x, z1, ctx);
mpi_set_ui (result->z, 1);
mpi_free (z1);
}
point_free (&p1);
point_free (&p2);
point_free (&p1_);
point_free (&p2_);
return;
}
x1 = mpi_alloc_like (ctx->p);
y1 = mpi_alloc_like (ctx->p);
h = mpi_alloc_like (ctx->p);
k = mpi_copy (scalar);
yy = mpi_copy (point->y);
if ( mpi_has_sign (k) )
{
k->sign = 0;
ec_invm (yy, yy, ctx);
}
if (!mpi_cmp_ui (point->z, 1))
{
mpi_set (x1, point->x);
mpi_set (y1, yy);
}
else
{
gcry_mpi_t z2, z3;
z2 = mpi_alloc_like (ctx->p);
z3 = mpi_alloc_like (ctx->p);
ec_mulm (z2, point->z, point->z, ctx);
ec_mulm (z3, point->z, z2, ctx);
ec_invm (z2, z2, ctx);
ec_mulm (x1, point->x, z2, ctx);
ec_invm (z3, z3, ctx);
ec_mulm (y1, yy, z3, ctx);
mpi_free (z2);
mpi_free (z3);
}
z1 = mpi_copy (mpi_const (MPI_C_ONE));
mpi_mul (h, k, mpi_const (MPI_C_THREE)); /* h = 3k */
loops = mpi_get_nbits (h);
if (loops < 2)
{
/* If SCALAR is zero, the above mpi_mul sets H to zero and thus
LOOPs will be zero. To avoid an underflow of I in the main
loop we set LOOP to 2 and the result to (0,0,0). */
loops = 2;
mpi_clear (result->x);
mpi_clear (result->y);
mpi_clear (result->z);
}
else
{
mpi_set (result->x, point->x);
mpi_set (result->y, yy);
mpi_set (result->z, point->z);
}
mpi_free (yy); yy = NULL;
p1.x = x1; x1 = NULL;
p1.y = y1; y1 = NULL;
p1.z = z1; z1 = NULL;
point_init (&p2);
point_init (&p1inv);
/* Invert point: y = p - y mod p */
point_set (&p1inv, &p1);
ec_subm (p1inv.y, ctx->p, p1inv.y, ctx);
for (i=loops-2; i > 0; i--)
{
_gcry_mpi_ec_dup_point (result, result, ctx);
if (mpi_test_bit (h, i) == 1 && mpi_test_bit (k, i) == 0)
{
point_set (&p2, result);
_gcry_mpi_ec_add_points (result, &p2, &p1, ctx);
}
if (mpi_test_bit (h, i) == 0 && mpi_test_bit (k, i) == 1)
{
point_set (&p2, result);
_gcry_mpi_ec_add_points (result, &p2, &p1inv, ctx);
}
}
point_free (&p1);
point_free (&p2);
point_free (&p1inv);
mpi_free (h);
mpi_free (k);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'ecc: Add mitigation against timing attack.
* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Add the order N to K.
* mpi/ec.c (_gcry_mpi_ec_mul_point): Compute with NBITS of P or larger.
CVE-id: CVE-2019-13627
GnuPG-bug-id: 4626
Co-authored-by: Ján Jančár <[email protected]>
Signed-off-by: NIIBE Yutaka <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _gcry_ecc_gost_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s)
{
gpg_err_code_t rc = 0;
gcry_mpi_t k, dr, sum, ke, x, e;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
if (DBG_CIPHER)
log_mpidump ("gost sign hash ", input );
qbits = mpi_get_nbits (skey->E.n);
/* Convert the INPUT into an MPI if needed. */
if (mpi_is_opaque (input))
{
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_mpi_scan (&hash, GCRYMPI_FMT_USG, abuf, (abits+7)/8, NULL);
if (rc)
return rc;
if (abits > qbits)
mpi_rshift (hash, hash, abits - qbits);
}
else
hash = input;
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
ke = mpi_alloc (0);
e = mpi_alloc (0);
x = mpi_alloc (0);
point_init (&I);
ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0,
skey->E.p, skey->E.a, skey->E.b);
mpi_mod (e, input, skey->E.n); /* e = hash mod n */
if (!mpi_cmp_ui (e, 0))
mpi_set_ui (e, 1);
/* Two loops to avoid R or S are zero. This is more of a joke than
a real demand because the probability of them being zero is less
than any hardware failure. Some specs however require it. */
do
{
do
{
mpi_free (k);
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */
mpi_mulm (ke, k, e, skey->E.n); /* ke = k*e mod n */
mpi_addm (s, ke, dr, skey->E.n); /* sum = (k*e+ d*r) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
{
log_mpidump ("gost sign result r ", r);
log_mpidump ("gost sign result s ", s);
}
leave:
_gcry_mpi_ec_free (ctx);
point_free (&I);
mpi_free (x);
mpi_free (e);
mpi_free (ke);
mpi_free (sum);
mpi_free (dr);
mpi_free (k);
if (hash != input)
mpi_free (hash);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'dsa,ecdsa: Fix use of nonce, use larger one.
* cipher/dsa-common.c (_gcry_dsa_modify_k): New.
* cipher/pubkey-internal.h (_gcry_dsa_modify_k): New.
* cipher/dsa.c (sign): Use _gcry_dsa_modify_k.
* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Likewise.
* cipher/ecc-gost.c (_gcry_ecc_gost_sign): Likewise.
CVE-id: CVE-2019-13627
GnuPG-bug-id: 4626
Signed-off-by: NIIBE Yutaka <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s,
int flags, int hashalgo)
{
gpg_err_code_t rc = 0;
int extraloops = 0;
gcry_mpi_t k, dr, sum, k_1, x;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
gcry_mpi_t b; /* Random number needed for blinding. */
gcry_mpi_t bi; /* multiplicative inverse of B. */
if (DBG_CIPHER)
log_mpidump ("ecdsa sign hash ", input );
qbits = mpi_get_nbits (skey->E.n);
/* Convert the INPUT into an MPI if needed. */
rc = _gcry_dsa_normalize_hash (input, &hash, qbits);
if (rc)
return rc;
b = mpi_snew (qbits);
bi = mpi_snew (qbits);
do
{
_gcry_mpi_randomize (b, qbits, GCRY_WEAK_RANDOM);
mpi_mod (b, b, skey->E.n);
}
while (!mpi_invm (bi, b, skey->E.n));
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
k_1 = mpi_alloc (0);
x = mpi_alloc (0);
point_init (&I);
ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0,
skey->E.p, skey->E.a, skey->E.b);
/* Two loops to avoid R or S are zero. This is more of a joke than
a real demand because the probability of them being zero is less
than any hardware failure. Some specs however require it. */
do
{
do
{
mpi_free (k);
k = NULL;
if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)
{
/* Use Pornin's method for deterministic DSA. If this
flag is set, it is expected that HASH is an opaque
MPI with the to be signed hash. That hash is also
used as h1 from 3.2.a. */
if (!mpi_is_opaque (input))
{
rc = GPG_ERR_CONFLICT;
goto leave;
}
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,
abuf, (abits+7)/8,
hashalgo, extraloops);
if (rc)
goto leave;
extraloops++;
}
else
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
/* Originally, ECDSA computation requires k where 0 < k < n.
* Here, we add n (the order of curve), to keep k in a
* range: n < k < 2*n, or, addming more n, keep k in a range:
* 2*n < k < 3*n, so that timing difference of the EC
* multiply operation can be small. The result is same.
*/
mpi_add (k, k, skey->E.n);
if (!mpi_test_bit (k, qbits))
mpi_add (k, k, skey->E.n);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, b, skey->d, skey->E.n);
mpi_mulm (dr, dr, r, skey->E.n); /* dr = d*r mod n (blinded with b) */
mpi_mulm (sum, b, hash, skey->E.n);
mpi_addm (sum, sum, dr, skey->E.n); /* sum = hash + (d*r) mod n (blinded with b) */
mpi_mulm (sum, bi, sum, skey->E.n); /* undo blinding by b^-1 */
mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */
mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
{
log_mpidump ("ecdsa sign result r ", r);
log_mpidump ("ecdsa sign result s ", s);
}
leave:
mpi_free (b);
mpi_free (bi);
_gcry_mpi_ec_free (ctx);
point_free (&I);
mpi_free (x);
mpi_free (k_1);
mpi_free (sum);
mpi_free (dr);
mpi_free (k);
if (hash != input)
mpi_free (hash);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'dsa,ecdsa: Fix use of nonce, use larger one.
* cipher/dsa-common.c (_gcry_dsa_modify_k): New.
* cipher/pubkey-internal.h (_gcry_dsa_modify_k): New.
* cipher/dsa.c (sign): Use _gcry_dsa_modify_k.
* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Likewise.
* cipher/ecc-gost.c (_gcry_ecc_gost_sign): Likewise.
CVE-id: CVE-2019-13627
GnuPG-bug-id: 4626
Signed-off-by: NIIBE Yutaka <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: extern "C" const char * aspell_version_string() {
#ifdef NDEBUG
return VERSION " NDEBUG";
#endif
return VERSION;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Don't allow null-terminated UCS-2/4 strings using the original API.
Detect if the encoding is UCS-2/4 and the length is -1 in affected API
functions and refuse to convert the string. If the string ends up
being converted somehow, abort with an error message in DecodeDirect
and ConvDirect. To convert a null terminated string in
Decode/ConvDirect, a negative number corresponding to the width of the
underlying character type for the encoding is expected; for example,
if the encoding is "ucs-2" then a the size is expected to be -2.
Also fix a 1-3 byte over-read in DecodeDirect when reading UCS-2/4
strings when a size is provided (found by OSS-Fuzz).
Also fix a bug in DecodeDirect that caused DocumentChecker to return
the wrong offsets when working with UCS-2/4 strings.'</s> |
<s>[INST] Given the following code containing errors, provide 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 DocumentChecker::process(const char * str, int size)
{
proc_str_.clear();
conv_->decode(str, size, proc_str_);
proc_str_.append(0);
FilterChar * begin = proc_str_.pbegin();
FilterChar * end = proc_str_.pend() - 1;
if (filter_)
filter_->process(begin, end);
tokenizer_->reset(begin, end);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Don't allow null-terminated UCS-2/4 strings using the original API.
Detect if the encoding is UCS-2/4 and the length is -1 in affected API
functions and refuse to convert the string. If the string ends up
being converted somehow, abort with an error message in DecodeDirect
and ConvDirect. To convert a null terminated string in
Decode/ConvDirect, a negative number corresponding to the width of the
underlying character type for the encoding is expected; for example,
if the encoding is "ucs-2" then a the size is expected to be -2.
Also fix a 1-3 byte over-read in DecodeDirect when reading UCS-2/4
strings when a size is provided (found by OSS-Fuzz).
Also fix a bug in DecodeDirect that caused DocumentChecker to return
the wrong offsets when working with UCS-2/4 strings.'</s> |
<s>[INST] Given the following code containing errors, provide 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 set_default_flags(int *flags)
{
if (((*flags) & IDN2_TRANSITIONAL) && ((*flags) & IDN2_NONTRANSITIONAL))
return IDN2_INVALID_FLAGS;
if (((*flags) & (IDN2_TRANSITIONAL|IDN2_NONTRANSITIONAL)) && ((*flags) & IDN2_NO_TR46))
return IDN2_INVALID_FLAGS;
if (!((*flags) & (IDN2_NO_TR46|IDN2_TRANSITIONAL)))
*flags |= IDN2_NONTRANSITIONAL;
return IDN2_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default
This adds another check to avoid unexpected results.
It was a longstanding FIXME.
Thanks to Jonathan Birch of Microsoft Corporation,
Florian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS)
for investigation, discussion and testing.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: idn2_strerror_name (int rc)
{
switch (rc)
{
case IDN2_OK: return ERR2STR (IDN2_OK);
case IDN2_MALLOC: return ERR2STR (IDN2_MALLOC);
case IDN2_NO_CODESET: return ERR2STR (IDN2_NO_NODESET);
case IDN2_ICONV_FAIL: return ERR2STR (IDN2_ICONV_FAIL);
case IDN2_ENCODING_ERROR: return ERR2STR (IDN2_ENCODING_ERROR);
case IDN2_NFC: return ERR2STR (IDN2_NFC);
case IDN2_PUNYCODE_BAD_INPUT: return ERR2STR (IDN2_PUNYCODE_BAD_INPUT);
case IDN2_PUNYCODE_BIG_OUTPUT: return ERR2STR (IDN2_PUNYCODE_BIG_OUTPUT);
case IDN2_PUNYCODE_OVERFLOW: return ERR2STR (IDN2_PUNYCODE_OVERFLOW);
case IDN2_TOO_BIG_DOMAIN: return ERR2STR (IDN2_TOO_BIG_DOMAIN);
case IDN2_TOO_BIG_LABEL: return ERR2STR (IDN2_TOO_BIG_LABEL);
case IDN2_INVALID_ALABEL: return ERR2STR (IDN2_INVALID_ALABEL);
case IDN2_UALABEL_MISMATCH: return ERR2STR (IDN2_UALABEL_MISMATCH);
case IDN2_INVALID_FLAGS: return ERR2STR (IDN2_INVALID_FLAGS);
case IDN2_NOT_NFC: return ERR2STR (IDN2_NOT_NFC);
case IDN2_2HYPHEN: return ERR2STR (IDN2_2HYPHEN);
case IDN2_HYPHEN_STARTEND: return ERR2STR (IDN2_HYPHEN_STARTEND);
case IDN2_LEADING_COMBINING: return ERR2STR (IDN2_LEADING_COMBINING);
case IDN2_DISALLOWED: return ERR2STR (IDN2_DISALLOWED);
case IDN2_CONTEXTJ: return ERR2STR (IDN2_CONTEXTJ);
case IDN2_CONTEXTJ_NO_RULE: return ERR2STR (IDN2_CONTEXTJ_NO_RULE);
case IDN2_CONTEXTO: return ERR2STR (IDN2_CONTEXTO);
case IDN2_CONTEXTO_NO_RULE: return ERR2STR (IDN2_CONTEXTO_NO_RULE);
case IDN2_UNASSIGNED: return ERR2STR (IDN2_UNASSIGNED);
case IDN2_BIDI: return ERR2STR (IDN2_BIDI);
case IDN2_DOT_IN_LABEL: return ERR2STR (IDN2_DOT_IN_LABEL);
case IDN2_INVALID_TRANSITIONAL: return ERR2STR (IDN2_INVALID_TRANSITIONAL);
case IDN2_INVALID_NONTRANSITIONAL: return ERR2STR (IDN2_INVALID_NONTRANSITIONAL);
default: return "IDN2_UNKNOWN";
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default
This adds another check to avoid unexpected results.
It was a longstanding FIXME.
Thanks to Jonathan Birch of Microsoft Corporation,
Florian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS)
for investigation, discussion and testing.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: label (const uint8_t * src, size_t srclen, uint8_t * dst, size_t * dstlen,
int flags)
{
size_t plen;
uint32_t *p;
int rc;
size_t tmpl;
if (_idn2_ascii_p (src, srclen))
{
if (flags & IDN2_ALABEL_ROUNDTRIP)
/* FIXME implement this MAY:
If the input to this procedure appears to be an A-label
(i.e., it starts in "xn--", interpreted
case-insensitively), the lookup application MAY attempt to
convert it to a U-label, first ensuring that the A-label is
entirely in lowercase (converting it to lowercase if
necessary), and apply the tests of Section 5.4 and the
conversion of Section 5.5 to that form. */
return IDN2_INVALID_FLAGS;
if (srclen > IDN2_LABEL_MAX_LENGTH)
return IDN2_TOO_BIG_LABEL;
if (srclen > *dstlen)
return IDN2_TOO_BIG_DOMAIN;
memcpy (dst, src, srclen);
*dstlen = srclen;
return IDN2_OK;
}
rc = _idn2_u8_to_u32_nfc (src, srclen, &p, &plen, flags & IDN2_NFC_INPUT);
if (rc != IDN2_OK)
return rc;
if (!(flags & IDN2_TRANSITIONAL))
{
rc = _idn2_label_test(
TEST_NFC |
TEST_2HYPHEN |
TEST_LEADING_COMBINING |
TEST_DISALLOWED |
TEST_CONTEXTJ_RULE |
TEST_CONTEXTO_WITH_RULE |
TEST_UNASSIGNED | TEST_BIDI |
((flags & IDN2_NONTRANSITIONAL) ? TEST_NONTRANSITIONAL : 0) |
((flags & IDN2_USE_STD3_ASCII_RULES) ? 0 : TEST_ALLOW_STD3_DISALLOWED),
p, plen);
if (rc != IDN2_OK)
{
free(p);
return rc;
}
}
dst[0] = 'x';
dst[1] = 'n';
dst[2] = '-';
dst[3] = '-';
tmpl = *dstlen - 4;
rc = _idn2_punycode_encode (plen, p, &tmpl, (char *) dst + 4);
free (p);
if (rc != IDN2_OK)
return rc;
*dstlen = 4 + tmpl;
return IDN2_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default
This adds another check to avoid unexpected results.
It was a longstanding FIXME.
Thanks to Jonathan Birch of Microsoft Corporation,
Florian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS)
for investigation, discussion and testing.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)
{
uint32_t *input_u32;
uint8_t *input_u8, *output_u8;
size_t length;
int rc;
if (!input)
{
if (output)
*output = 0;
return IDN2_OK;
}
input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));
if (!input_u32)
return IDN2_MALLOC;
u32_cpy (input_u32, input, inlen);
input_u32[inlen] = 0;
input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);
free (input_u32);
if (!input_u8)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
rc = idn2_lookup_u8 (input_u8, &output_u8, flags);
free (input_u8);
if (rc == IDN2_OK)
{
/* wow, this is ugly, but libidn manpage states:
* char * out output zero terminated string that must have room for at
* least 63 characters plus the terminating zero.
*/
if (output)
strcpy (output, (const char *) output_u8);
free(output_u8);
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'idn2_to_ascii_4i(): Restrict output length to 63'</s> |
<s>[INST] Given the following code containing errors, provide 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 decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int zero_bits = *in & 0x07;
size_t octets_left = inlen - 1;
int i, count = 0;
memset(outbuf, 0, outlen);
in++;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fixed out of bounds access of ASN.1 Bitstring
Credit to OSS-Fuzz'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
size_t i, o4, nelements, j, slen, left;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *,
cdf_offset(sst->sst_tab, offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1)
goto out;
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
inp = cdf_grow_info(info, maxcount, sh.sh_properties);
if (inp == NULL)
goto out;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh)));
e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len));
if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL)
goto out;
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
left = CAST(size_t, e - q);
if (left < sizeof(uint32_t)) {
DPRINTF(("short info (no type)_\n"));
goto out;
}
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
if (left < sizeof(uint32_t) * 2) {
DPRINTF(("missing CDF_VECTOR length\n"));
goto out;
}
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
slen = 2;
} else {
nelements = 1;
slen = 1;
}
o4 = slen * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t)))
goto unknown;
break;
case CDF_SIGNED32:
case CDF_BOOL:
case CDF_UNSIGNED32:
case CDF_FLOAT:
if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t)))
goto unknown;
break;
case CDF_SIGNED64:
case CDF_UNSIGNED64:
case CDF_DOUBLE:
case CDF_FILETIME:
if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t)))
goto unknown;
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
inp = cdf_grow_info(info, maxcount, nelements);
if (inp == NULL)
goto out;
inp += nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l;
if (o4 + sizeof(uint32_t) > left)
goto out;
l = CDF_GETUINT32(q, slen);
o4 += sizeof(uint32_t);
if (o4 + l > left)
goto out;
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = CAST(const char *,
CAST(const void *, &q[o4]));
DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%"
SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT
"u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)),
left, inp[i].pi_str.s_buf));
if (l & 1)
l++;
slen += l >> 1;
o4 = slen * sizeof(uint32_t);
}
i--;
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val));
DPRINTF(("Don't know how to deal with %#x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
*info = NULL;
*count = 0;
*maxcount = 0;
errno = EFTYPE;
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Limit the number of elements in a vector (found by oss-fuzz)'</s> |
<s>[INST] Given the following code containing errors, provide 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 vrend_renderer_transfer_iov(const struct vrend_transfer_info *info,
int transfer_mode)
{
struct vrend_resource *res;
struct vrend_context *ctx;
struct iovec *iov;
int num_iovs;
if (!info->box)
return EINVAL;
ctx = vrend_lookup_renderer_ctx(info->ctx_id);
if (!ctx)
return EINVAL;
if (info->ctx_id == 0)
res = vrend_resource_lookup(info->handle, 0);
else
res = vrend_renderer_ctx_res_lookup(ctx, info->handle);
if (!res) {
if (info->ctx_id)
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, info->handle);
return EINVAL;
}
iov = info->iovec;
num_iovs = info->iovec_cnt;
if (res->iov && (!iov || num_iovs == 0)) {
iov = res->iov;
num_iovs = res->num_iovs;
}
if (!iov) {
if (info->ctx_id)
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, info->handle);
return EINVAL;
}
#ifdef ENABLE_GBM_ALLOCATION
if (res->gbm_bo)
return virgl_gbm_transfer(res->gbm_bo, transfer_mode, iov, num_iovs, info);
#endif
if (!check_transfer_bounds(res, info))
return EINVAL;
if (!check_iov_bounds(res, info, iov, num_iovs))
return EINVAL;
if (info->context0) {
vrend_renderer_force_ctx_0();
ctx = NULL;
}
switch (transfer_mode) {
case VIRGL_TRANSFER_TO_HOST:
return vrend_renderer_transfer_write_iov(ctx, res, iov, num_iovs, info);
case VIRGL_TRANSFER_FROM_HOST:
return vrend_renderer_transfer_send_iov(res, iov, num_iovs, info);
default:
assert(0);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'vrend: check transfer bounds for negative values too and report error
Closes #138
Signed-off-by: Gert Wollny <[email protected]>
Reviewed-by: Emil Velikov <[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 check_resource_valid(struct vrend_renderer_resource_create_args *args)
{
/* do not accept handle 0 */
if (args->handle == 0)
return -1;
/* limit the target */
if (args->target >= PIPE_MAX_TEXTURE_TYPES)
return -1;
if (args->format >= VIRGL_FORMAT_MAX)
return -1;
/* only texture 2d and 2d array can have multiple samples */
if (args->nr_samples > 0) {
if (!has_feature(feat_texture_multisample))
return -1;
if (args->target != PIPE_TEXTURE_2D && args->target != PIPE_TEXTURE_2D_ARRAY)
return -1;
/* multisample can't have miplevels */
if (args->last_level > 0)
return -1;
}
if (args->last_level > 0) {
/* buffer and rect textures can't have mipmaps */
if (args->target == PIPE_BUFFER || args->target == PIPE_TEXTURE_RECT)
return -1;
if (args->last_level > (floor(log2(MAX2(args->width, args->height))) + 1))
return -1;
}
if (args->flags != 0 && args->flags != VIRGL_RESOURCE_Y_0_TOP)
return -1;
if (args->flags & VIRGL_RESOURCE_Y_0_TOP)
if (args->target != PIPE_TEXTURE_2D && args->target != PIPE_TEXTURE_RECT)
return -1;
/* array size for array textures only */
if (args->target == PIPE_TEXTURE_CUBE) {
if (args->array_size != 6)
return -1;
} else if (args->target == PIPE_TEXTURE_CUBE_ARRAY) {
if (!has_feature(feat_cube_map_array))
return -1;
if (args->array_size % 6)
return -1;
} else if (args->array_size > 1) {
if (args->target != PIPE_TEXTURE_2D_ARRAY &&
args->target != PIPE_TEXTURE_1D_ARRAY)
return -1;
if (!has_feature(feat_texture_array))
return -1;
}
if (args->bind == 0 ||
args->bind == VIRGL_BIND_CUSTOM ||
args->bind == VIRGL_BIND_STAGING ||
args->bind == VIRGL_BIND_INDEX_BUFFER ||
args->bind == VIRGL_BIND_STREAM_OUTPUT ||
args->bind == VIRGL_BIND_VERTEX_BUFFER ||
args->bind == VIRGL_BIND_CONSTANT_BUFFER ||
args->bind == VIRGL_BIND_QUERY_BUFFER ||
args->bind == VIRGL_BIND_COMMAND_ARGS ||
args->bind == VIRGL_BIND_SHADER_BUFFER) {
if (args->target != PIPE_BUFFER)
return -1;
if (args->height != 1 || args->depth != 1)
return -1;
if (args->bind == VIRGL_BIND_QUERY_BUFFER && !has_feature(feat_qbo))
return -1;
if (args->bind == VIRGL_BIND_COMMAND_ARGS && !has_feature(feat_indirect_draw))
return -1;
} else {
if (!((args->bind & VIRGL_BIND_SAMPLER_VIEW) ||
(args->bind & VIRGL_BIND_DEPTH_STENCIL) ||
(args->bind & VIRGL_BIND_RENDER_TARGET) ||
(args->bind & VIRGL_BIND_CURSOR) ||
(args->bind & VIRGL_BIND_SHARED) ||
(args->bind & VIRGL_BIND_LINEAR))) {
return -1;
}
if (args->target == PIPE_TEXTURE_2D ||
args->target == PIPE_TEXTURE_RECT ||
args->target == PIPE_TEXTURE_CUBE ||
args->target == PIPE_TEXTURE_2D_ARRAY ||
args->target == PIPE_TEXTURE_CUBE_ARRAY) {
if (args->depth != 1)
return -1;
}
if (args->target == PIPE_TEXTURE_1D ||
args->target == PIPE_TEXTURE_1D_ARRAY) {
if (args->height != 1 || args->depth != 1)
return -1;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'vrend: Check resource creation more thoroughly
While we are at it:
- free memory if texture allocation fails
Closes #144
Closes #145
Closes #146
v2: Move the error string creation to extra patch (Emil)
v3: Fix whitespace errors (Emil) and one logic error
Signed-off-by: Gert Wollny <[email protected]>
Reviewed-by: Emil Velikov <[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 vrend_renderer_transfer_write_iov(struct vrend_context *ctx,
struct vrend_resource *res,
struct iovec *iov, int num_iovs,
const struct vrend_transfer_info *info)
{
void *data;
if (res->storage == VREND_RESOURCE_STORAGE_GUEST ||
(res->storage == VREND_RESOURCE_STORAGE_GUEST_ELSE_SYSTEM && res->iov)) {
return vrend_copy_iovec(iov, num_iovs, info->offset,
res->iov, res->num_iovs, info->box->x,
info->box->width, res->ptr);
}
if (res->storage == VREND_RESOURCE_STORAGE_GUEST_ELSE_SYSTEM) {
assert(!res->iov);
vrend_read_from_iovec(iov, num_iovs, info->offset,
res->ptr + info->box->x, info->box->width);
return 0;
}
if (res->storage == VREND_RESOURCE_STORAGE_BUFFER) {
GLuint map_flags = GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT;
struct virgl_sub_upload_data d;
d.box = info->box;
d.target = res->target;
if (!info->synchronized)
map_flags |= GL_MAP_UNSYNCHRONIZED_BIT;
glBindBufferARB(res->target, res->id);
data = glMapBufferRange(res->target, info->box->x, info->box->width, map_flags);
if (data == NULL) {
vrend_printf("map failed for element buffer\n");
vrend_read_from_iovec_cb(iov, num_iovs, info->offset, info->box->width, &iov_buffer_upload, &d);
} else {
vrend_read_from_iovec(iov, num_iovs, info->offset, data, info->box->width);
glUnmapBuffer(res->target);
}
glBindBufferARB(res->target, 0);
} else {
GLenum glformat;
GLenum gltype;
int need_temp = 0;
int elsize = util_format_get_blocksize(res->base.format);
int x = 0, y = 0;
bool compressed;
bool invert = false;
float depth_scale;
GLuint send_size = 0;
uint32_t stride = info->stride;
uint32_t layer_stride = info->layer_stride;
if (ctx)
vrend_use_program(ctx, 0);
else
glUseProgram(0);
if (!stride)
stride = util_format_get_nblocksx(res->base.format, u_minify(res->base.width0, info->level)) * elsize;
if (!layer_stride)
layer_stride = util_format_get_2d_size(res->base.format, stride,
u_minify(res->base.height0, info->level));
compressed = util_format_is_compressed(res->base.format);
if (num_iovs > 1 || compressed) {
need_temp = true;
}
if (vrend_state.use_core_profile == true && (res->y_0_top || (res->base.format == (enum pipe_format)VIRGL_FORMAT_Z24X8_UNORM))) {
need_temp = true;
if (res->y_0_top)
invert = true;
}
if (need_temp) {
send_size = util_format_get_nblocks(res->base.format, info->box->width,
info->box->height) * elsize * info->box->depth;
data = malloc(send_size);
if (!data)
return ENOMEM;
read_transfer_data(iov, num_iovs, data, res->base.format, info->offset,
stride, layer_stride, info->box, invert);
} else {
data = (char*)iov[0].iov_base + info->offset;
}
if (!need_temp) {
assert(stride);
glPixelStorei(GL_UNPACK_ROW_LENGTH, stride / elsize);
glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, layer_stride / stride);
} else
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
switch (elsize) {
case 1:
case 3:
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
break;
case 2:
case 6:
glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
break;
case 4:
default:
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
break;
case 8:
glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
break;
}
glformat = tex_conv_table[res->base.format].glformat;
gltype = tex_conv_table[res->base.format].gltype;
if ((!vrend_state.use_core_profile) && (res->y_0_top)) {
GLuint buffers;
if (res->readback_fb_id == 0 || (int)res->readback_fb_level != info->level) {
GLuint fb_id;
if (res->readback_fb_id)
glDeleteFramebuffers(1, &res->readback_fb_id);
glGenFramebuffers(1, &fb_id);
glBindFramebuffer(GL_FRAMEBUFFER, fb_id);
vrend_fb_bind_texture(res, 0, info->level, 0);
res->readback_fb_id = fb_id;
res->readback_fb_level = info->level;
} else {
glBindFramebuffer(GL_FRAMEBUFFER, res->readback_fb_id);
}
buffers = GL_COLOR_ATTACHMENT0;
glDrawBuffers(1, &buffers);
glDisable(GL_BLEND);
if (ctx) {
vrend_depth_test_enable(ctx, false);
vrend_alpha_test_enable(ctx, false);
vrend_stencil_test_enable(ctx, false);
} else {
glDisable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
glDisable(GL_STENCIL_TEST);
}
glPixelZoom(1.0f, res->y_0_top ? -1.0f : 1.0f);
glWindowPos2i(info->box->x, res->y_0_top ? (int)res->base.height0 - info->box->y : info->box->y);
glDrawPixels(info->box->width, info->box->height, glformat, gltype,
data);
} else {
uint32_t comp_size;
glBindTexture(res->target, res->id);
if (compressed) {
glformat = tex_conv_table[res->base.format].internalformat;
comp_size = util_format_get_nblocks(res->base.format, info->box->width,
info->box->height) * util_format_get_blocksize(res->base.format);
}
if (glformat == 0) {
glformat = GL_BGRA;
gltype = GL_UNSIGNED_BYTE;
}
x = info->box->x;
y = invert ? (int)res->base.height0 - info->box->y - info->box->height : info->box->y;
/* mipmaps are usually passed in one iov, and we need to keep the offset
* into the data in case we want to read back the data of a surface
* that can not be rendered. Since we can not assume that the whole texture
* is filled, we evaluate the offset for origin (0,0,0). Since it is also
* possible that a resource is reused and resized update the offset every time.
*/
if (info->level < VR_MAX_TEXTURE_2D_LEVELS) {
int64_t level_height = u_minify(res->base.height0, info->level);
res->mipmap_offsets[info->level] = info->offset -
((info->box->z * level_height + y) * stride + x * elsize);
}
if (res->base.format == (enum pipe_format)VIRGL_FORMAT_Z24X8_UNORM) {
/* we get values from the guest as 24-bit scaled integers
but we give them to the host GL and it interprets them
as 32-bit scaled integers, so we need to scale them here */
depth_scale = 256.0;
if (!vrend_state.use_core_profile)
glPixelTransferf(GL_DEPTH_SCALE, depth_scale);
else
vrend_scale_depth(data, send_size, depth_scale);
}
if (res->target == GL_TEXTURE_CUBE_MAP) {
GLenum ctarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + info->box->z;
if (compressed) {
glCompressedTexSubImage2D(ctarget, info->level, x, y,
info->box->width, info->box->height,
glformat, comp_size, data);
} else {
glTexSubImage2D(ctarget, info->level, x, y, info->box->width, info->box->height,
glformat, gltype, data);
}
} else if (res->target == GL_TEXTURE_3D || res->target == GL_TEXTURE_2D_ARRAY || res->target == GL_TEXTURE_CUBE_MAP_ARRAY) {
if (compressed) {
glCompressedTexSubImage3D(res->target, info->level, x, y, info->box->z,
info->box->width, info->box->height, info->box->depth,
glformat, comp_size, data);
} else {
glTexSubImage3D(res->target, info->level, x, y, info->box->z,
info->box->width, info->box->height, info->box->depth,
glformat, gltype, data);
}
} else if (res->target == GL_TEXTURE_1D) {
if (vrend_state.use_gles) {
/* Covers both compressed and none compressed. */
report_gles_missing_func(ctx, "gl[Compressed]TexSubImage1D");
} else if (compressed) {
glCompressedTexSubImage1D(res->target, info->level, info->box->x,
info->box->width,
glformat, comp_size, data);
} else {
glTexSubImage1D(res->target, info->level, info->box->x, info->box->width,
glformat, gltype, data);
}
} else {
if (compressed) {
glCompressedTexSubImage2D(res->target, info->level, x, res->target == GL_TEXTURE_1D_ARRAY ? info->box->z : y,
info->box->width, info->box->height,
glformat, comp_size, data);
} else {
glTexSubImage2D(res->target, info->level, x, res->target == GL_TEXTURE_1D_ARRAY ? info->box->z : y,
info->box->width,
res->target == GL_TEXTURE_1D_ARRAY ? info->box->depth : info->box->height,
glformat, gltype, data);
}
}
if (res->base.format == (enum pipe_format)VIRGL_FORMAT_Z24X8_UNORM) {
if (!vrend_state.use_core_profile)
glPixelTransferf(GL_DEPTH_SCALE, 1.0);
}
glBindTexture(res->target, 0);
}
if (stride && !need_temp) {
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
if (need_temp)
free(data);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'vrend: check that the transfer iov holds enough data for the data upload
Closes #140
Signed-off-by: Gert Wollny <[email protected]>
Reviewed-by: Emil Velikov <[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: gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
{
TIFF* tif = img->tif;
tileSeparateRoutine put = img->put.separate;
unsigned char *buf = NULL;
unsigned char *p0 = NULL, *p1 = NULL, *p2 = NULL, *pa = NULL;
uint32 row, y, nrow, rowstoread;
tmsize_t pos;
tmsize_t scanline;
uint32 rowsperstrip, offset_row;
uint32 imagewidth = img->width;
tmsize_t stripsize;
tmsize_t bufsize;
int32 fromskew, toskew;
int alpha = img->alpha;
int ret = 1, flip;
uint16 colorchannels;
stripsize = TIFFStripSize(tif);
bufsize = _TIFFMultiplySSize(tif,alpha?4:3,stripsize, "gtStripSeparate");
if (bufsize == 0) {
return (0);
}
flip = setorientation(img);
if (flip & FLIP_VERTICALLY) {
y = h - 1;
toskew = -(int32)(w + w);
}
else {
y = 0;
toskew = -(int32)(w - w);
}
switch( img->photometric )
{
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
case PHOTOMETRIC_PALETTE:
colorchannels = 1;
break;
default:
colorchannels = 3;
break;
}
TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
scanline = TIFFScanlineSize(tif);
fromskew = (w < imagewidth ? imagewidth - w : 0);
for (row = 0; row < h; row += nrow)
{
rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip;
nrow = (row + rowstoread > h ? h - row : rowstoread);
offset_row = row + img->row_offset;
if( buf == NULL )
{
if (_TIFFReadEncodedStripAndAllocBuffer(
tif, TIFFComputeStrip(tif, offset_row, 0),
(void**) &buf, bufsize,
((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1)
&& (buf == NULL || img->stoponerr))
{
ret = 0;
break;
}
p0 = buf;
if( colorchannels == 1 )
{
p2 = p1 = p0;
pa = (alpha?(p0+3*stripsize):NULL);
}
else
{
p1 = p0 + stripsize;
p2 = p1 + stripsize;
pa = (alpha?(p2+stripsize):NULL);
}
}
else if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0),
p0, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1)
&& img->stoponerr)
{
ret = 0;
break;
}
if (colorchannels > 1
&& TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1),
p1, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1)
&& img->stoponerr)
{
ret = 0;
break;
}
if (colorchannels > 1
&& TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2),
p2, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1)
&& img->stoponerr)
{
ret = 0;
break;
}
if (alpha)
{
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, colorchannels),
pa, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1)
&& img->stoponerr)
{
ret = 0;
break;
}
}
pos = ((row + img->row_offset) % rowsperstrip) * scanline + \
((tmsize_t) img->col_offset * img->samplesperpixel);
(*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos,
p2 + pos, (alpha?(pa+pos):NULL));
y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow);
}
if (flip & FLIP_HORIZONTALLY) {
uint32 line;
for (line = 0; line < h; line++) {
uint32 *left = raster + (line * w);
uint32 *right = left + w - 1;
while ( left < right ) {
uint32 temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
}
_TIFFfree(buf);
return (ret);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'RGBA interface: fix integer overflow potentially causing write heap buffer overflow, especially on 32 bit builds. Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16443. Credit to OSS Fuzz'</s> |
<s>[INST] Given the following code containing errors, provide 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* OGRExpatRealloc( void *ptr, size_t size )
{
if( CanAlloc(size) )
return realloc(ptr, size);
free(ptr);
return nullptr;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'OGRExpatRealloc(): fix double-free when size to allocate is above the default 10MB threshold. Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16178. Credit to OSS Fuzz'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: char * unescape(char * dest, const char * src)
{
while (*src) {
if (*src == '\\') {
++src;
switch (*src) {
case 'n': *dest = '\n'; break;
case 'r': *dest = '\r'; break;
case 't': *dest = '\t'; break;
case 'f': *dest = '\f'; break;
case 'v': *dest = '\v'; break;
default: *dest = *src;
}
} else {
*dest = *src;
}
++src;
++dest;
}
*dest = '\0';
return dest;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix various bugs found by OSS-Fuze.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _nc_find_type_entry(const char *string,
int type,
bool termcap)
{
struct name_table_entry const *ptr = NULL;
const HashData *data = _nc_get_hash_info(termcap);
int hashvalue = data->hash_of(string);
if (data->table_data[hashvalue] >= 0) {
const struct name_table_entry *const table = _nc_get_table(termcap);
ptr = table + data->table_data[hashvalue];
while (ptr->nte_type != type
|| !data->compare_names(ptr->nte_name, string)) {
if (ptr->nte_link < 0) {
ptr = 0;
break;
}
ptr = table + (ptr->nte_link + data->table_data[data->table_size]);
}
}
return ptr;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'ncurses 6.1 - patch 20191012
+ amend recent changes to ncurses*-config and pc-files to filter out
Debian linker-flags (report by Sven Joachim, cf: 20150516).
+ clarify relationship between tic, infocmp and captoinfo in manpage.
+ check for invalid hashcode in _nc_find_type_entry and
_nc_find_name_entry.
> fix several errata in tic (reports/testcases by "zjuchenyuan"):
+ check for invalid hashcode in _nc_find_entry.
+ check for missing character after backslash in fmt_entry
+ check for acsc with odd length in dump_entry in check for one-one
mapping (cf: 20060415);
+ check length when converting from old AIX box_chars_1 capability,
overlooked in changes to eliminate strcpy (cf: 20001007).
+ amend the ncurses*-config and pc-files to take into account the rpath'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: postprocess_terminfo(TERMTYPE2 *tp)
{
/*
* TERMINFO-TO-TERMINFO MAPPINGS FOR SOURCE TRANSLATION
* ----------------------------------------------------------------------
*/
/*
* Translate AIX forms characters.
*/
if (PRESENT(box_chars_1)) {
char buf2[MAX_TERMCAP_LENGTH];
string_desc result;
_nc_str_init(&result, buf2, sizeof(buf2));
_nc_safe_strcat(&result, acs_chars);
append_acs0(&result, 'l', box_chars_1[0]); /* ACS_ULCORNER */
append_acs0(&result, 'q', box_chars_1[1]); /* ACS_HLINE */
append_acs0(&result, 'k', box_chars_1[2]); /* ACS_URCORNER */
append_acs0(&result, 'x', box_chars_1[3]); /* ACS_VLINE */
append_acs0(&result, 'j', box_chars_1[4]); /* ACS_LRCORNER */
append_acs0(&result, 'm', box_chars_1[5]); /* ACS_LLCORNER */
append_acs0(&result, 'w', box_chars_1[6]); /* ACS_TTEE */
append_acs0(&result, 'u', box_chars_1[7]); /* ACS_RTEE */
append_acs0(&result, 'v', box_chars_1[8]); /* ACS_BTEE */
append_acs0(&result, 't', box_chars_1[9]); /* ACS_LTEE */
append_acs0(&result, 'n', box_chars_1[10]); /* ACS_PLUS */
if (buf2[0]) {
acs_chars = _nc_save_str(buf2);
_nc_warning("acsc string synthesized from AIX capabilities");
box_chars_1 = ABSENT_STRING;
}
}
/*
* ----------------------------------------------------------------------
*/
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'ncurses 6.1 - patch 20191012
+ amend recent changes to ncurses*-config and pc-files to filter out
Debian linker-flags (report by Sven Joachim, cf: 20150516).
+ clarify relationship between tic, infocmp and captoinfo in manpage.
+ check for invalid hashcode in _nc_find_type_entry and
_nc_find_name_entry.
> fix several errata in tic (reports/testcases by "zjuchenyuan"):
+ check for invalid hashcode in _nc_find_entry.
+ check for missing character after backslash in fmt_entry
+ check for acsc with odd length in dump_entry in check for one-one
mapping (cf: 20060415);
+ check length when converting from old AIX box_chars_1 capability,
overlooked in changes to eliminate strcpy (cf: 20001007).
+ amend the ncurses*-config and pc-files to take into account the rpath'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: fmt_entry(TERMTYPE2 *tterm,
PredFunc pred,
int content_only,
int suppress_untranslatable,
int infodump,
int numbers)
{
PredIdx i, j;
char buffer[MAX_TERMINFO_LENGTH + EXTRA_CAP];
char *capability;
NCURSES_CONST char *name;
int predval, len;
PredIdx num_bools = 0;
PredIdx num_values = 0;
PredIdx num_strings = 0;
bool outcount = 0;
#define WRAP_CONCAT1(s) wrap_concat1(s); outcount = TRUE
#define WRAP_CONCAT WRAP_CONCAT1(buffer)
len = 12; /* terminfo file-header */
if (pred == 0) {
cur_type = tterm;
pred = dump_predicate;
}
strcpy_DYN(&outbuf, 0);
if (content_only) {
column = indent; /* FIXME: workaround to prevent empty lines */
} else {
strcpy_DYN(&outbuf, tterm->term_names);
/*
* Colon is legal in terminfo descriptions, but not in termcap.
*/
if (!infodump) {
char *p = outbuf.text;
while (*p) {
if (*p == ':') {
*p = '=';
}
++p;
}
}
strcpy_DYN(&outbuf, separator);
column = (int) outbuf.used;
if (height > 1)
force_wrap();
}
for_each_boolean(j, tterm) {
i = BoolIndirect(j);
name = ExtBoolname(tterm, (int) i, bool_names);
assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
if (!version_filter(BOOLEAN, i))
continue;
else if (isObsolete(outform, name))
continue;
predval = pred(BOOLEAN, i);
if (predval != FAIL) {
_nc_STRCPY(buffer, name, sizeof(buffer));
if (predval <= 0)
_nc_STRCAT(buffer, "@", sizeof(buffer));
else if (i + 1 > num_bools)
num_bools = i + 1;
WRAP_CONCAT;
}
}
if (column != indent && height > 1)
force_wrap();
for_each_number(j, tterm) {
i = NumIndirect(j);
name = ExtNumname(tterm, (int) i, num_names);
assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
if (!version_filter(NUMBER, i))
continue;
else if (isObsolete(outform, name))
continue;
predval = pred(NUMBER, i);
if (predval != FAIL) {
if (tterm->Numbers[i] < 0) {
_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
"%s@", name);
} else {
size_t nn;
_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
"%s#", name);
nn = strlen(buffer);
_nc_SPRINTF(buffer + nn, _nc_SLIMIT(sizeof(buffer) - nn)
number_format(tterm->Numbers[i]),
tterm->Numbers[i]);
if (i + 1 > num_values)
num_values = i + 1;
}
WRAP_CONCAT;
}
}
if (column != indent && height > 1)
force_wrap();
len += (int) (num_bools
+ num_values * 2
+ strlen(tterm->term_names) + 1);
if (len & 1)
len++;
#undef CUR
#define CUR tterm->
if (outform == F_TERMCAP) {
if (VALID_STRING(termcap_reset)) {
if (VALID_STRING(init_3string)
&& !strcmp(init_3string, termcap_reset))
DISCARD(init_3string);
if (VALID_STRING(reset_2string)
&& !strcmp(reset_2string, termcap_reset))
DISCARD(reset_2string);
}
}
for_each_string(j, tterm) {
i = StrIndirect(j);
name = ExtStrname(tterm, (int) i, str_names);
assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
capability = tterm->Strings[i];
if (!version_filter(STRING, i))
continue;
else if (isObsolete(outform, name))
continue;
#if NCURSES_XNAMES
/*
* Extended names can be longer than 2 characters, but termcap programs
* cannot read those (filter them out).
*/
if (outform == F_TERMCAP && (strlen(name) > 2))
continue;
#endif
if (outform == F_TERMCAP) {
/*
* Some older versions of vi want rmir/smir to be defined
* for ich/ich1 to work. If they're not defined, force
* them to be output as defined and empty.
*/
if (PRESENT(insert_character) || PRESENT(parm_ich)) {
if (SAME_CAP(i, enter_insert_mode)
&& enter_insert_mode == ABSENT_STRING) {
_nc_STRCPY(buffer, "im=", sizeof(buffer));
WRAP_CONCAT;
continue;
}
if (SAME_CAP(i, exit_insert_mode)
&& exit_insert_mode == ABSENT_STRING) {
_nc_STRCPY(buffer, "ei=", sizeof(buffer));
WRAP_CONCAT;
continue;
}
}
/*
* termcap applications such as screen will be confused if sgr0
* is translated to a string containing rmacs. Filter that out.
*/
if (PRESENT(exit_attribute_mode)) {
if (SAME_CAP(i, exit_attribute_mode)) {
char *trimmed_sgr0;
char *my_sgr = set_attributes;
set_attributes = save_sgr;
trimmed_sgr0 = _nc_trim_sgr0(tterm);
if (strcmp(capability, trimmed_sgr0)) {
capability = trimmed_sgr0;
} else {
if (trimmed_sgr0 != exit_attribute_mode)
free(trimmed_sgr0);
}
set_attributes = my_sgr;
}
}
}
predval = pred(STRING, i);
buffer[0] = '\0';
if (predval != FAIL) {
if (VALID_STRING(capability)
&& i + 1 > num_strings)
num_strings = i + 1;
if (!VALID_STRING(capability)) {
_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
"%s@", name);
WRAP_CONCAT;
} else if (TcOutput()) {
char *srccap = _nc_tic_expand(capability, TRUE, numbers);
int params = ((i < (int) SIZEOF(parametrized))
? parametrized[i]
: ((*srccap == 'k')
? 0
: has_params(srccap)));
char *cv = _nc_infotocap(name, srccap, params);
if (cv == 0) {
if (outform == F_TCONVERR) {
_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
"%s=!!! %s WILL NOT CONVERT !!!",
name, srccap);
WRAP_CONCAT;
} else if (suppress_untranslatable) {
continue;
} else {
char *s = srccap, *d = buffer;
int need = 3 + (int) strlen(name);
while ((*d = *s++) != 0) {
if ((d - buffer + 1) >= (int) sizeof(buffer)) {
fprintf(stderr,
"%s: value for %s is too long\n",
_nc_progname,
name);
*d = '\0';
break;
}
if (*d == ':') {
*d++ = '\\';
*d = ':';
} else if (*d == '\\') {
*++d = *s++;
}
d++;
*d = '\0';
}
need += (int) (d - buffer);
wrap_concat("..", need, w1ST | wERR);
need -= 2;
wrap_concat(name, need, wOFF | wERR);
need -= (int) strlen(name);
wrap_concat("=", need, w2ND | wERR);
need -= 1;
wrap_concat(buffer, need, wEND | wERR);
outcount = TRUE;
}
} else {
wrap_concat3(name, "=", cv);
}
len += (int) strlen(capability) + 1;
} else {
char *src = _nc_tic_expand(capability,
outform == F_TERMINFO, numbers);
strcpy_DYN(&tmpbuf, 0);
strcpy_DYN(&tmpbuf, name);
strcpy_DYN(&tmpbuf, "=");
if (pretty
&& (outform == F_TERMINFO
|| outform == F_VARIABLE)) {
fmt_complex(tterm, name, src, 1);
} else {
strcpy_DYN(&tmpbuf, src);
}
len += (int) strlen(capability) + 1;
WRAP_CONCAT1(tmpbuf.text);
}
}
/* e.g., trimmed_sgr0 */
if (VALID_STRING(capability) &&
capability != tterm->Strings[i])
free(capability);
}
len += (int) (num_strings * 2);
/*
* This piece of code should be an effective inverse of the functions
* postprocess_terminfo() and postprocess_terminfo() in parse_entry.c.
* Much more work should be done on this to support dumping termcaps.
*/
if (tversion == V_HPUX) {
if (VALID_STRING(memory_lock)) {
_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
"meml=%s", memory_lock);
WRAP_CONCAT;
}
if (VALID_STRING(memory_unlock)) {
_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
"memu=%s", memory_unlock);
WRAP_CONCAT;
}
} else if (tversion == V_AIX) {
if (VALID_STRING(acs_chars)) {
bool box_ok = TRUE;
const char *acstrans = "lqkxjmwuvtn";
const char *cp;
char *tp, *sp, boxchars[11];
tp = boxchars;
for (cp = acstrans; *cp; cp++) {
sp = (strchr) (acs_chars, *cp);
if (sp)
*tp++ = sp[1];
else {
box_ok = FALSE;
break;
}
}
tp[0] = '\0';
if (box_ok) {
char *tmp = _nc_tic_expand(boxchars,
(outform == F_TERMINFO),
numbers);
_nc_STRCPY(buffer, "box1=", sizeof(buffer));
while (*tmp != '\0') {
size_t have = strlen(buffer);
size_t next = strlen(tmp);
size_t want = have + next + 1;
size_t last = next;
char save = '\0';
/*
* If the expanded string is too long for the buffer,
* chop it off and save the location where we chopped it.
*/
if (want >= sizeof(buffer)) {
save = tmp[last];
tmp[last] = '\0';
}
_nc_STRCAT(buffer, tmp, sizeof(buffer));
/*
* If we chopped the buffer, replace the missing piece and
* shift everything to append the remainder.
*/
if (save != '\0') {
next = 0;
tmp[last] = save;
while ((tmp[next] = tmp[last + next]) != '\0') {
++next;
}
} else {
break;
}
}
WRAP_CONCAT;
}
}
}
/*
* kludge: trim off trailer to avoid an extra blank line
* in infocmp -u output when there are no string differences
*/
if (outcount) {
bool trimmed = FALSE;
j = (PredIdx) outbuf.used;
if (wrapped && did_wrap) {
/* EMPTY */ ;
} else if (j >= 2
&& outbuf.text[j - 1] == '\t'
&& outbuf.text[j - 2] == '\n') {
outbuf.used -= 2;
trimmed = TRUE;
} else if (j >= 4
&& outbuf.text[j - 1] == ':'
&& outbuf.text[j - 2] == '\t'
&& outbuf.text[j - 3] == '\n'
&& outbuf.text[j - 4] == '\\') {
outbuf.used -= 4;
trimmed = TRUE;
}
if (trimmed) {
outbuf.text[outbuf.used] = '\0';
column = oldcol;
strcpy_DYN(&outbuf, " ");
}
}
#if 0
fprintf(stderr, "num_bools = %d\n", num_bools);
fprintf(stderr, "num_values = %d\n", num_values);
fprintf(stderr, "num_strings = %d\n", num_strings);
fprintf(stderr, "term_names=%s, len=%d, strlen(outbuf)=%d, outbuf=%s\n",
tterm->term_names, len, outbuf.used, outbuf.text);
#endif
/*
* Here's where we use infodump to trigger a more stringent length check
* for termcap-translation purposes.
* Return the length of the raw entry, without tc= expansions,
* It gives an idea of which entries are deadly to even *scan past*,
* as opposed to *use*.
*/
return (infodump ? len : (int) termcap_length(outbuf.text));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'ncurses 6.1 - patch 20191012
+ amend recent changes to ncurses*-config and pc-files to filter out
Debian linker-flags (report by Sven Joachim, cf: 20150516).
+ clarify relationship between tic, infocmp and captoinfo in manpage.
+ check for invalid hashcode in _nc_find_type_entry and
_nc_find_name_entry.
> fix several errata in tic (reports/testcases by "zjuchenyuan"):
+ check for invalid hashcode in _nc_find_entry.
+ check for missing character after backslash in fmt_entry
+ check for acsc with odd length in dump_entry in check for one-one
mapping (cf: 20060415);
+ check length when converting from old AIX box_chars_1 capability,
overlooked in changes to eliminate strcpy (cf: 20001007).
+ amend the ncurses*-config and pc-files to take into account the rpath'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _nc_find_entry(const char *string,
const HashValue * hash_table)
{
bool termcap = (hash_table != _nc_get_hash_table(FALSE));
const HashData *data = _nc_get_hash_info(termcap);
int hashvalue;
struct name_table_entry const *ptr = 0;
struct name_table_entry const *real_table;
hashvalue = data->hash_of(string);
if (data->table_data[hashvalue] >= 0) {
real_table = _nc_get_table(termcap);
ptr = real_table + data->table_data[hashvalue];
while (!data->compare_names(ptr->nte_name, string)) {
if (ptr->nte_link < 0) {
ptr = 0;
break;
}
ptr = real_table + (ptr->nte_link
+ data->table_data[data->table_size]);
}
}
return (ptr);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'ncurses 6.1 - patch 20191012
+ amend recent changes to ncurses*-config and pc-files to filter out
Debian linker-flags (report by Sven Joachim, cf: 20150516).
+ clarify relationship between tic, infocmp and captoinfo in manpage.
+ check for invalid hashcode in _nc_find_type_entry and
_nc_find_name_entry.
> fix several errata in tic (reports/testcases by "zjuchenyuan"):
+ check for invalid hashcode in _nc_find_entry.
+ check for missing character after backslash in fmt_entry
+ check for acsc with odd length in dump_entry in check for one-one
mapping (cf: 20060415);
+ check length when converting from old AIX box_chars_1 capability,
overlooked in changes to eliminate strcpy (cf: 20001007).
+ amend the ncurses*-config and pc-files to take into account the rpath'</s> |
<s>[INST] Given the following code containing errors, provide 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 TraceBezier(MVGInfo *mvg_info,
const size_t number_coordinates)
{
double
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
PrimitiveInfo
*primitive_info;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coefficients.
*/
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (double) SSIZE_MAX)
{
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
if (alpha > (double) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (double) SSIZE_MAX)
{
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
if (alpha > (double) quantum)
quantum=(size_t) alpha;
}
}
quantum=MagickMin(quantum/number_coordinates,BezierQuantum);
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
coefficients=(double *) AcquireQuantumMemory(number_coordinates,
sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*
sizeof(*points));
if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))
{
if (points != (PointInfo *) NULL)
points=(PointInfo *) RelinquishMagickMemory(points);
if (coefficients != (double *) NULL)
coefficients=(double *) RelinquishMagickMemory(coefficients);
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
control_points=quantum*number_coordinates;
if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse)
{
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickFalse);
}
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
if (TracePoint(p,points[i]) == MagickFalse)
{
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickFalse);
}
p+=p->coordinates;
}
if (TracePoint(p,end) == MagickFalse)
{
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickFalse);
}
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
primitive_info->closed_subpath=MagickFalse;
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], '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 boolean ReadICCProfile(j_decompress_ptr jpeg_info)
{
char
magick[12];
ErrorManager
*error_manager;
ExceptionInfo
*exception;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*icc_profile,
*profile;
/*
Read color profile.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
for (i=0; i < 12; i++)
magick[i]=(char) GetCharacter(jpeg_info);
if (LocaleCompare(magick,ICC_PROFILE) != 0)
{
/*
Not a ICC profile, return.
*/
for (i=0; i < (ssize_t) (length-12); i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
(void) GetCharacter(jpeg_info); /* id */
(void) GetCharacter(jpeg_info); /* markers */
length-=14;
error_manager=(ErrorManager *) jpeg_info->client_data;
exception=error_manager->exception;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
error_manager->profile=NULL;
icc_profile=(StringInfo *) GetImageProfile(image,"icc");
if (icc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(icc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: ICC, %.20g bytes",(double) length);
return(TRUE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1641'</s> |
<s>[INST] Given the following code containing errors, provide 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 boolean ReadICCProfile(j_decompress_ptr jpeg_info)
{
char
magick[12];
ErrorManager
*error_manager;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*icc_profile,
*profile;
/*
Read color profile.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
for (i=0; i < 12; i++)
magick[i]=(char) GetCharacter(jpeg_info);
if (LocaleCompare(magick,ICC_PROFILE) != 0)
{
/*
Not a ICC profile, return.
*/
for (i=0; i < (ssize_t) (length-12); i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
(void) GetCharacter(jpeg_info); /* id */
(void) GetCharacter(jpeg_info); /* markers */
length-=14;
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
error_manager->profile=NULL;
icc_profile=(StringInfo *) GetImageProfile(image,"icc");
if (icc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(icc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: ICC, %.20g bytes",(double) length);
return(TRUE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1641'</s> |
<s>[INST] Given the following code containing errors, provide 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 WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
imageListLength;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric,
predictor;
unsigned char
*pixels;
/*
Open TIFF 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);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
if (image->exception.severity > ErrorException)
{
TIFFClose(tiff);
return(MagickFalse);
}
(void) DeleteImageProfile(image,"tiff:37724");
scene=0;
debug=IsEventLogging();
(void) debug;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
#if defined(COMPRESSION_WEBP)
case WebPCompression:
{
compress_tag=COMPRESSION_WEBP;
break;
}
#endif
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
#if defined(COMPRESSION_ZSTD)
case ZstdCompression:
{
compress_tag=COMPRESSION_ZSTD;
break;
}
#endif
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) ||
(compress_tag == COMPRESSION_CCITTFAX4))
{
if ((photometric != PHOTOMETRIC_MINISWHITE) &&
(photometric != PHOTOMETRIC_MINISBLACK))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
predictor=0;
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
if (image->colorspace == YCbCrColorspace)
{
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
break;
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
break;
}
#if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP)
case COMPRESSION_WEBP:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality);
if (image_info->quality >= 100)
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1);
break;
}
#endif
#if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD)
case COMPRESSION_ZSTD:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/
100.0);
break;
}
#endif
default:
break;
}
option=GetImageOption(image_info,"tiff:predictor");
if (option != (const char * ) NULL)
predictor=(size_t) strtol(option,(char **) NULL,10);
if (predictor != 0)
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (imageListLength > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
imageListLength);
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
else
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) imageListLength;
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
{
if (red != (uint16 *) NULL)
red=(uint16 *) RelinquishMagickMemory(red);
if (green != (uint16 *) NULL)
green=(uint16 *) RelinquishMagickMemory(green);
if (blue != (uint16 *) NULL)
blue=(uint16 *) RelinquishMagickMemory(blue);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize TIFF colormap.
*/
(void) memset(red,0,65536*sizeof(*red));
(void) memset(green,0,65536*sizeof(*green));
(void) memset(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
if (image->exception.severity > ErrorException)
break;
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1560'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ModuleExport size_t RegisterXWDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)");
#if defined(MAGICKCORE_X11_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadXWDImage;
entry->encoder=(EncodeImageHandler *) WriteXWDImage;
#endif
entry->magick=(IsImageFormatHandler *) IsXWD;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1553'</s> |
<s>[INST] Given the following code containing errors, provide 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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CheckOverflowException(length,width,height) \
(((height) != 0) && ((length)/((size_t) height) != ((size_t) width)))
char
*comment;
Image
*image;
IndexPacket
index;
int
x_status;
MagickBooleanType
authentic_colormap;
MagickStatusType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register size_t
pixel;
size_t
length;
ssize_t
count,
y;
unsigned long
lsb_first;
XColor
*colors;
XImage
*ximage;
XWDFileHeader
header;
/*
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read in header information.
*/
count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header);
if (count != sz_XWDheader)
ThrowReaderException(CorruptImageError,"UnableToReadImageHeader");
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
MSBOrderLong((unsigned char *) &header,sz_XWDheader);
/*
Check to see if the dump file is in the proper format.
*/
if (header.file_version != XWD_FILE_VERSION)
ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch");
if (header.header_size < sz_XWDheader)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.visual_class)
{
case StaticGray:
case GrayScale:
{
if (header.bits_per_pixel != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case StaticColor:
case PseudoColor:
{
if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) ||
(header.ncolors == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case TrueColor:
case DirectColor:
{
if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) &&
(header.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.pixmap_format)
{
case XYBitmap:
{
if (header.pixmap_depth != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case XYPixmap:
case ZPixmap:
{
if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.bitmap_pad)
{
case 8:
case 16:
case 32:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.bitmap_unit)
{
case 8:
case 16:
case 32:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.byte_order)
{
case LSBFirst:
case MSBFirst:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.bitmap_bit_order)
{
case LSBFirst:
case MSBFirst:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header.ncolors > 65535)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
length=(size_t) (header.header_size-sz_XWDheader);
if ((length+1) != ((size_t) ((CARD32) (length+1))))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length,(unsigned char *) comment);
comment[length]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/*
Initialize the X image.
*/
ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage));
if (ximage == (XImage *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ximage->depth=(int) header.pixmap_depth;
ximage->format=(int) header.pixmap_format;
ximage->xoffset=(int) header.xoffset;
ximage->data=(char *) NULL;
ximage->width=(int) header.pixmap_width;
ximage->height=(int) header.pixmap_height;
ximage->bitmap_pad=(int) header.bitmap_pad;
ximage->bytes_per_line=(int) header.bytes_per_line;
ximage->byte_order=(int) header.byte_order;
ximage->bitmap_unit=(int) header.bitmap_unit;
ximage->bitmap_bit_order=(int) header.bitmap_bit_order;
ximage->bits_per_pixel=(int) header.bits_per_pixel;
ximage->red_mask=header.red_mask;
ximage->green_mask=header.green_mask;
ximage->blue_mask=header.blue_mask;
if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) ||
(ximage->format < 0) || (ximage->byte_order < 0) ||
(ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) ||
(ximage->bytes_per_line < 0))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->width > 65535) || (ximage->height > 65535))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
x_status=XInitImage(ximage);
if (x_status == 0)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
/*
Read colormap.
*/
authentic_colormap=MagickFalse;
colors=(XColor *) NULL;
if (header.ncolors != 0)
{
XWDColor
color;
colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors,
sizeof(*colors));
if (colors == (XColor *) NULL)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) header.ncolors; i++)
{
count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color);
if (count != sz_XWDColor)
{
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
colors[i].pixel=color.pixel;
colors[i].red=color.red;
colors[i].green=color.green;
colors[i].blue=color.blue;
colors[i].flags=(char) color.flags;
if (color.flags != 0)
authentic_colormap=MagickTrue;
}
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
for (i=0; i < (ssize_t) header.ncolors; i++)
{
MSBOrderLong((unsigned char *) &colors[i].pixel,
sizeof(colors[i].pixel));
MSBOrderShort((unsigned char *) &colors[i].red,3*
sizeof(colors[i].red));
}
}
/*
Allocate the pixel buffer.
*/
length=(size_t) ximage->bytes_per_line*ximage->height;
if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (ximage->format != ZPixmap)
{
size_t
extent;
extent=length;
length*=ximage->depth;
if (CheckOverflowException(length,extent,ximage->depth))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data));
if (ximage->data == (char *) NULL)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
count=ReadBlob(image,length,(unsigned char *) ximage->data);
if (count != (ssize_t) length)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
/*
Convert image to MIFF format.
*/
image->columns=(size_t) ximage->width;
image->rows=(size_t) ximage->height;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((header.ncolors == 0U) || (ximage->red_mask != 0) ||
(ximage->green_mask != 0) || (ximage->blue_mask != 0))
image->storage_class=DirectClass;
else
image->storage_class=PseudoClass;
image->colors=header.ncolors;
if (image_info->ping == MagickFalse)
switch (image->storage_class)
{
case DirectClass:
default:
{
register size_t
color;
size_t
blue_mask,
blue_shift,
green_mask,
green_shift,
red_mask,
red_shift;
/*
Determine shift and mask for red, green, and blue.
*/
red_mask=ximage->red_mask;
red_shift=0;
while ((red_mask != 0) && ((red_mask & 0x01) == 0))
{
red_mask>>=1;
red_shift++;
}
green_mask=ximage->green_mask;
green_shift=0;
while ((green_mask != 0) && ((green_mask & 0x01) == 0))
{
green_mask>>=1;
green_shift++;
}
blue_mask=ximage->blue_mask;
blue_shift=0;
while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))
{
blue_mask>>=1;
blue_shift++;
}
/*
Convert X image to DirectClass packets.
*/
if ((image->colors != 0) && (authentic_colormap != MagickFalse))
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
index=ConstrainColormapIndex(image,(ssize_t) (pixel >>
red_shift) & red_mask);
SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red));
index=ConstrainColormapIndex(image,(ssize_t) (pixel >>
green_shift) & green_mask);
SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t)
index].green));
index=ConstrainColormapIndex(image,(ssize_t) (pixel >>
blue_shift) & blue_mask);
SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
color=(pixel >> red_shift) & red_mask;
if (red_mask != 0)
color=(color*65535UL)/red_mask;
SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));
color=(pixel >> green_shift) & green_mask;
if (green_mask != 0)
color=(color*65535UL)/green_mask;
SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color));
color=(pixel >> blue_shift) & blue_mask;
if (blue_mask != 0)
color=(color*65535UL)/blue_mask;
SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
case PseudoClass:
{
/*
Convert X image to PseudoClass packets.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleShortToQuantum(colors[i].red);
image->colormap[i].green=ScaleShortToQuantum(colors[i].green);
image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int)
x,(int) y));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
}
/*
Free image and colormap.
*/
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1553'</s> |
<s>[INST] Given the following code containing errors, provide 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 *ReadMATImageV4(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
typedef struct {
unsigned char Type[4];
unsigned int nRows;
unsigned int nCols;
unsigned int imagf;
unsigned int nameLen;
} MAT4_HDR;
long
ldblk;
EndianType
endian;
Image
*rotated_image;
MagickBooleanType
status;
MAT4_HDR
HDR;
QuantumInfo
*quantum_info;
QuantumFormatType
format_type;
register ssize_t
i;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned int
depth;
quantum_info=(QuantumInfo *) NULL;
(void) SeekBlob(image,0,SEEK_SET);
status=MagickTrue;
while (EOFBlob(image) == MagickFalse)
{
/*
Object parser loop.
*/
ldblk=ReadBlobLSBLong(image);
if ((ldblk > 9999) || (ldblk < 0))
break;
HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */
HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */
HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */
HDR.Type[0]=ldblk; /* M digit */
if (HDR.Type[3] != 0)
break; /* Data format */
if (HDR.Type[2] != 0)
break; /* Always 0 */
if (HDR.Type[0] == 0)
{
HDR.nRows=ReadBlobLSBLong(image);
HDR.nCols=ReadBlobLSBLong(image);
HDR.imagf=ReadBlobLSBLong(image);
HDR.nameLen=ReadBlobLSBLong(image);
endian=LSBEndian;
}
else
{
HDR.nRows=ReadBlobMSBLong(image);
HDR.nCols=ReadBlobMSBLong(image);
HDR.imagf=ReadBlobMSBLong(image);
HDR.nameLen=ReadBlobMSBLong(image);
endian=MSBEndian;
}
if ((HDR.imagf != 0) && (HDR.imagf != 1))
break;
if (HDR.nameLen > 0xFFFF)
return(DestroyImageList(image));
for (i=0; i < (ssize_t) HDR.nameLen; i++)
{
int
byte;
/*
Skip matrix name.
*/
byte=ReadBlobByte(image);
if (byte == EOF)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
image->columns=(size_t) HDR.nRows;
image->rows=(size_t) HDR.nCols;
if ((image->columns == 0) || (image->rows == 0))
return(DestroyImageList(image));
if (image_info->ping != MagickFalse)
{
Swap(image->columns,image->rows);
if(HDR.imagf==1) ldblk *= 2;
SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);
if ((image->columns == 0) || (image->rows == 0))
return(image->previous == (Image *) NULL ? DestroyImageList(image)
: image);
goto skip_reading_current;
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(DestroyImageList(image));
switch(HDR.Type[1])
{
case 0:
format_type=FloatingPointQuantumFormat;
depth=64;
break;
case 1:
format_type=FloatingPointQuantumFormat;
depth=32;
break;
case 2:
format_type=UnsignedQuantumFormat;
depth=16;
break;
case 3:
format_type=SignedQuantumFormat;
depth=16;
break;
case 4:
format_type=UnsignedQuantumFormat;
depth=8;
break;
default:
format_type=UnsignedQuantumFormat;
depth=8;
break;
}
image->depth=depth;
if (HDR.Type[0] != 0)
SetQuantumEndian(image,quantum_info,MSBEndian);
status=SetQuantumFormat(image,quantum_info,format_type);
status=SetQuantumDepth(image,quantum_info,depth);
status=SetQuantumEndian(image,quantum_info,endian);
SetQuantumScale(quantum_info,1.0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
if (count == -1)
break;
q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
FixSignedValues(image,q,(int) image->columns);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (HDR.imagf == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
/*
Read complex pixels.
*/
count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
if (count == -1)
break;
if (HDR.Type[1] == 0)
InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);
else
InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
rotated_image=RotateImage(image,90.0,exception);
if (rotated_image != (Image *) NULL)
{
rotated_image->page.x=0;
rotated_image->page.y=0;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->blob);
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Allocate next image structure.
*/
skip_reading_current:
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1554'</s> |
<s>[INST] Given the following code containing errors, provide 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 *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
quantum_info=(QuantumInfo *) NULL;
image = AcquireImage(image_info);
image2 = (Image *) NULL;
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=(ImageInfo *) NULL;
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image=ReadMATImageV4(image_info,image,exception);
if (image == NULL)
{
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
return((Image *) NULL);
}
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
{
MATLAB_KO:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
if (filepos != (unsigned int) filepos)
break;
if(SeekBlob(image,filepos,SEEK_SET) != filepos) break;
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))
goto MATLAB_KO;
filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4;
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
clone_info=CloneImageInfo(image_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if (MATLAB_HDR.DataType != miMATRIX)
{
clone_info=DestroyImageInfo(clone_info);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (image2 != image)
DeleteImageFromList(&image2);
#endif
continue; /* skip another objects. */
}
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
}
break;
default:
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
{
if ((image2 != (Image*) NULL) && (image2 != image))
{
CloseBlob(image2);
DeleteImageFromList(&image2);
}
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
}
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (((size_t) size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
/* data size */
if (ReadBlob(image2, 4, (unsigned char *) &size) != 4)
goto MATLAB_KO;
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
}
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
image->colors = GetQuantumRange(image->depth);
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image);
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->blob);
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
if(!EOFBlob(image) && TellBlob(image)<filepos)
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
}
END_OF_READING:
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
if (tmp == image2)
image2=(Image *) NULL;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader")
return(image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1554'</s> |
<s>[INST] Given the following code containing errors, provide 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 mutt_init (int skip_sys_rc, LIST *commands)
{
struct passwd *pw;
struct utsname utsname;
char *p, buffer[STRING], error[STRING];
int i, default_rc = 0, need_pause = 0;
BUFFER err;
memset (&err, 0, sizeof (err));
err.data = error;
err.dsize = sizeof (error);
Groups = hash_create (1031, 0);
ReverseAlias = hash_create (1031, 1);
mutt_menu_init ();
/*
* XXX - use something even more difficult to predict?
*/
snprintf (AttachmentMarker, sizeof (AttachmentMarker),
"\033]9;%ld\a", (long) time (NULL));
/* on one of the systems I use, getcwd() does not return the same prefix
as is listed in the passwd file */
if ((p = getenv ("HOME")))
Homedir = safe_strdup (p);
/* Get some information about the user */
if ((pw = getpwuid (getuid ())))
{
char rnbuf[STRING];
Username = safe_strdup (pw->pw_name);
if (!Homedir)
Homedir = safe_strdup (pw->pw_dir);
Realname = safe_strdup (mutt_gecos_name (rnbuf, sizeof (rnbuf), pw));
Shell = safe_strdup (pw->pw_shell);
endpwent ();
}
else
{
if (!Homedir)
{
mutt_endwin (NULL);
fputs (_("unable to determine home directory"), stderr);
exit (1);
}
if ((p = getenv ("USER")))
Username = safe_strdup (p);
else
{
mutt_endwin (NULL);
fputs (_("unable to determine username"), stderr);
exit (1);
}
Shell = safe_strdup ((p = getenv ("SHELL")) ? p : "/bin/sh");
}
#ifdef DEBUG
/* Start up debugging mode if requested */
if (debuglevel > 0)
start_debug ();
#endif
/* And about the host... */
uname (&utsname);
/* some systems report the FQDN instead of just the hostname */
if ((p = strchr (utsname.nodename, '.')))
{
Hostname = mutt_substrdup (utsname.nodename, p);
p++;
strfcpy (buffer, p, sizeof (buffer)); /* save the domain for below */
}
else
Hostname = safe_strdup (utsname.nodename);
#ifndef DOMAIN
#define DOMAIN buffer
if (!p && getdnsdomainname (buffer, sizeof (buffer)) == -1)
Fqdn = safe_strdup ("@");
else
#endif /* DOMAIN */
if (*DOMAIN != '@')
{
Fqdn = safe_malloc (mutt_strlen (DOMAIN) + mutt_strlen (Hostname) + 2);
sprintf (Fqdn, "%s.%s", NONULL(Hostname), DOMAIN); /* __SPRINTF_CHECKED__ */
}
else
Fqdn = safe_strdup(NONULL(Hostname));
if ((p = getenv ("MAIL")))
Spoolfile = safe_strdup (p);
else if ((p = getenv ("MAILDIR")))
Spoolfile = safe_strdup (p);
else
{
#ifdef HOMESPOOL
mutt_concat_path (buffer, NONULL (Homedir), MAILPATH, sizeof (buffer));
#else
mutt_concat_path (buffer, MAILPATH, NONULL(Username), sizeof (buffer));
#endif
Spoolfile = safe_strdup (buffer);
}
if ((p = getenv ("MAILCAPS")))
MailcapPath = safe_strdup (p);
else
{
/* Default search path from RFC1524 */
MailcapPath = safe_strdup ("~/.mailcap:" PKGDATADIR "/mailcap:" SYSCONFDIR "/mailcap:/etc/mailcap:/usr/etc/mailcap:/usr/local/etc/mailcap");
}
Tempdir = safe_strdup ((p = getenv ("TMPDIR")) ? p : "/tmp");
p = getenv ("VISUAL");
if (!p)
{
p = getenv ("EDITOR");
if (!p)
p = "vi";
}
Editor = safe_strdup (p);
Visual = safe_strdup (p);
if ((p = getenv ("REPLYTO")) != NULL)
{
BUFFER buf, token;
snprintf (buffer, sizeof (buffer), "Reply-To: %s", p);
memset (&buf, 0, sizeof (buf));
buf.data = buf.dptr = buffer;
buf.dsize = mutt_strlen (buffer);
memset (&token, 0, sizeof (token));
parse_my_hdr (&token, &buf, 0, &err);
FREE (&token.data);
}
if ((p = getenv ("EMAIL")) != NULL)
From = rfc822_parse_adrlist (NULL, p);
mutt_set_langinfo_charset ();
mutt_set_charset (Charset);
Matches = safe_calloc (Matches_listsize, sizeof (char *));
/* Set standard defaults */
for (i = 0; MuttVars[i].option; i++)
{
mutt_set_default (&MuttVars[i]);
mutt_restore_default (&MuttVars[i]);
}
CurrentMenu = MENU_MAIN;
#ifndef LOCALES_HACK
/* Do we have a locale definition? */
if (((p = getenv ("LC_ALL")) != NULL && p[0]) ||
((p = getenv ("LANG")) != NULL && p[0]) ||
((p = getenv ("LC_CTYPE")) != NULL && p[0]))
set_option (OPTLOCALES);
#endif
#ifdef HAVE_GETSID
/* Unset suspend by default if we're the session leader */
if (getsid(0) == getpid())
unset_option (OPTSUSPEND);
#endif
mutt_init_history ();
/*
*
* BIG FAT WARNING
*
* When changing the code which looks for a configuration file,
* please also change the corresponding code in muttbug.sh.in.
*
*
*/
if (!Muttrc)
{
snprintf (buffer, sizeof(buffer), "%s/.muttrc-%s", NONULL(Homedir), MUTT_VERSION);
if (access(buffer, F_OK) == -1)
snprintf (buffer, sizeof(buffer), "%s/.muttrc", NONULL(Homedir));
if (access(buffer, F_OK) == -1)
snprintf (buffer, sizeof (buffer), "%s/.mutt/muttrc-%s", NONULL(Homedir), MUTT_VERSION);
if (access(buffer, F_OK) == -1)
snprintf (buffer, sizeof (buffer), "%s/.mutt/muttrc", NONULL(Homedir));
if (access(buffer, F_OK) == -1) /* default to .muttrc for alias_file */
snprintf (buffer, sizeof(buffer), "%s/.muttrc", NONULL(Homedir));
default_rc = 1;
Muttrc = safe_strdup (buffer);
}
else
{
strfcpy (buffer, Muttrc, sizeof (buffer));
FREE (&Muttrc);
mutt_expand_path (buffer, sizeof (buffer));
Muttrc = safe_strdup (buffer);
}
FREE (&AliasFile);
AliasFile = safe_strdup (NONULL(Muttrc));
/* Process the global rc file if it exists and the user hasn't explicity
requested not to via "-n". */
if (!skip_sys_rc)
{
snprintf (buffer, sizeof(buffer), "%s/Muttrc-%s", SYSCONFDIR, MUTT_VERSION);
if (access (buffer, F_OK) == -1)
snprintf (buffer, sizeof(buffer), "%s/Muttrc", SYSCONFDIR);
if (access (buffer, F_OK) == -1)
snprintf (buffer, sizeof (buffer), "%s/Muttrc-%s", PKGDATADIR, MUTT_VERSION);
if (access (buffer, F_OK) == -1)
snprintf (buffer, sizeof (buffer), "%s/Muttrc", PKGDATADIR);
if (access (buffer, F_OK) != -1)
{
if (source_rc (buffer, &err) != 0)
{
fputs (err.data, stderr);
fputc ('\n', stderr);
need_pause = 1;
}
}
}
/* Read the user's initialization file. */
if (access (Muttrc, F_OK) != -1)
{
if (!option (OPTNOCURSES))
endwin ();
if (source_rc (Muttrc, &err) != 0)
{
fputs (err.data, stderr);
fputc ('\n', stderr);
need_pause = 1;
}
}
else if (!default_rc)
{
/* file specified by -F does not exist */
snprintf (buffer, sizeof (buffer), "%s: %s", Muttrc, strerror (errno));
mutt_endwin (buffer);
exit (1);
}
if (mutt_execute_commands (commands) != 0)
need_pause = 1;
if (need_pause && !option (OPTNOCURSES))
{
if (mutt_any_key_to_continue (NULL) == -1)
mutt_exit(1);
}
mutt_read_histfile ();
#if 0
set_option (OPTWEED); /* turn weeding on by default */
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-668'], 'message': 'use a 64-bit random value in temporary filenames.
closes #3158'</s> |
<s>[INST] Given the following code containing errors, provide 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 report_block(struct dquot *dquot, unsigned int blk, char *bitmap,
int (*process_dquot) (struct dquot *, void *),
void *data)
{
struct qtree_mem_dqinfo *info =
&dquot->dq_h->qh_info.u.v2_mdqi.dqi_qtree;
dqbuf_t buf = getdqbuf();
struct qt_disk_dqdbheader *dh;
char *ddata;
int entries, i;
if (!buf)
return 0;
set_bit(bitmap, blk);
read_blk(dquot->dq_h, blk, buf);
dh = (struct qt_disk_dqdbheader *)buf;
ddata = buf + sizeof(struct qt_disk_dqdbheader);
entries = ext2fs_le16_to_cpu(dh->dqdh_entries);
for (i = 0; i < qtree_dqstr_in_blk(info);
i++, ddata += info->dqi_entry_size)
if (!qtree_entry_unused(info, ddata)) {
dquot->dq_dqb.u.v2_mdqb.dqb_off =
(blk << QT_BLKSIZE_BITS) +
sizeof(struct qt_disk_dqdbheader) +
i * info->dqi_entry_size;
info->dqi_ops->disk2mem_dqblk(dquot, ddata);
if (process_dquot(dquot, data) < 0)
break;
}
freedqbuf(buf);
return entries;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'libsupport: add checks to prevent buffer overrun bugs in quota code
A maliciously corrupted file systems can trigger buffer overruns in
the quota code used by e2fsck. To fix this, add sanity checks to the
quota header fields as well as to block number references in the quota
tree.
Addresses: CVE-2019-5094
Addresses: TALOS-2019-0887
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: static void check_reference(struct quota_handle *h, unsigned int blk)
{
if (blk >= h->qh_info.u.v2_mdqi.dqi_qtree.dqi_blocks)
log_err("Illegal reference (%u >= %u) in %s quota file. "
"Quota file is probably corrupted.\n"
"Please run e2fsck (8) to fix it.",
blk,
h->qh_info.u.v2_mdqi.dqi_qtree.dqi_blocks,
quota_type2name(h->qh_type));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'libsupport: add checks to prevent buffer overrun bugs in quota code
A maliciously corrupted file systems can trigger buffer overruns in
the quota code used by e2fsck. To fix this, add sanity checks to the
quota header fields as well as to block number references in the quota
tree.
Addresses: CVE-2019-5094
Addresses: TALOS-2019-0887
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: static int v2_init_io(struct quota_handle *h)
{
struct v2_disk_dqinfo ddqinfo;
h->qh_info.u.v2_mdqi.dqi_qtree.dqi_entry_size =
sizeof(struct v2r1_disk_dqblk);
h->qh_info.u.v2_mdqi.dqi_qtree.dqi_ops = &v2r1_fmt_ops;
/* Read information about quotafile */
if (h->e2fs_read(&h->qh_qf, V2_DQINFOOFF, &ddqinfo,
sizeof(ddqinfo)) != sizeof(ddqinfo))
return -1;
v2_disk2memdqinfo(&h->qh_info, &ddqinfo);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'libsupport: add checks to prevent buffer overrun bugs in quota code
A maliciously corrupted file systems can trigger buffer overruns in
the quota code used by e2fsck. To fix this, add sanity checks to the
quota header fields as well as to block number references in the quota
tree.
Addresses: CVE-2019-5094
Addresses: TALOS-2019-0887
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: fribidi_get_par_embedding_levels_ex (
/* input */
const FriBidiCharType *bidi_types,
const FriBidiBracketType *bracket_types,
const FriBidiStrIndex len,
/* input and output */
FriBidiParType *pbase_dir,
/* output */
FriBidiLevel *embedding_levels
)
{
FriBidiLevel base_level, *base_level_per_iso_level = NULL, max_level = 0;
FriBidiParType base_dir;
FriBidiRun *main_run_list = NULL, *explicits_list = NULL, *pp;
fribidi_boolean status = false;
int max_iso_level = 0;
if UNLIKELY
(!len)
{
status = true;
goto out;
}
DBG ("in fribidi_get_par_embedding_levels");
fribidi_assert (bidi_types);
fribidi_assert (pbase_dir);
fribidi_assert (embedding_levels);
/* Determinate character types */
{
/* Get run-length encoded character types */
main_run_list = run_list_encode_bidi_types (bidi_types, bracket_types, len);
if UNLIKELY
(!main_run_list) goto out;
}
/* Find base level */
/* If no strong base_dir was found, resort to the weak direction
that was passed on input. */
base_level = FRIBIDI_DIR_TO_LEVEL (*pbase_dir);
if (!FRIBIDI_IS_STRONG (*pbase_dir))
/* P2. P3. Search for first strong character and use its direction as
base direction */
{
int valid_isolate_count = 0;
for_run_list (pp, main_run_list)
{
if (RL_TYPE(pp) == FRIBIDI_TYPE_PDI)
{
/* Ignore if there is no matching isolate */
if (valid_isolate_count>0)
valid_isolate_count--;
}
else if (FRIBIDI_IS_ISOLATE(RL_TYPE(pp)))
valid_isolate_count++;
else if (valid_isolate_count==0 && FRIBIDI_IS_LETTER (RL_TYPE (pp)))
{
base_level = FRIBIDI_DIR_TO_LEVEL (RL_TYPE (pp));
*pbase_dir = FRIBIDI_LEVEL_TO_DIR (base_level);
break;
}
}
}
base_dir = FRIBIDI_LEVEL_TO_DIR (base_level);
DBG2 (" base level : %c", fribidi_char_from_level (base_level));
DBG2 (" base dir : %s", fribidi_get_bidi_type_name (base_dir));
base_level_per_iso_level = fribidi_malloc(sizeof(base_level_per_iso_level[0]) *
FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL);
base_level_per_iso_level[0] = base_level;
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_types_re (main_run_list);
}
# endif /* DEBUG */
/* Explicit Levels and Directions */
DBG ("explicit levels and directions");
{
FriBidiLevel level, new_level = 0;
int isolate_level = 0;
FriBidiCharType override, new_override;
FriBidiStrIndex i;
int stack_size, over_pushed, first_interval;
int valid_isolate_count = 0;
int isolate_overflow = 0;
int isolate = 0; /* The isolate status flag */
struct
{
FriBidiCharType override; /* only LTR, RTL and ON are valid */
FriBidiLevel level;
int isolate;
int isolate_level;
} *status_stack;
FriBidiRun temp_link;
FriBidiRun **run_per_isolate_level; /* Connect the isolate levels */
run_per_isolate_level = fribidi_malloc(sizeof(run_per_isolate_level[0])
* FRIBIDI_BIDI_MAX_RESOLVED_LEVELS);
memset(run_per_isolate_level, 0, sizeof(run_per_isolate_level[0])
* FRIBIDI_BIDI_MAX_RESOLVED_LEVELS);
/* explicits_list is a list like main_run_list, that holds the explicit
codes that are removed from main_run_list, to reinsert them later by
calling the shadow_run_list.
*/
explicits_list = new_run_list ();
if UNLIKELY
(!explicits_list) goto out;
/* X1. Begin by setting the current embedding level to the paragraph
embedding level. Set the directional override status to neutral,
and directional isolate status to false.
Process each character iteratively, applying rules X2 through X8.
Only embedding levels from 0 to 123 are valid in this phase. */
level = base_level;
override = FRIBIDI_TYPE_ON;
/* stack */
stack_size = 0;
over_pushed = 0;
first_interval = 0;
valid_isolate_count = 0;
isolate_overflow = 0;
status_stack = fribidi_malloc (sizeof (status_stack[0]) *
FRIBIDI_BIDI_MAX_RESOLVED_LEVELS);
for_run_list (pp, main_run_list)
{
FriBidiCharType this_type = RL_TYPE (pp);
RL_ISOLATE_LEVEL (pp) = isolate_level;
if (FRIBIDI_IS_EXPLICIT_OR_BN (this_type))
{
if (FRIBIDI_IS_STRONG (this_type))
{ /* LRE, RLE, LRO, RLO */
/* 1. Explicit Embeddings */
/* X2. With each RLE, compute the least greater odd
embedding level. */
/* X3. With each LRE, compute the least greater even
embedding level. */
/* 2. Explicit Overrides */
/* X4. With each RLO, compute the least greater odd
embedding level. */
/* X5. With each LRO, compute the least greater even
embedding level. */
new_override = FRIBIDI_EXPLICIT_TO_OVERRIDE_DIR (this_type);
for (i = RL_LEN (pp); i; i--)
{
new_level =
((level + FRIBIDI_DIR_TO_LEVEL (this_type) + 2) & ~1) -
FRIBIDI_DIR_TO_LEVEL (this_type);
isolate = 0;
PUSH_STATUS;
}
}
else if (this_type == FRIBIDI_TYPE_PDF)
{
/* 3. Terminating Embeddings and overrides */
/* X7. With each PDF, determine the matching embedding or
override code. */
for (i = RL_LEN (pp); i; i--)
{
if (stack_size && status_stack[stack_size-1].isolate != 0)
break;
POP_STATUS;
}
}
/* X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes. */
/* Remove element and add it to explicits_list */
RL_LEVEL (pp) = FRIBIDI_SENTINEL;
temp_link.next = pp->next;
move_node_before (pp, explicits_list);
pp = &temp_link;
}
else if (this_type == FRIBIDI_TYPE_PDI)
/* X6a. pop the direction of the stack */
{
for (i = RL_LEN (pp); i; i--)
{
if (isolate_overflow > 0)
{
isolate_overflow--;
RL_LEVEL (pp) = level;
}
else if (valid_isolate_count > 0)
{
/* Pop away all LRE,RLE,LRO, RLO levels
from the stack, as these are implicitly
terminated by the PDI */
while (stack_size && !status_stack[stack_size-1].isolate)
POP_STATUS;
over_pushed = 0; /* The PDI resets the overpushed! */
POP_STATUS;
isolate_level-- ;
valid_isolate_count--;
RL_LEVEL (pp) = level;
RL_ISOLATE_LEVEL (pp) = isolate_level;
}
else
{
/* Ignore isolated PDI's by turning them into ON's */
RL_TYPE (pp) = FRIBIDI_TYPE_ON;
RL_LEVEL (pp) = level;
}
}
}
else if (FRIBIDI_IS_ISOLATE(this_type))
{
/* TBD support RL_LEN > 1 */
new_override = FRIBIDI_TYPE_ON;
isolate = 1;
if (this_type == FRIBIDI_TYPE_LRI)
new_level = level + 2 - (level%2);
else if (this_type == FRIBIDI_TYPE_RLI)
new_level = level + 1 + (level%2);
else if (this_type == FRIBIDI_TYPE_FSI)
{
/* Search for a local strong character until we
meet the corresponding PDI or the end of the
paragraph */
FriBidiRun *fsi_pp;
int isolate_count = 0;
int fsi_base_level = 0;
for_run_list (fsi_pp, pp)
{
if (RL_TYPE(fsi_pp) == FRIBIDI_TYPE_PDI)
{
isolate_count--;
if (valid_isolate_count < 0)
break;
}
else if (FRIBIDI_IS_ISOLATE(RL_TYPE(fsi_pp)))
isolate_count++;
else if (isolate_count==0 && FRIBIDI_IS_LETTER (RL_TYPE (fsi_pp)))
{
fsi_base_level = FRIBIDI_DIR_TO_LEVEL (RL_TYPE (fsi_pp));
break;
}
}
/* Same behavior like RLI and LRI above */
if (FRIBIDI_LEVEL_IS_RTL (fsi_base_level))
new_level = level + 1 + (level%2);
else
new_level = level + 2 - (level%2);
}
RL_LEVEL (pp) = level;
RL_ISOLATE_LEVEL (pp) = isolate_level++;
base_level_per_iso_level[isolate_level] = new_level;
if (!FRIBIDI_IS_NEUTRAL (override))
RL_TYPE (pp) = override;
if (new_level <= FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL)
{
valid_isolate_count++;
PUSH_STATUS;
level = new_level;
}
else
isolate_overflow += 1;
}
else if (this_type == FRIBIDI_TYPE_BS)
{
/* X8. All explicit directional embeddings and overrides are
completely terminated at the end of each paragraph. Paragraph
separators are not included in the embedding. */
break;
}
else
{
/* X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
a. Set the level of the current character to the current
embedding level.
b. Whenever the directional override status is not neutral,
reset the current character type to the directional override
status. */
RL_LEVEL (pp) = level;
if (!FRIBIDI_IS_NEUTRAL (override))
RL_TYPE (pp) = override;
}
}
/* Build the isolate_level connections */
for_run_list (pp, main_run_list)
{
int isolate_level = RL_ISOLATE_LEVEL (pp);
if (run_per_isolate_level[isolate_level])
{
run_per_isolate_level[isolate_level]->next_isolate = pp;
pp->prev_isolate = run_per_isolate_level[isolate_level];
}
run_per_isolate_level[isolate_level] = pp;
}
/* Implementing X8. It has no effect on a single paragraph! */
level = base_level;
override = FRIBIDI_TYPE_ON;
stack_size = 0;
over_pushed = 0;
fribidi_free (status_stack);
fribidi_free (run_per_isolate_level);
}
/* X10. The remaining rules are applied to each run of characters at the
same level. For each run, determine the start-of-level-run (sor) and
end-of-level-run (eor) type, either L or R. This depends on the
higher of the two levels on either side of the boundary (at the start
or end of the paragraph, the level of the 'other' run is the base
embedding level). If the higher level is odd, the type is R, otherwise
it is L. */
/* Resolving Implicit Levels can be done out of X10 loop, so only change
of Resolving Weak Types and Resolving Neutral Types is needed. */
compact_list (main_run_list);
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_types_re (main_run_list);
print_bidi_string (bidi_types, len);
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
/* 4. Resolving weak types. Also calculate the maximum isolate level */
max_iso_level = 0;
DBG ("resolving weak types");
{
int *last_strong_stack;
FriBidiCharType prev_type_orig;
fribidi_boolean w4;
last_strong_stack = fribidi_malloc (sizeof (int)
* FRIBIDI_BIDI_MAX_RESOLVED_LEVELS);
last_strong_stack[0] = base_dir;
for_run_list (pp, main_run_list)
{
register FriBidiCharType prev_type, this_type, next_type;
FriBidiRun *ppp_prev, *ppp_next;
int iso_level;
ppp_prev = get_adjacent_run(pp, false, false);
ppp_next = get_adjacent_run(pp, true, false);
this_type = RL_TYPE (pp);
iso_level = RL_ISOLATE_LEVEL(pp);
if (iso_level > max_iso_level)
max_iso_level = iso_level;
if (RL_LEVEL(ppp_prev) == RL_LEVEL(pp))
prev_type = RL_TYPE(ppp_prev);
else
prev_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_prev), RL_LEVEL(pp)));
if (RL_LEVEL(ppp_next) == RL_LEVEL(pp))
next_type = RL_TYPE(ppp_next);
else
next_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_next), RL_LEVEL(pp)));
if (FRIBIDI_IS_STRONG (prev_type))
last_strong_stack[iso_level] = prev_type;
/* W1. NSM
Examine each non-spacing mark (NSM) in the level run, and change the
type of the NSM to the type of the previous character. If the NSM
is at the start of the level run, it will get the type of sor. */
/* Implementation note: it is important that if the previous character
is not sor, then we should merge this run with the previous,
because of rules like W5, that we assume all of a sequence of
adjacent ETs are in one FriBidiRun. */
if (this_type == FRIBIDI_TYPE_NSM)
{
/* New rule in Unicode 6.3 */
if (FRIBIDI_IS_ISOLATE (RL_TYPE (pp->prev)))
RL_TYPE(pp) = FRIBIDI_TYPE_ON;
if (RL_LEVEL (ppp_prev) == RL_LEVEL (pp))
{
if (ppp_prev == pp->prev)
pp = merge_with_prev (pp);
}
else
RL_TYPE (pp) = prev_type;
if (prev_type == next_type && RL_LEVEL (pp) == RL_LEVEL (pp->next))
{
if (ppp_next == pp->next)
pp = merge_with_prev (pp->next);
}
continue; /* As we know the next condition cannot be true. */
}
/* W2: European numbers. */
if (this_type == FRIBIDI_TYPE_EN && last_strong_stack[iso_level] == FRIBIDI_TYPE_AL)
{
RL_TYPE (pp) = FRIBIDI_TYPE_AN;
/* Resolving dependency of loops for rules W1 and W2, so we
can merge them in one loop. */
if (next_type == FRIBIDI_TYPE_NSM)
RL_TYPE (ppp_next) = FRIBIDI_TYPE_AN;
}
}
last_strong_stack[0] = base_dir;
/* Resolving dependency of loops for rules W4 and W5, W5 may
want to prevent W4 to take effect in the next turn, do this
through "w4". */
w4 = true;
/* Resolving dependency of loops for rules W4 and W5 with W7,
W7 may change an EN to L but it sets the prev_type_orig if needed,
so W4 and W5 in next turn can still do their works. */
prev_type_orig = FRIBIDI_TYPE_ON;
/* Each isolate level has its own memory of the last strong character */
for_run_list (pp, main_run_list)
{
register FriBidiCharType prev_type, this_type, next_type;
int iso_level;
FriBidiRun *ppp_prev, *ppp_next;
this_type = RL_TYPE (pp);
iso_level = RL_ISOLATE_LEVEL(pp);
ppp_prev = get_adjacent_run(pp, false, false);
ppp_next = get_adjacent_run(pp, true, false);
if (RL_LEVEL(ppp_prev) == RL_LEVEL(pp))
prev_type = RL_TYPE(ppp_prev);
else
prev_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_prev), RL_LEVEL(pp)));
if (RL_LEVEL(ppp_next) == RL_LEVEL(pp))
next_type = RL_TYPE(ppp_next);
else
next_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_next), RL_LEVEL(pp)));
if (FRIBIDI_IS_STRONG (prev_type))
last_strong_stack[iso_level] = prev_type;
/* W2 ??? */
/* W3: Change ALs to R. */
if (this_type == FRIBIDI_TYPE_AL)
{
RL_TYPE (pp) = FRIBIDI_TYPE_RTL;
w4 = true;
prev_type_orig = FRIBIDI_TYPE_ON;
continue;
}
/* W4. A single european separator changes to a european number.
A single common separator between two numbers of the same type
changes to that type. */
if (w4
&& RL_LEN (pp) == 1 && FRIBIDI_IS_ES_OR_CS (this_type)
&& FRIBIDI_IS_NUMBER (prev_type_orig)
&& prev_type_orig == next_type
&& (prev_type_orig == FRIBIDI_TYPE_EN
|| this_type == FRIBIDI_TYPE_CS))
{
RL_TYPE (pp) = prev_type;
this_type = RL_TYPE (pp);
}
w4 = true;
/* W5. A sequence of European terminators adjacent to European
numbers changes to All European numbers. */
if (this_type == FRIBIDI_TYPE_ET
&& (prev_type_orig == FRIBIDI_TYPE_EN
|| next_type == FRIBIDI_TYPE_EN))
{
RL_TYPE (pp) = FRIBIDI_TYPE_EN;
w4 = false;
this_type = RL_TYPE (pp);
}
/* W6. Otherwise change separators and terminators to other neutral. */
if (FRIBIDI_IS_NUMBER_SEPARATOR_OR_TERMINATOR (this_type))
RL_TYPE (pp) = FRIBIDI_TYPE_ON;
/* W7. Change european numbers to L. */
if (this_type == FRIBIDI_TYPE_EN && last_strong_stack[iso_level] == FRIBIDI_TYPE_LTR)
{
RL_TYPE (pp) = FRIBIDI_TYPE_LTR;
prev_type_orig = (RL_LEVEL (pp) == RL_LEVEL (pp->next) ?
FRIBIDI_TYPE_EN : FRIBIDI_TYPE_ON);
}
else
prev_type_orig = PREV_TYPE_OR_SOR (pp->next);
}
fribidi_free (last_strong_stack);
}
compact_neutrals (main_run_list);
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
/* 5. Resolving Neutral Types */
DBG ("resolving neutral types - N0");
{
/* BD16 - Build list of all pairs*/
int num_iso_levels = max_iso_level + 1;
FriBidiPairingNode *pairing_nodes = NULL;
FriBidiRun ***bracket_stack = fribidi_malloc(sizeof(bracket_stack[0])
* num_iso_levels);
int *bracket_stack_size = fribidi_malloc(sizeof(bracket_stack_size[0])
* num_iso_levels);
int last_level = RL_LEVEL(main_run_list);
int last_iso_level = 0;
memset(bracket_stack, 0, sizeof(bracket_stack[0])*num_iso_levels);
memset(bracket_stack_size, 0, sizeof(bracket_stack_size[0])*num_iso_levels);
/* Build the bd16 pair stack. */
for_run_list (pp, main_run_list)
{
int level = RL_LEVEL(pp);
int iso_level = RL_ISOLATE_LEVEL(pp);
FriBidiBracketType brack_prop = RL_BRACKET_TYPE(pp);
/* Interpret the isolating run sequence as such that they
end at a change in the level, unless the iso_level has been
raised. */
if (level != last_level && last_iso_level == iso_level)
bracket_stack_size[last_iso_level] = 0;
if (!bracket_stack[iso_level])
bracket_stack[iso_level] = fribidi_malloc (sizeof (bracket_stack[0])
* FRIBIDI_BIDI_MAX_NESTED_BRACKET_PAIRS);
if (brack_prop!= FRIBIDI_NO_BRACKET)
{
if (FRIBIDI_IS_BRACKET_OPEN(brack_prop))
{
if (bracket_stack_size[iso_level]==FRIBIDI_BIDI_MAX_NESTED_BRACKET_PAIRS)
break;
/* push onto the pair stack */
bracket_stack[iso_level][bracket_stack_size[iso_level]++] = pp;
}
else
{
int stack_idx = bracket_stack_size[iso_level] - 1;
while (stack_idx >= 0)
{
FriBidiBracketType se_brack_prop = RL_BRACKET_TYPE(bracket_stack[iso_level][stack_idx]);
if (FRIBIDI_BRACKET_ID(se_brack_prop) == FRIBIDI_BRACKET_ID(brack_prop))
{
bracket_stack_size[iso_level] = stack_idx;
pairing_nodes = pairing_nodes_push(pairing_nodes,
bracket_stack[iso_level][stack_idx],
pp);
break;
}
stack_idx--;
}
}
}
last_level = level;
last_iso_level = iso_level;
}
/* The list must now be sorted for the next algo to work! */
sort_pairing_nodes(&pairing_nodes);
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_pairing_nodes (pairing_nodes);
}
# endif /* DEBUG */
/* Start the N0 */
{
FriBidiPairingNode *ppairs = pairing_nodes;
while (ppairs)
{
int iso_level = ppairs->open->isolate_level;
int embedding_level = base_level_per_iso_level[iso_level];
/* Find matching strong. */
fribidi_boolean found = false;
FriBidiRun *ppn;
for (ppn = ppairs->open; ppn!= ppairs->close; ppn = ppn->next)
{
FriBidiCharType this_type = RL_TYPE_AN_EN_AS_RTL(ppn);
/* Calculate level like in resolve implicit levels below to prevent
embedded levels not to match the base_level */
int this_level = RL_LEVEL (ppn) +
(FRIBIDI_LEVEL_IS_RTL (RL_LEVEL(ppn)) ^ FRIBIDI_DIR_TO_LEVEL (this_type));
/* N0b */
if (FRIBIDI_IS_STRONG (this_type) && this_level == embedding_level)
{
RL_TYPE(ppairs->open) = RL_TYPE(ppairs->close) = this_level%2 ? FRIBIDI_TYPE_RTL : FRIBIDI_TYPE_LTR;
found = true;
break;
}
}
/* N0c */
/* Search for any strong type preceding and within the bracket pair */
if (!found)
{
/* Search for a preceding strong */
int prec_strong_level = embedding_level; /* TBDov! Extract from Isolate level in effect */
int iso_level = RL_ISOLATE_LEVEL(ppairs->open);
for (ppn = ppairs->open->prev; ppn->type != FRIBIDI_TYPE_SENTINEL; ppn=ppn->prev)
{
FriBidiCharType this_type = RL_TYPE_AN_EN_AS_RTL(ppn);
if (FRIBIDI_IS_STRONG (this_type) && RL_ISOLATE_LEVEL(ppn) == iso_level)
{
prec_strong_level = RL_LEVEL (ppn) +
(FRIBIDI_LEVEL_IS_RTL (RL_LEVEL(ppn)) ^ FRIBIDI_DIR_TO_LEVEL (this_type));
break;
}
}
for (ppn = ppairs->open; ppn!= ppairs->close; ppn = ppn->next)
{
FriBidiCharType this_type = RL_TYPE_AN_EN_AS_RTL(ppn);
if (FRIBIDI_IS_STRONG (this_type) && RL_ISOLATE_LEVEL(ppn) == iso_level)
{
/* By constraint this is opposite the embedding direction,
since we did not match the N0b rule. We must now
compare with the preceding strong to establish whether
to apply N0c1 (opposite) or N0c2 embedding */
RL_TYPE(ppairs->open) = RL_TYPE(ppairs->close) = prec_strong_level % 2 ? FRIBIDI_TYPE_RTL : FRIBIDI_TYPE_LTR;
RL_LEVEL(ppairs->open) = RL_LEVEL(ppairs->close) = prec_strong_level;
found = true;
break;
}
}
}
ppairs = ppairs->next;
}
free_pairing_nodes(pairing_nodes);
{
int i;
for (i=0; i<num_iso_levels; i++)
fribidi_free(bracket_stack[i]);
}
fribidi_free(bracket_stack);
fribidi_free(bracket_stack_size);
/* Remove the bracket property and re-compact */
{
const FriBidiBracketType NoBracket = FRIBIDI_NO_BRACKET;
for_run_list (pp, main_run_list)
pp->bracket_type = NoBracket;
compact_list (main_run_list);
}
}
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
}
DBG ("resolving neutral types - N1+N2");
{
for_run_list (pp, main_run_list)
{
FriBidiCharType prev_type, this_type, next_type;
FriBidiRun *ppp_prev, *ppp_next;
ppp_prev = get_adjacent_run(pp, false, false);
ppp_next = get_adjacent_run(pp, true, false);
/* "European and Arabic numbers are treated as though they were R"
FRIBIDI_CHANGE_NUMBER_TO_RTL does this. */
this_type = FRIBIDI_CHANGE_NUMBER_TO_RTL (RL_TYPE (pp));
if (RL_LEVEL(ppp_prev) == RL_LEVEL(pp))
prev_type = FRIBIDI_CHANGE_NUMBER_TO_RTL (RL_TYPE(ppp_prev));
else
prev_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_prev), RL_LEVEL(pp)));
if (RL_LEVEL(ppp_next) == RL_LEVEL(pp))
next_type = FRIBIDI_CHANGE_NUMBER_TO_RTL (RL_TYPE(ppp_next));
else
next_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_next), RL_LEVEL(pp)));
if (FRIBIDI_IS_NEUTRAL (this_type))
RL_TYPE (pp) = (prev_type == next_type) ?
/* N1. */ prev_type :
/* N2. */ FRIBIDI_EMBEDDING_DIRECTION (pp);
}
}
compact_list (main_run_list);
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
/* 6. Resolving implicit levels */
DBG ("resolving implicit levels");
{
max_level = base_level;
for_run_list (pp, main_run_list)
{
FriBidiCharType this_type;
int level;
this_type = RL_TYPE (pp);
level = RL_LEVEL (pp);
/* I1. Even */
/* I2. Odd */
if (FRIBIDI_IS_NUMBER (this_type))
RL_LEVEL (pp) = (level + 2) & ~1;
else
RL_LEVEL (pp) =
level +
(FRIBIDI_LEVEL_IS_RTL (level) ^ FRIBIDI_DIR_TO_LEVEL (this_type));
if (RL_LEVEL (pp) > max_level)
max_level = RL_LEVEL (pp);
}
}
compact_list (main_run_list);
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_bidi_string (bidi_types, len);
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
/* Reinsert the explicit codes & BN's that are already removed, from the
explicits_list to main_run_list. */
DBG ("reinserting explicit codes");
if UNLIKELY
(explicits_list->next != explicits_list)
{
register FriBidiRun *p;
register fribidi_boolean stat =
shadow_run_list (main_run_list, explicits_list, true);
explicits_list = NULL;
if UNLIKELY
(!stat) goto out;
/* Set level of inserted explicit chars to that of their previous
* char, such that they do not affect reordering. */
p = main_run_list->next;
if (p != main_run_list && p->level == FRIBIDI_SENTINEL)
p->level = base_level;
for_run_list (p, main_run_list) if (p->level == FRIBIDI_SENTINEL)
p->level = p->prev->level;
}
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_types_re (main_run_list);
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
DBG ("reset the embedding levels, 1, 2, 3.");
{
register int j, state, pos;
register FriBidiCharType char_type;
register FriBidiRun *p, *q, *list;
/* L1. Reset the embedding levels of some chars:
1. segment separators,
2. paragraph separators,
3. any sequence of whitespace characters preceding a segment
separator or paragraph separator, and
4. any sequence of whitespace characters and/or isolate formatting
characters at the end of the line.
... (to be continued in fribidi_reorder_line()). */
list = new_run_list ();
if UNLIKELY
(!list) goto out;
q = list;
state = 1;
pos = len - 1;
for (j = len - 1; j >= -1; j--)
{
/* close up the open link at the end */
if (j >= 0)
char_type = bidi_types[j];
else
char_type = FRIBIDI_TYPE_ON;
if (!state && FRIBIDI_IS_SEPARATOR (char_type))
{
state = 1;
pos = j;
}
else if (state &&
!(FRIBIDI_IS_EXPLICIT_OR_SEPARATOR_OR_BN_OR_WS(char_type)
|| FRIBIDI_IS_ISOLATE(char_type)))
{
state = 0;
p = new_run ();
if UNLIKELY
(!p)
{
free_run_list (list);
goto out;
}
p->pos = j + 1;
p->len = pos - j;
p->type = base_dir;
p->level = base_level;
move_node_before (p, q);
q = p;
}
}
if UNLIKELY
(!shadow_run_list (main_run_list, list, false)) goto out;
}
# if DEBUG
if UNLIKELY
(fribidi_debug_status ())
{
print_types_re (main_run_list);
print_resolved_levels (main_run_list);
print_resolved_types (main_run_list);
}
# endif /* DEBUG */
{
FriBidiStrIndex pos = 0;
for_run_list (pp, main_run_list)
{
register FriBidiStrIndex l;
register FriBidiLevel level = pp->level;
for (l = pp->len; l; l--)
embedding_levels[pos++] = level;
}
}
status = true;
out:
DBG ("leaving fribidi_get_par_embedding_levels");
if (main_run_list)
free_run_list (main_run_list);
if UNLIKELY
(explicits_list) free_run_list (explicits_list);
if (base_level_per_iso_level)
fribidi_free (base_level_per_iso_level);
return status ? max_level + 1 : 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'Reduce dynamic allocations by using arrays for all small arrays.'</s> |
<s>[INST] Given the following code containing errors, provide 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 check_file_actlst(int *ifd, char *dfile, struct activity *act[], unsigned int flags,
struct file_magic *file_magic, struct file_header *file_hdr,
struct file_activity **file_actlst, unsigned int id_seq[],
int ignore, int *endian_mismatch, int *arch_64)
{
int i, j, k, p;
struct file_activity *fal;
void *buffer = NULL;
/* Open sa data file and read its magic structure */
if (sa_open_read_magic(ifd, dfile, file_magic, ignore, endian_mismatch, TRUE) < 0)
/*
* Not current sysstat's format.
* Return now so that sadf -H can display at least
* file's version and magic number.
*/
return;
/*
* We know now that we have a *compatible* sysstat datafile format
* (correct FORMAT_MAGIC value), and in this case, we should have
* checked header_size value. Anyway, with a corrupted datafile,
* this may not be the case. So check again.
*/
if ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) ||
(file_magic->header_size > MAX_FILE_HEADER_SIZE)) {
#ifdef DEBUG
fprintf(stderr, "%s: header_size=%u\n",
__FUNCTION__, file_magic->header_size);
#endif
goto format_error;
}
/* Allocate buffer for file_header structure */
SREALLOC(buffer, char, file_magic->header_size);
/* Read sa data file standard header and allocate activity list */
sa_fread(*ifd, buffer, (size_t) file_magic->header_size, HARD_SIZE, UEOF_STOP);
/*
* Data file header size (file_magic->header_size) may be greater or
* smaller than FILE_HEADER_SIZE. Remap the fields of the file header
* then copy its contents to the expected structure.
*/
remap_struct(hdr_types_nr, file_magic->hdr_types_nr, buffer,
file_magic->header_size, FILE_HEADER_SIZE, file_magic->header_size);
memcpy(file_hdr, buffer, FILE_HEADER_SIZE);
free(buffer);
buffer = NULL;
/* Tell that data come from a 64 bit machine */
*arch_64 = (file_hdr->sa_sizeof_long == SIZEOF_LONG_64BIT);
/* Normalize endianness for file_hdr structure */
if (*endian_mismatch) {
swap_struct(hdr_types_nr, file_hdr, *arch_64);
}
/*
* Sanity checks.
* NB: Compare against MAX_NR_ACT and not NR_ACT because
* we are maybe reading a datafile from a future sysstat version
* with more activities than known today.
*/
if ((file_hdr->sa_act_nr > MAX_NR_ACT) ||
(file_hdr->act_size > MAX_FILE_ACTIVITY_SIZE) ||
(file_hdr->rec_size > MAX_RECORD_HEADER_SIZE) ||
(MAP_SIZE(file_hdr->act_types_nr) > file_hdr->act_size) ||
(MAP_SIZE(file_hdr->rec_types_nr) > file_hdr->rec_size)) {
#ifdef DEBUG
fprintf(stderr, "%s: sa_act_nr=%d act_size=%u rec_size=%u map_size(act)=%u map_size(rec)=%u\n",
__FUNCTION__, file_hdr->sa_act_nr, file_hdr->act_size, file_hdr->rec_size,
MAP_SIZE(file_hdr->act_types_nr), MAP_SIZE(file_hdr->rec_types_nr));
#endif
/* Maybe a "false positive" sysstat datafile? */
goto format_error;
}
SREALLOC(buffer, char, file_hdr->act_size);
SREALLOC(*file_actlst, struct file_activity, FILE_ACTIVITY_SIZE * file_hdr->sa_act_nr);
fal = *file_actlst;
/* Read activity list */
j = 0;
for (i = 0; i < file_hdr->sa_act_nr; i++, fal++) {
/* Read current file_activity structure from file */
sa_fread(*ifd, buffer, (size_t) file_hdr->act_size, HARD_SIZE, UEOF_STOP);
/*
* Data file_activity size (file_hdr->act_size) may be greater or
* smaller than FILE_ACTIVITY_SIZE. Remap the fields of the file's structure
* then copy its contents to the expected structure.
*/
if (remap_struct(act_types_nr, file_hdr->act_types_nr, buffer,
file_hdr->act_size, FILE_ACTIVITY_SIZE, file_hdr->act_size) < 0)
goto format_error;
memcpy(fal, buffer, FILE_ACTIVITY_SIZE);
/* Normalize endianness for file_activity structures */
if (*endian_mismatch) {
swap_struct(act_types_nr, fal, *arch_64);
}
/*
* Every activity, known or unknown, should have
* at least one item and sub-item, and a positive size value.
* Also check that the number of items and sub-items
* doesn't exceed a max value. This is necessary
* because we will use @nr and @nr2 to
* allocate memory to read the file contents. So we
* must make sure the file is not corrupted.
* NB: Another check will be made below for known
* activities which have each a specific max value.
*/
if ((fal->nr < 1) || (fal->nr2 < 1) ||
(fal->nr > NR_MAX) || (fal->nr2 > NR2_MAX) ||
(fal->size <= 0)) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d nr=%d nr2=%d\n",
__FUNCTION__, fal->id, fal->nr, fal->nr2);
#endif
goto format_error;
}
if ((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0)
/* Unknown activity */
continue;
if (act[p]->magic != fal->magic) {
/* Bad magical number */
if (ignore) {
/*
* This is how sadf -H knows that this
* activity has an unknown format.
*/
act[p]->magic = ACTIVITY_MAGIC_UNKNOWN;
}
else
continue;
}
/* Check max value for known activities */
if (fal->nr > act[p]->nr_max) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d nr=%d nr_max=%d\n",
__FUNCTION__, fal->id, fal->nr, act[p]->nr_max);
#endif
goto format_error;
}
/*
* Number of fields of each type ("long long", or "long"
* or "int") composing the structure with statistics may
* only increase with new sysstat versions. Here, we may
* be reading a file created by current sysstat version,
* or by an older or a newer version.
*/
if (!(((fal->types_nr[0] >= act[p]->gtypes_nr[0]) &&
(fal->types_nr[1] >= act[p]->gtypes_nr[1]) &&
(fal->types_nr[2] >= act[p]->gtypes_nr[2]))
||
((fal->types_nr[0] <= act[p]->gtypes_nr[0]) &&
(fal->types_nr[1] <= act[p]->gtypes_nr[1]) &&
(fal->types_nr[2] <= act[p]->gtypes_nr[2]))) && !ignore) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d file=%d,%d,%d activity=%d,%d,%d\n",
__FUNCTION__, fal->id, fal->types_nr[0], fal->types_nr[1], fal->types_nr[2],
act[p]->gtypes_nr[0], act[p]->gtypes_nr[1], act[p]->gtypes_nr[2]);
#endif
goto format_error;
}
if (MAP_SIZE(fal->types_nr) > fal->size) {
#ifdef DEBUG
fprintf(stderr, "%s: id=%d size=%u map_size=%u\n",
__FUNCTION__, fal->id, fal->size, MAP_SIZE(fal->types_nr));
#endif
goto format_error;
}
for (k = 0; k < 3; k++) {
act[p]->ftypes_nr[k] = fal->types_nr[k];
}
if (fal->size > act[p]->msize) {
act[p]->msize = fal->size;
}
act[p]->nr_ini = fal->nr;
act[p]->nr2 = fal->nr2;
act[p]->fsize = fal->size;
/*
* This is a known activity with a known format
* (magical number). Only such activities will be displayed.
* (Well, this may also be an unknown format if we have entered sadf -H.)
*/
id_seq[j++] = fal->id;
}
while (j < NR_ACT) {
id_seq[j++] = 0;
}
free(buffer);
/* Check that at least one activity selected by the user is available in file */
for (i = 0; i < NR_ACT; i++) {
if (!IS_SELECTED(act[i]->options))
continue;
/* Here is a selected activity: Does it exist in file? */
fal = *file_actlst;
for (j = 0; j < file_hdr->sa_act_nr; j++, fal++) {
if (act[i]->id == fal->id)
break;
}
if (j == file_hdr->sa_act_nr) {
/* No: Unselect it */
act[i]->options &= ~AO_SELECTED;
}
}
/*
* None of selected activities exist in file: Abort.
* NB: Error is ignored if we only want to display
* datafile header (sadf -H).
*/
if (!get_activity_nr(act, AO_SELECTED, COUNT_ACTIVITIES) && !DISPLAY_HDR_ONLY(flags)) {
fprintf(stderr, _("Requested activities not available in file %s\n"),
dfile);
close(*ifd);
exit(1);
}
return;
format_error:
if (buffer) {
free(buffer);
}
handle_invalid_sa_file(*ifd, file_magic, dfile, 0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Fix #230: Memory corruption bug due to Integer Overflow in remap_struct()
(See problem description in issue #230.)
Check that the number of fields (long long integers, long integers or
integers) as read from a system activity binary datafile multiplied by
its alignment width doesn't overflow, i.e. the result must not be
smaller than the number of fields.
Reported-by: Ren Kimura
Signed-off-by: Sebastien GODARD <[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: parse_exp(Node** np, PToken* tok, int term, UChar** src, UChar* end,
ScanEnv* env, int group_head)
{
int r, len, group = 0;
Node* qn;
Node** tp;
*np = NULL;
if (tok->type == (enum TokenSyms )term)
goto end_of_token;
switch (tok->type) {
case TK_ALT:
case TK_EOT:
end_of_token:
*np = node_new_empty();
CHECK_NULL_RETURN_MEMERR(*np);
return tok->type;
break;
case TK_SUBEXP_OPEN:
r = parse_bag(np, tok, TK_SUBEXP_CLOSE, src, end, env);
if (r < 0) return r;
if (r == 1) { /* group */
if (group_head == 0)
group = 1;
else {
Node* target = *np;
*np = node_new_group(target);
if (IS_NULL(*np)) {
onig_node_free(target);
return ONIGERR_MEMORY;
}
group = 2;
}
}
else if (r == 2) { /* option only */
Node* target;
OnigOptionType prev = env->options;
env->options = BAG_(*np)->o.options;
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, src, end, env, 0);
env->options = prev;
if (r < 0) {
onig_node_free(target);
return r;
}
NODE_BODY(*np) = target;
return tok->type;
}
break;
case TK_SUBEXP_CLOSE:
if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP))
return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS;
if (tok->escaped) goto tk_raw_byte;
else goto tk_byte;
break;
case TK_STRING:
tk_byte:
{
*np = node_new_str(tok->backp, *src);
CHECK_NULL_RETURN_MEMERR(*np);
while (1) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_STRING) break;
r = onig_node_str_cat(*np, tok->backp, *src);
if (r < 0) return r;
}
string_end:
tp = np;
goto repeat;
}
break;
case TK_RAW_BYTE:
tk_raw_byte:
{
*np = node_new_str_raw_char((UChar )tok->u.c);
CHECK_NULL_RETURN_MEMERR(*np);
len = 1;
while (1) {
if (len >= ONIGENC_MBC_MINLEN(env->enc)) {
if (len == enclen(env->enc, STR_(*np)->s)) {
r = fetch_token(tok, src, end, env);
goto tk_raw_byte_end;
}
}
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_RAW_BYTE)
return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
r = node_str_cat_char(*np, (UChar )tok->u.c);
if (r < 0) return r;
len++;
}
tk_raw_byte_end:
if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, STR_(*np)->s, STR_(*np)->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
NODE_STRING_CLEAR_RAW(*np);
goto string_end;
}
break;
case TK_CODE_POINT:
{
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
len = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf);
if (len < 0) return len;
#ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG
*np = node_new_str_raw(buf, buf + len);
#else
*np = node_new_str(buf, buf + len);
#endif
CHECK_NULL_RETURN_MEMERR(*np);
}
break;
case TK_QUOTE_OPEN:
{
OnigCodePoint end_op[2];
UChar *qstart, *qend, *nextp;
end_op[0] = (OnigCodePoint )MC_ESC(env->syntax);
end_op[1] = (OnigCodePoint )'E';
qstart = *src;
qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc);
if (IS_NULL(qend)) {
nextp = qend = end;
}
*np = node_new_str(qstart, qend);
CHECK_NULL_RETURN_MEMERR(*np);
*src = nextp;
}
break;
case TK_CHAR_TYPE:
{
switch (tok->u.prop.ctype) {
case ONIGENC_CTYPE_WORD:
*np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not, env->options);
CHECK_NULL_RETURN_MEMERR(*np);
break;
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_XDIGIT:
{
CClassNode* cc;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = CCLASS_(*np);
add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env);
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
}
break;
case TK_CHAR_PROPERTY:
r = parse_char_property(np, tok, src, end, env);
if (r != 0) return r;
break;
case TK_CC_OPEN:
{
CClassNode* cc;
r = parse_char_class(np, tok, src, end, env);
if (r != 0) return r;
cc = CCLASS_(*np);
if (IS_IGNORECASE(env->options)) {
IApplyCaseFoldArg iarg;
iarg.env = env;
iarg.cc = cc;
iarg.alt_root = NULL_NODE;
iarg.ptail = &(iarg.alt_root);
r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag,
i_apply_case_fold, &iarg);
if (r != 0) {
onig_node_free(iarg.alt_root);
return r;
}
if (IS_NOT_NULL(iarg.alt_root)) {
Node* work = onig_node_new_alt(*np, iarg.alt_root);
if (IS_NULL(work)) {
onig_node_free(iarg.alt_root);
return ONIGERR_MEMORY;
}
*np = work;
}
}
}
break;
case TK_ANYCHAR:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
break;
case TK_ANYCHAR_ANYTIME:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
qn = node_new_quantifier(0, INFINITE_REPEAT, 0);
CHECK_NULL_RETURN_MEMERR(qn);
NODE_BODY(qn) = *np;
*np = qn;
break;
case TK_BACKREF:
len = tok->u.backref.num;
*np = node_new_backref(len,
(len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)),
tok->u.backref.by_name,
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level,
tok->u.backref.level,
#endif
env);
CHECK_NULL_RETURN_MEMERR(*np);
break;
#ifdef USE_CALL
case TK_CALL:
{
int gnum = tok->u.call.gnum;
*np = node_new_call(tok->u.call.name, tok->u.call.name_end,
gnum, tok->u.call.by_number);
CHECK_NULL_RETURN_MEMERR(*np);
env->num_call++;
if (tok->u.call.by_number != 0 && gnum == 0) {
env->has_call_zero = 1;
}
}
break;
#endif
case TK_ANCHOR:
{
int ascii_mode =
IS_WORD_ASCII(env->options) && IS_WORD_ANCHOR_TYPE(tok->u.anchor) ? 1 : 0;
*np = onig_node_new_anchor(tok->u.anchor, ascii_mode);
CHECK_NULL_RETURN_MEMERR(*np);
}
break;
case TK_REPEAT:
case TK_INTERVAL:
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED;
else {
*np = node_new_empty();
CHECK_NULL_RETURN_MEMERR(*np);
}
}
else {
goto tk_byte;
}
break;
case TK_KEEP:
r = node_new_keep(np, env);
if (r < 0) return r;
break;
case TK_GENERAL_NEWLINE:
r = node_new_general_newline(np, env);
if (r < 0) return r;
break;
case TK_NO_NEWLINE:
r = node_new_no_newline(np, env);
if (r < 0) return r;
break;
case TK_TRUE_ANYCHAR:
r = node_new_true_anychar(np, env);
if (r < 0) return r;
break;
case TK_TEXT_SEGMENT:
r = make_text_segment(np, env);
if (r < 0) return r;
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
{
tp = np;
re_entry:
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
repeat:
if (r == TK_REPEAT || r == TK_INTERVAL) {
Node* target;
if (is_invalid_quantifier_target(*tp))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID;
qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper,
r == TK_INTERVAL);
CHECK_NULL_RETURN_MEMERR(qn);
QUANT_(qn)->greedy = tok->u.repeat.greedy;
if (group == 2) {
target = node_drop_group(*tp);
*tp = NULL_NODE;
}
else {
target = *tp;
}
r = set_quantifier(qn, target, group, env);
if (r < 0) {
onig_node_free(qn);
return r;
}
if (tok->u.repeat.possessive != 0) {
Node* en;
en = node_new_bag(BAG_STOP_BACKTRACK);
if (IS_NULL(en)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
NODE_BODY(en) = qn;
qn = en;
}
if (r == 0) {
*tp = qn;
}
else if (r == 1) { /* x{1,1} ==> x */
onig_node_free(qn);
*tp = target;
}
else if (r == 2) { /* split case: /abc+/ */
Node *tmp;
*tp = node_new_list(*tp, NULL);
if (IS_NULL(*tp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
tmp = NODE_CDR(*tp) = node_new_list(qn, NULL);
if (IS_NULL(tmp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
tp = &(NODE_CAR(tmp));
}
group = 0;
goto re_entry;
}
}
return r;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-399', 'CWE-674'], 'message': 'fix #147: Stack Exhaustion Problem caused by some parsing functions in regcomp.c making recursive calls to themselves.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int r, num;
OnigCodePoint c;
OnigEncoding enc = env->enc;
const OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
start:
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
tok->type = TK_STRING;
tok->base = 0;
tok->backp = p;
PFETCH(c);
if (IS_MC_ESC_CODE(c, syn)) {
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
tok->backp = p;
PFETCH(c);
tok->u.c = c;
tok->escaped = 1;
switch (c) {
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
greedy_check:
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {
PFETCH(c);
tok->u.repeat.greedy = 0;
tok->u.repeat.possessive = 0;
}
else {
possessive_check:
if (!PEND && PPEEK_IS('+') &&
((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&
tok->type != TK_INTERVAL) ||
(IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&
tok->type == TK_INTERVAL))) {
PFETCH(c);
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 1;
}
else {
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 0;
}
}
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case 'w':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'b':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_WORD_BOUND;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option)
&& ! IS_WORD_BOUND_ALL_RANGE(env->option);
break;
case 'B':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_NOT_WORD_BOUND;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option)
&& ! IS_WORD_BOUND_ALL_RANGE(env->option);
break;
#ifdef USE_WORD_BEGIN_END
case '<':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_WORD_BEGIN;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option);
break;
case '>':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_WORD_END;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option);
break;
#endif
case 's':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'd':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'A':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
begin_buf:
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_BEGIN_BUF;
break;
case 'Z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_SEMI_END_BUF;
break;
case 'z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
end_buf:
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_END_BUF;
break;
case 'G':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_BEGIN_POSITION;
break;
case '`':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto begin_buf;
break;
case '\'':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto end_buf;
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc);
if (num < -1) return ONIGERR_TOO_SHORT_DIGITS;
else if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case 'o':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) {
PINC;
num = scan_unsigned_octal_number(&p, end, 11, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
OnigCodePoint c = PPEEK;
if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8')
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
PUNFETCH;
prev = p;
num = onig_scan_unsigned_number(&p, end, enc);
if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {
goto skip_backref;
}
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&
(num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.num = 1;
tok->u.backref.ref1 = num;
tok->u.backref.by_name = 0;
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level = 0;
#endif
break;
}
skip_backref:
if (c == '8' || c == '9') {
/* normal char */
p = prev; PINC;
break;
}
p = prev;
/* fall through */
case '0':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
prev = p;
num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);
if (num < 0 || 0xff < num) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
else if (c != '0') {
PINC;
}
break;
#ifdef USE_NAMED_GROUP
case 'k':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {
PFETCH(c);
if (c == '<' || c == '\'') {
r = fetch_named_backref_token(c, tok, &p, end, env);
if (r < 0) return r;
}
else {
PUNFETCH;
onig_syntax_warn(env, "invalid back reference");
}
}
break;
#endif
#if defined(USE_SUBEXP_CALL) || defined(USE_NAMED_GROUP)
case 'g':
# ifdef USE_NAMED_GROUP
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_BRACE_BACKREF)) {
PFETCH(c);
if (c == '{') {
r = fetch_named_backref_token(c, tok, &p, end, env);
if (r < 0) return r;
}
else
PUNFETCH;
}
# endif
# ifdef USE_SUBEXP_CALL
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {
PFETCH(c);
if (c == '<' || c == '\'') {
int gnum = -1, rel = 0;
UChar* name_end;
OnigCodePoint cnext;
cnext = PPEEK;
if (cnext == '0') {
PINC;
if (PPEEK_IS(get_name_end_code_point(c))) { /* \g<0>, \g'0' */
PINC;
name_end = p;
gnum = 0;
}
}
else if (cnext == '+') {
PINC;
rel = 1;
}
prev = p;
if (gnum < 0) {
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
}
tok->type = TK_CALL;
tok->u.call.name = prev;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = rel;
}
else {
onig_syntax_warn(env, "invalid subexp call");
PUNFETCH;
}
}
# endif
break;
#endif
case 'Q':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {
tok->type = TK_QUOTE_OPEN;
}
break;
case 'p':
case 'P':
if (PPEEK_IS('{') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c);
if (c == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
else {
onig_syntax_warn(env, "invalid Unicode Property \\%c", c);
}
break;
case 'R':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_R_LINEBREAK)) {
tok->type = TK_LINEBREAK;
}
break;
case 'X':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_X_EXTENDED_GRAPHEME_CLUSTER)) {
tok->type = TK_EXTENDED_GRAPHEME_CLUSTER;
}
break;
case 'K':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP)) {
tok->type = TK_KEEP;
}
break;
default:
{
OnigCodePoint c2;
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
/* set_raw: */
if ((OnigCodePoint )tok->u.c != c2) {
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )c2;
}
else { /* string */
p = tok->backp + enclen(enc, tok->backp, end);
}
}
break;
}
}
else {
tok->u.c = c;
tok->escaped = 0;
#ifdef USE_VARIABLE_META_CHARS
if ((c != ONIG_INEFFECTIVE_META_CHAR) &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {
if (c == MC_ANYCHAR(syn))
goto any_char;
else if (c == MC_ANYTIME(syn))
goto anytime;
else if (c == MC_ZERO_OR_ONE_TIME(syn))
goto zero_or_one_time;
else if (c == MC_ONE_OR_MORE_TIME(syn))
goto one_or_more_time;
else if (c == MC_ANYCHAR_ANYTIME(syn)) {
tok->type = TK_ANYCHAR_ANYTIME;
goto out;
}
}
#endif
switch (c) {
case '.':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;
#ifdef USE_VARIABLE_META_CHARS
any_char:
#endif
tok->type = TK_ANYCHAR;
break;
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
anytime:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
one_or_more_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;
#ifdef USE_VARIABLE_META_CHARS
zero_or_one_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
goto greedy_check;
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (PPEEK_IS('?') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (PPEEK_IS('#')) {
PFETCH(c);
while (1) {
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
if (c == MC_ESC(syn)) {
if (!PEND) PFETCH(c);
}
else {
if (c == ')') break;
}
}
goto start;
}
#ifdef USE_PERL_SUBEXP_CALL
/* (?&name), (?n), (?R), (?0), (?+n), (?-n) */
c = PPEEK;
if ((c == '&' || c == 'R' || ONIGENC_IS_CODE_DIGIT(enc, c)) &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) {
/* (?&name), (?n), (?R), (?0) */
int gnum;
UChar *name;
UChar *name_end;
if (c == 'R' || c == '0') {
PINC; /* skip 'R' / '0' */
if (!PPEEK_IS(')')) return ONIGERR_INVALID_GROUP_NAME;
PINC; /* skip ')' */
name_end = name = p;
gnum = 0;
}
else {
int numref = 1;
if (c == '&') { /* (?&name) */
PINC;
numref = 0; /* don't allow number name */
}
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, numref);
if (r < 0) return r;
}
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = 0;
break;
}
else if ((c == '-' || c == '+') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) {
/* (?+n), (?-n) */
int gnum;
UChar *name;
UChar *name_end;
OnigCodePoint cnext;
PFETCH_READY;
PINC; /* skip '-' / '+' */
cnext = PPEEK;
if (ONIGENC_IS_CODE_DIGIT(enc, cnext)) {
if (c == '-') PUNFETCH;
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = 1;
break;
}
}
#endif /* USE_PERL_SUBEXP_CALL */
#ifdef USE_CAPITAL_P_NAMED_GROUP
if (PPEEK_IS('P') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_CAPITAL_P_NAMED_GROUP)) {
int gnum;
UChar *name;
UChar *name_end;
PFETCH_READY;
PINC; /* skip 'P' */
if (PEND) return ONIGERR_UNDEFINED_GROUP_OPTION;
PFETCH(c);
if (c == '=') { /* (?P=name): backref */
r = fetch_named_backref_token((OnigCodePoint )'(', tok, &p, end, env);
if (r < 0) return r;
break;
}
else if (c == '>') { /* (?P>name): subexp call */
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 0);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = 0;
break;
}
}
#endif /* USE_CAPITAL_P_NAMED_GROUP */
PUNFETCH;
}
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case '^':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);
break;
case '$':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);
break;
case '[':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;
tok->type = TK_CC_OPEN;
break;
case ']':
if (*src > env->pattern) /* /].../ is allowed. */
CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]");
break;
case '#':
if (IS_EXTEND(env->option)) {
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_NEWLINE(enc, c))
break;
}
goto start;
break;
}
break;
case ' ': case '\t': case '\n': case '\r': case '\f':
if (IS_EXTEND(env->option))
goto start;
break;
default:
/* string */
break;
}
}
#ifdef USE_VARIABLE_META_CHARS
out:
#endif
*src = p;
return tok->type;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix SEGV in onig_error_code_to_str() (Fix #132)
When onig_new(ONIG_SYNTAX_PERL) fails with ONIGERR_INVALID_GROUP_NAME,
onig_error_code_to_str() crashes.
onig_scan_env_set_error_string() should have been used when returning
ONIGERR_INVALID_GROUP_NAME.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int r, num;
OnigCodePoint c;
OnigEncoding enc = env->enc;
OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
start:
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
tok->type = TK_STRING;
tok->base = 0;
tok->backp = p;
PFETCH(c);
if (IS_MC_ESC_CODE(c, syn)) {
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
tok->backp = p;
PFETCH(c);
tok->u.c = c;
tok->escaped = 1;
switch (c) {
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
greedy_check:
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {
PFETCH(c);
tok->u.repeat.greedy = 0;
tok->u.repeat.possessive = 0;
}
else {
possessive_check:
if (!PEND && PPEEK_IS('+') &&
((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&
tok->type != TK_INTERVAL) ||
(IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&
tok->type == TK_INTERVAL))) {
PFETCH(c);
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 1;
}
else {
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 0;
}
}
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case 'w':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'b':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BOUNDARY;
break;
case 'B':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_NO_WORD_BOUNDARY;
break;
case 'y':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP2_ESC_X_Y_GRAPHEME_CLUSTER)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;
break;
case 'Y':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP2_ESC_X_Y_GRAPHEME_CLUSTER)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_NO_EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;
break;
#ifdef USE_WORD_BEGIN_END
case '<':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BEGIN;
break;
case '>':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_END;
break;
#endif
case 's':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'd':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'K':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP)) break;
tok->type = TK_KEEP;
break;
case 'R':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_R_GENERAL_NEWLINE)) break;
tok->type = TK_GENERAL_NEWLINE;
break;
case 'N':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_N_O_SUPER_DOT)) break;
tok->type = TK_NO_NEWLINE;
break;
case 'O':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_N_O_SUPER_DOT)) break;
tok->type = TK_TRUE_ANYCHAR;
break;
case 'X':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_X_Y_GRAPHEME_CLUSTER)) break;
tok->type = TK_EXTENDED_GRAPHEME_CLUSTER;
break;
case 'A':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
begin_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_BUF;
break;
case 'Z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_SEMI_END_BUF;
break;
case 'z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
end_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_END_BUF;
break;
case 'G':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_POSITION;
break;
case '`':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto begin_buf;
break;
case '\'':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto end_buf;
break;
case 'o':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) {
PINC;
num = scan_unsigned_octal_number(&p, end, 11, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
if (IS_CODE_DIGIT_ASCII(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc);
if (num < 0) {
if (num == ONIGERR_TOO_BIG_NUMBER)
return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
else
return num;
}
if (!PEND) {
if (IS_CODE_XDIGIT_ASCII(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc);
if (num < 0) return num;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc);
if (num < 0) return num;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
PUNFETCH;
prev = p;
num = onig_scan_unsigned_number(&p, end, enc);
if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {
goto skip_backref;
}
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&
(num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem || IS_NULL(SCANENV_MEMENV(env)[num].node))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.num = 1;
tok->u.backref.ref1 = num;
tok->u.backref.by_name = 0;
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level = 0;
#endif
break;
}
skip_backref:
if (c == '8' || c == '9') {
/* normal char */
p = prev; PINC;
break;
}
p = prev;
/* fall through */
case '0':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
prev = p;
num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);
if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
else if (c != '0') {
PINC;
}
break;
case 'k':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {
PFETCH(c);
if (c == '<' || c == '\'') {
UChar* name_end;
int* backs;
int back_num;
enum REF_NUM num_type;
prev = p;
#ifdef USE_BACKREF_WITH_LEVEL
name_end = NULL_UCHARP; /* no need. escape gcc warning. */
r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end,
env, &back_num, &tok->u.backref.level, &num_type);
if (r == 1) tok->u.backref.exist_level = 1;
else tok->u.backref.exist_level = 0;
#else
r = fetch_name(c, &p, end, &name_end, env, &back_num, &num_type, 1);
#endif
if (r < 0) return r;
if (num_type != IS_NOT_NUM) {
if (num_type == IS_REL_NUM) {
back_num = backref_rel_to_abs(back_num, env);
}
if (back_num <= 0)
return ONIGERR_INVALID_BACKREF;
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (back_num > env->num_mem ||
IS_NULL(SCANENV_MEMENV(env)[back_num].node))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 0;
tok->u.backref.num = 1;
tok->u.backref.ref1 = back_num;
}
else {
num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs);
if (num <= 0) {
onig_scan_env_set_error_string(env,
ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
int i;
for (i = 0; i < num; i++) {
if (backs[i] > env->num_mem ||
IS_NULL(SCANENV_MEMENV(env)[backs[i]].node))
return ONIGERR_INVALID_BACKREF;
}
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 1;
if (num == 1) {
tok->u.backref.num = 1;
tok->u.backref.ref1 = backs[0];
}
else {
tok->u.backref.num = num;
tok->u.backref.refs = backs;
}
}
}
else
PUNFETCH;
}
break;
#ifdef USE_CALL
case 'g':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {
PFETCH(c);
if (c == '<' || c == '\'') {
int gnum;
UChar* name_end;
enum REF_NUM num_type;
prev = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env,
&gnum, &num_type, 1);
if (r < 0) return r;
if (num_type != IS_NOT_NUM) {
if (num_type == IS_REL_NUM) {
gnum = backref_rel_to_abs(gnum, env);
if (gnum < 0)
return ONIGERR_UNDEFINED_GROUP_REFERENCE;
}
tok->u.call.by_number = 1;
tok->u.call.gnum = gnum;
}
else {
tok->u.call.by_number = 0;
tok->u.call.gnum = 0;
}
tok->type = TK_CALL;
tok->u.call.name = prev;
tok->u.call.name_end = name_end;
}
else
PUNFETCH;
}
break;
#endif
case 'Q':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {
tok->type = TK_QUOTE_OPEN;
}
break;
case 'p':
case 'P':
if (!PEND && PPEEK_IS('{') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c);
if (c == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
break;
default:
{
OnigCodePoint c2;
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
/* set_raw: */
if (tok->u.c != c2) {
tok->type = TK_CODE_POINT;
tok->u.code = c2;
}
else { /* string */
p = tok->backp + enclen(enc, tok->backp);
}
}
break;
}
}
else {
tok->u.c = c;
tok->escaped = 0;
#ifdef USE_VARIABLE_META_CHARS
if ((c != ONIG_INEFFECTIVE_META_CHAR) &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {
if (c == MC_ANYCHAR(syn))
goto any_char;
else if (c == MC_ANYTIME(syn))
goto anytime;
else if (c == MC_ZERO_OR_ONE_TIME(syn))
goto zero_or_one_time;
else if (c == MC_ONE_OR_MORE_TIME(syn))
goto one_or_more_time;
else if (c == MC_ANYCHAR_ANYTIME(syn)) {
tok->type = TK_ANYCHAR_ANYTIME;
goto out;
}
}
#endif
switch (c) {
case '.':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;
#ifdef USE_VARIABLE_META_CHARS
any_char:
#endif
tok->type = TK_ANYCHAR;
break;
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
anytime:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
one_or_more_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;
#ifdef USE_VARIABLE_META_CHARS
zero_or_one_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
goto greedy_check;
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (! PEND) {
c = PPEEK;
if (c == '#') {
PFETCH(c);
while (1) {
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
if (c == MC_ESC(syn)) {
if (! PEND) PFETCH(c);
}
else {
if (c == ')') break;
}
}
goto start;
}
else if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_PERL_SUBEXP_CALL)) {
int gnum;
UChar* name;
UChar* name_end;
enum REF_NUM num_type;
switch (c) {
case '&':
{
PINC;
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum,
&num_type, 0);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.by_number = 0;
tok->u.call.gnum = 0;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
}
break;
case 'R':
tok->type = TK_CALL;
tok->u.call.by_number = 1;
tok->u.call.gnum = 0;
tok->u.call.name = p;
PINC;
if (! PPEEK_IS(')')) return ONIGERR_INVALID_GROUP_NAME;
tok->u.call.name_end = p;
break;
case '-':
case '+':
goto lparen_qmark_num;
break;
default:
if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto lparen_qmark_end;
lparen_qmark_num:
{
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env,
&gnum, &num_type, 1);
if (r < 0) return r;
if (num_type == IS_NOT_NUM) {
return ONIGERR_INVALID_GROUP_NAME;
}
else {
if (num_type == IS_REL_NUM) {
gnum = backref_rel_to_abs(gnum, env);
if (gnum < 0)
return ONIGERR_UNDEFINED_GROUP_REFERENCE;
}
tok->u.call.by_number = 1;
tok->u.call.gnum = gnum;
}
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
}
break;
}
}
}
lparen_qmark_end:
PUNFETCH;
}
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case '^':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->options)
? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);
break;
case '$':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->options)
? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);
break;
case '[':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;
tok->type = TK_CC_OPEN;
break;
case ']':
if (*src > env->pattern) /* /].../ is allowed. */
CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]");
break;
case '#':
if (IS_EXTEND(env->options)) {
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_NEWLINE(enc, c))
break;
}
goto start;
break;
}
break;
case ' ': case '\t': case '\n': case '\r': case '\f':
if (IS_EXTEND(env->options))
goto start;
break;
default:
/* string */
break;
}
}
#ifdef USE_VARIABLE_META_CHARS
out:
#endif
*src = p;
return tok->type;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'fix #87: Read unknown address in onig_error_code_to_str()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-125', 'CWE-908'], 'message': 'Avoid uninitialized memory
As reported by https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16856'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: archive_read_format_rar_read_data(struct archive_read *a, const void **buff,
size_t *size, int64_t *offset)
{
struct rar *rar = (struct rar *)(a->format->data);
int ret;
if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
rar->has_encrypted_entries = 0;
}
if (rar->bytes_unconsumed > 0) {
/* Consume as much as the decompressor actually used. */
__archive_read_consume(a, rar->bytes_unconsumed);
rar->bytes_unconsumed = 0;
}
*buff = NULL;
if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {
*size = 0;
*offset = rar->offset;
if (*offset < rar->unp_size)
*offset = rar->unp_size;
return (ARCHIVE_EOF);
}
switch (rar->compression_method)
{
case COMPRESS_METHOD_STORE:
ret = read_data_stored(a, buff, size, offset);
break;
case COMPRESS_METHOD_FASTEST:
case COMPRESS_METHOD_FAST:
case COMPRESS_METHOD_NORMAL:
case COMPRESS_METHOD_GOOD:
case COMPRESS_METHOD_BEST:
ret = read_data_compressed(a, buff, size, offset);
if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN)
__archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported compression method for RAR file.");
ret = ARCHIVE_FATAL;
break;
}
return (ret);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'RAR reader: fix use after free
If read_data_compressed() returns ARCHIVE_FAILED, the caller is allowed
to continue with next archive headers. We need to set rar->start_new_table
after the ppmd7_context got freed, otherwise it won't be allocated again.
Reported by: OSS-Fuzz issue 2582'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: walk_string(fz_context *ctx, int uni, int remove, editable_str *str)
{
int rune;
if (str->utf8 == NULL)
return;
do
{
char *s = &str->utf8[str->pos];
size_t len;
int n = fz_chartorune(&rune, s);
if (rune == uni)
{
/* Match. Skip over that one. */
str->pos += n;
}
else if (uni == 32) {
/* We don't care if we're given whitespace
* and it doesn't match the string. Don't
* skip forward. Nothing to remove. */
break;
}
else if (rune == 32) {
/* The string has a whitespace, and we
* don't match it; that's forgivable as
* PDF often misses out spaces. Remove this
* if we are removing stuff. */
}
else
{
/* Mismatch. No point in tracking through any more. */
str->pos = -1;
break;
}
if (remove)
{
len = strlen(s+n);
memmove(s, s+n, len+1);
str->edited = 1;
}
}
while (rune != uni);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Bug 701292: Fix test for missing/empty string.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_F(ConnectionHandlerTest, ContinueOnListenerFilterTimeout) {
InSequence s;
TestListener* test_listener =
addListener(1, true, false, "test_listener", Network::Address::SocketType::Stream,
std::chrono::milliseconds(15000), true);
Network::MockListener* listener = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks = &cb;
return listener;
}));
EXPECT_CALL(test_listener->socket_, localAddress());
handler_->addListener(*test_listener);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_))
.WillOnce(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus {
return Network::FilterStatus::StopIteration;
}));
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
Network::IoSocketHandleImpl io_handle{42};
EXPECT_CALL(*accepted_socket, ioHandle()).WillRepeatedly(ReturnRef(io_handle));
Event::MockTimer* timeout = new Event::MockTimer(&dispatcher_);
EXPECT_CALL(*timeout, enableTimer(std::chrono::milliseconds(15000), _));
listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});
Stats::Gauge& downstream_pre_cx_active =
stats_store_.gauge("downstream_pre_cx_active", Stats::Gauge::ImportMode::Accumulate);
EXPECT_EQ(1UL, downstream_pre_cx_active.value());
EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(nullptr));
EXPECT_CALL(*timeout, disableTimer());
timeout->invokeCallback();
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(0UL, downstream_pre_cx_active.value());
EXPECT_EQ(1UL, stats_store_.counter("downstream_pre_cx_timeout").value());
// Make sure we continued to try create connection.
EXPECT_EQ(1UL, stats_store_.counter("no_filter_chain_match").value());
EXPECT_CALL(*listener, onDestroy());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)
Signed-off-by: Yuchen Dai <[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: TEST_F(ConnectionHandlerTest, ListenerFilterTimeout) {
InSequence s;
TestListener* test_listener = addListener(1, true, false, "test_listener");
Network::MockListener* listener = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks = &cb;
return listener;
}));
EXPECT_CALL(test_listener->socket_, localAddress());
handler_->addListener(*test_listener);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_))
.WillOnce(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus {
return Network::FilterStatus::StopIteration;
}));
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
Network::IoSocketHandleImpl io_handle{42};
EXPECT_CALL(*accepted_socket, ioHandle()).WillRepeatedly(ReturnRef(io_handle));
Event::MockTimer* timeout = new Event::MockTimer(&dispatcher_);
EXPECT_CALL(*timeout, enableTimer(std::chrono::milliseconds(15000), _));
listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});
Stats::Gauge& downstream_pre_cx_active =
stats_store_.gauge("downstream_pre_cx_active", Stats::Gauge::ImportMode::Accumulate);
EXPECT_EQ(1UL, downstream_pre_cx_active.value());
EXPECT_CALL(*timeout, disableTimer());
timeout->invokeCallback();
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(0UL, downstream_pre_cx_active.value());
EXPECT_EQ(1UL, stats_store_.counter("downstream_pre_cx_timeout").value());
// Make sure we didn't continue to try create connection.
EXPECT_EQ(0UL, stats_store_.counter("no_filter_chain_match").value());
EXPECT_CALL(*listener, onDestroy());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)
Signed-off-by: Yuchen Dai <[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: TEST_F(ConnectionHandlerTest, ListenerFilterDisabledTimeout) {
InSequence s;
TestListener* test_listener =
addListener(1, true, false, "test_listener", Network::Address::SocketType::Stream,
std::chrono::milliseconds());
Network::MockListener* listener = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks = &cb;
return listener;
}));
EXPECT_CALL(test_listener->socket_, localAddress());
handler_->addListener(*test_listener);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_))
.WillOnce(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus {
return Network::FilterStatus::StopIteration;
}));
EXPECT_CALL(dispatcher_, createTimer_(_)).Times(0);
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_CALL(*listener, onDestroy());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)
Signed-off-by: Yuchen Dai <[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: TEST_F(ConnectionHandlerTest, WildcardListenerWithOriginalDst) {
TestListener* test_listener1 = addListener(1, true, true, "test_listener1");
Network::MockListener* listener1 = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks1;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks1 = &cb;
return listener1;
}));
Network::Address::InstanceConstSharedPtr normal_address(
new Network::Address::Ipv4Instance("127.0.0.1", 80));
// Original dst address nor port number match that of the listener's address.
Network::Address::InstanceConstSharedPtr original_dst_address(
new Network::Address::Ipv4Instance("127.0.0.2", 8080));
Network::Address::InstanceConstSharedPtr any_address = Network::Utility::getAddressWithPort(
*Network::Utility::getIpv4AnyAddress(), normal_address->ip()->port());
EXPECT_CALL(test_listener1->socket_, localAddress()).WillRepeatedly(ReturnRef(any_address));
handler_->addListener(*test_listener1);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
// Insert the Mock filter.
manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_))
.WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus {
cb.socket().restoreLocalAddress(original_dst_address);
return Network::FilterStatus::Continue;
}));
EXPECT_CALL(*accepted_socket, restoreLocalAddress(original_dst_address));
EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(true));
EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(original_dst_address));
EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get()));
Network::MockConnection* connection = new NiceMock<Network::MockConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillOnce(Return(true));
listener_callbacks1->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_EQ(1UL, handler_->numConnections());
EXPECT_CALL(*listener1, onDestroy());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)
Signed-off-by: Yuchen Dai <[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: TEST_F(ConnectionHandlerTest, FallbackToWildcardListener) {
TestListener* test_listener1 = addListener(1, true, true, "test_listener1");
Network::MockListener* listener1 = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks1;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks1 = &cb;
return listener1;
}));
Network::Address::InstanceConstSharedPtr normal_address(
new Network::Address::Ipv4Instance("127.0.0.1", 10001));
EXPECT_CALL(test_listener1->socket_, localAddress()).WillRepeatedly(ReturnRef(normal_address));
handler_->addListener(*test_listener1);
TestListener* test_listener2 = addListener(1, false, false, "test_listener2");
Network::MockListener* listener2 = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks2;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks2 = &cb;
return listener2;
}));
Network::Address::InstanceConstSharedPtr any_address = Network::Utility::getIpv4AnyAddress();
EXPECT_CALL(test_listener2->socket_, localAddress()).WillRepeatedly(ReturnRef(any_address));
handler_->addListener(*test_listener2);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
bool redirected = false;
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
// Insert the Mock filter.
if (!redirected) {
manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});
redirected = true;
}
return true;
}));
// Zero port to match the port of AnyAddress
Network::Address::InstanceConstSharedPtr alt_address(
new Network::Address::Ipv4Instance("127.0.0.2", 0));
EXPECT_CALL(*test_filter, onAccept(_))
.WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus {
cb.socket().restoreLocalAddress(alt_address);
return Network::FilterStatus::Continue;
}));
EXPECT_CALL(*accepted_socket, restoreLocalAddress(alt_address));
EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(true));
EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(alt_address));
EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get()));
Network::MockConnection* connection = new NiceMock<Network::MockConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillOnce(Return(true));
listener_callbacks1->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_EQ(1UL, handler_->numConnections());
EXPECT_CALL(*listener2, onDestroy());
EXPECT_CALL(*listener1, onDestroy());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)
Signed-off-by: Yuchen Dai <[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: TEST_F(ConnectionHandlerTest, WildcardListenerWithNoOriginalDst) {
TestListener* test_listener1 = addListener(1, true, true, "test_listener1");
Network::MockListener* listener1 = new Network::MockListener();
Network::ListenerCallbacks* listener_callbacks1;
EXPECT_CALL(dispatcher_, createListener_(_, _, _))
.WillOnce(
Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {
listener_callbacks1 = &cb;
return listener1;
}));
Network::Address::InstanceConstSharedPtr normal_address(
new Network::Address::Ipv4Instance("127.0.0.1", 80));
Network::Address::InstanceConstSharedPtr any_address = Network::Utility::getAddressWithPort(
*Network::Utility::getIpv4AnyAddress(), normal_address->ip()->port());
EXPECT_CALL(test_listener1->socket_, localAddress()).WillRepeatedly(ReturnRef(any_address));
handler_->addListener(*test_listener1);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
// Insert the Mock filter.
manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_)).WillOnce(Return(Network::FilterStatus::Continue));
EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(false));
EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(normal_address));
EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get()));
Network::MockConnection* connection = new NiceMock<Network::MockConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillOnce(Return(true));
listener_callbacks1->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_EQ(1UL, handler_->numConnections());
EXPECT_CALL(*listener1, onDestroy());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)
Signed-off-by: Yuchen Dai <[email protected]>'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.