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: long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
if(book->used_entries>0){
int i,j,entry;
float *t;
if(book->dim>8){
for(i=0;i<n;){
entry = decode_packed_entry_number(book,b);
if(entry==-1)return(-1);
t = book->valuelist+entry*book->dim;
for (j=0;j<book->dim;)
a[i++]+=t[j++];
}
}else{
for(i=0;i<n;){
entry = decode_packed_entry_number(book,b);
if(entry==-1)return(-1);
t = book->valuelist+entry*book->dim;
j=0;
switch((int)book->dim){
case 8:
a[i++]+=t[j++];
case 7:
a[i++]+=t[j++];
case 6:
a[i++]+=t[j++];
case 5:
a[i++]+=t[j++];
case 4:
a[i++]+=t[j++];
case 3:
a[i++]+=t[j++];
case 2:
a[i++]+=t[j++];
case 1:
a[i++]+=t[j++];
case 0:
break;
}
}
}
}
return(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2018-5146: Prevent out-of-bounds write in codebook decoding.
Codebooks that are not an exact divisor of the partition size are now
truncated to fit within the partition.'</s> |
<s>[INST] Given the following code containing errors, provide 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 vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
oggpack_buffer *b,int n){
long i,j,entry;
int chptr=0;
if(book->used_entries>0){
for(i=offset/ch;i<(offset+n)/ch;){
entry = decode_packed_entry_number(book,b);
if(entry==-1)return(-1);
{
const float *t = book->valuelist+entry*book->dim;
for (j=0;j<book->dim;j++){
a[chptr++][i]+=t[j];
if(chptr==ch){
chptr=0;
i++;
}
}
}
}
}
return(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2018-5146: Prevent out-of-bounds write in codebook decoding.
Codebooks that are not an exact divisor of the partition size are now
truncated to fit within the partition.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
get_block_t *get_block;
/*
* Fallback to buffered I/O if we see an inode without
* extents.
*/
if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
return 0;
/* Fallback to buffered I/O if we do not support append dio. */
if (iocb->ki_pos + iter->count > i_size_read(inode) &&
!ocfs2_supports_append_dio(osb))
return 0;
if (iov_iter_rw(iter) == READ)
get_block = ocfs2_get_block;
else
get_block = ocfs2_dio_get_block;
return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
iter, get_block,
ocfs2_dio_end_io, NULL, 0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'ocfs2: ip_alloc_sem should be taken in ocfs2_get_block()
ip_alloc_sem should be taken in ocfs2_get_block() when reading file in
DIRECT mode to prevent concurrent access to extent tree with
ocfs2_dio_end_io_write(), which may cause BUGON in the following
situation:
read file 'A' end_io of writing file 'A'
vfs_read
__vfs_read
ocfs2_file_read_iter
generic_file_read_iter
ocfs2_direct_IO
__blockdev_direct_IO
do_blockdev_direct_IO
do_direct_IO
get_more_blocks
ocfs2_get_block
ocfs2_extent_map_get_blocks
ocfs2_get_clusters
ocfs2_get_clusters_nocache()
ocfs2_search_extent_list
return the index of record which
contains the v_cluster, that is
v_cluster > rec[i]->e_cpos.
ocfs2_dio_end_io
ocfs2_dio_end_io_write
down_write(&oi->ip_alloc_sem);
ocfs2_mark_extent_written
ocfs2_change_extent_flag
ocfs2_split_extent
...
--> modify the rec[i]->e_cpos, resulting
in v_cluster < rec[i]->e_cpos.
BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos))
[[email protected]: v3]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io")
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Reviewed-by: Gang He <[email protected]>
Acked-by: Changwei Ge <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sas_resume_port(struct asd_sas_phy *phy)
{
struct domain_device *dev;
struct asd_sas_port *port = phy->port;
struct sas_ha_struct *sas_ha = phy->ha;
struct sas_internal *si = to_sas_internal(sas_ha->core.shost->transportt);
if (si->dft->lldd_port_formed)
si->dft->lldd_port_formed(phy);
if (port->suspended)
port->suspended = 0;
else {
/* we only need to handle "link returned" actions once */
return;
}
/* if the port came back:
* 1/ presume every device came back
* 2/ force the next revalidation to check all expander phys
*/
list_for_each_entry(dev, &port->dev_list, dev_list_node) {
int i, rc;
rc = sas_notify_lldd_dev_found(dev);
if (rc) {
sas_unregister_dev(port, dev);
continue;
}
if (dev->dev_type == SAS_EDGE_EXPANDER_DEVICE || dev->dev_type == SAS_FANOUT_EXPANDER_DEVICE) {
dev->ex_dev.ex_change_count = -1;
for (i = 0; i < dev->ex_dev.num_phys; i++) {
struct ex_phy *phy = &dev->ex_dev.ex_phy[i];
phy->phy_change_count = -1;
}
}
}
sas_discover_event(port, DISCE_RESUME);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[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: int sas_discover_end_dev(struct domain_device *dev)
{
int res;
res = sas_notify_lldd_dev_found(dev);
if (res)
return res;
sas_discover_event(dev->port, DISCE_PROBE);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[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 void sas_unregister_devs_sas_addr(struct domain_device *parent,
int phy_id, bool last)
{
struct expander_device *ex_dev = &parent->ex_dev;
struct ex_phy *phy = &ex_dev->ex_phy[phy_id];
struct domain_device *child, *n, *found = NULL;
if (last) {
list_for_each_entry_safe(child, n,
&ex_dev->children, siblings) {
if (SAS_ADDR(child->sas_addr) ==
SAS_ADDR(phy->attached_sas_addr)) {
set_bit(SAS_DEV_GONE, &child->state);
if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
child->dev_type == SAS_FANOUT_EXPANDER_DEVICE)
sas_unregister_ex_tree(parent->port, child);
else
sas_unregister_dev(parent->port, child);
found = child;
break;
}
}
sas_disable_routing(parent, phy->attached_sas_addr);
}
memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE);
if (phy->port) {
sas_port_delete_phy(phy->port, phy->phy);
sas_device_set_phy(found, phy->port);
if (phy->port->num_phys == 0)
sas_port_delete(phy->port);
phy->port = NULL;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[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: void sas_init_disc(struct sas_discovery *disc, struct asd_sas_port *port)
{
int i;
static const work_func_t sas_event_fns[DISC_NUM_EVENTS] = {
[DISCE_DISCOVER_DOMAIN] = sas_discover_domain,
[DISCE_REVALIDATE_DOMAIN] = sas_revalidate_domain,
[DISCE_PROBE] = sas_probe_devices,
[DISCE_SUSPEND] = sas_suspend_devices,
[DISCE_RESUME] = sas_resume_devices,
[DISCE_DESTRUCT] = sas_destruct_devices,
};
disc->pending = 0;
for (i = 0; i < DISC_NUM_EVENTS; i++) {
INIT_SAS_WORK(&disc->disc_work[i].work, sas_event_fns[i]);
disc->disc_work[i].port = port;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[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 void sas_revalidate_domain(struct work_struct *work)
{
int res = 0;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
struct sas_ha_struct *ha = port->ha;
struct domain_device *ddev = port->port_dev;
/* prevent revalidation from finding sata links in recovery */
mutex_lock(&ha->disco_mutex);
if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) {
SAS_DPRINTK("REVALIDATION DEFERRED on port %d, pid:%d\n",
port->id, task_pid_nr(current));
goto out;
}
clear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending);
SAS_DPRINTK("REVALIDATING DOMAIN on port %d, pid:%d\n", port->id,
task_pid_nr(current));
if (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE ||
ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE))
res = sas_ex_revalidate_domain(ddev);
SAS_DPRINTK("done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\n",
port->id, task_pid_nr(current), res);
out:
mutex_unlock(&ha->disco_mutex);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[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: int sas_ex_revalidate_domain(struct domain_device *port_dev)
{
int res;
struct domain_device *dev = NULL;
res = sas_find_bcast_dev(port_dev, &dev);
while (res == 0 && dev) {
struct expander_device *ex = &dev->ex_dev;
int i = 0, phy_id;
do {
phy_id = -1;
res = sas_find_bcast_phy(dev, &phy_id, i, true);
if (phy_id == -1)
break;
res = sas_rediscover(dev, phy_id);
i = phy_id + 1;
} while (i < ex->num_phys);
dev = NULL;
res = sas_find_bcast_dev(port_dev, &dev);
}
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[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 inline void flush_tmregs_to_thread(struct task_struct *tsk) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'powerpc/tm: Flush TM only if CPU has TM feature
Commit cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump")
added code to access TM SPRs in flush_tmregs_to_thread(). However
flush_tmregs_to_thread() does not check if TM feature is available on
CPU before trying to access TM SPRs in order to copy live state to
thread structures. flush_tmregs_to_thread() is indeed guarded by
CONFIG_PPC_TRANSACTIONAL_MEM but it might be the case that kernel
was compiled with CONFIG_PPC_TRANSACTIONAL_MEM enabled and ran on
a CPU without TM feature available, thus rendering the execution
of TM instructions that are treated by the CPU as illegal instructions.
The fix is just to add proper checking in flush_tmregs_to_thread()
if CPU has the TM feature before accessing any TM-specific resource,
returning immediately if TM is no available on the CPU. Adding
that checking in flush_tmregs_to_thread() instead of in places
where it is called, like in vsr_get() and vsr_set(), is better because
avoids the same problem cropping up elsewhere.
Cc: [email protected] # v4.13+
Fixes: cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump")
Signed-off-by: Gustavo Romero <[email protected]>
Reviewed-by: Cyril Bur <[email protected]>
Signed-off-by: Michael Ellerman <[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: ncp_read_kernel(struct ncp_server *server, const char *file_id,
__u32 offset, __u16 to_read, char *target, int *bytes_read)
{
const char *source;
int result;
ncp_init_request(server);
ncp_add_byte(server, 0);
ncp_add_mem(server, file_id, 6);
ncp_add_be32(server, offset);
ncp_add_be16(server, to_read);
if ((result = ncp_request(server, 72)) != 0) {
goto out;
}
*bytes_read = ncp_reply_be16(server, 0);
source = ncp_reply_data(server, 2 + (offset & 1));
memcpy(target, source, *bytes_read);
out:
ncp_unlock_server(server);
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'staging: ncpfs: memory corruption in ncp_read_kernel()
If the server is malicious then *bytes_read could be larger than the
size of the "target" buffer. It would lead to memory corruption when we
do the memcpy().
Reported-by: Dr Silvio Cesare of InfoSect <Silvio Cesare <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 build_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_sm_info *sm_info;
int err;
sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
if (!sm_info)
return -ENOMEM;
/* init sm info */
sbi->sm_info = sm_info;
sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
sm_info->rec_prefree_segments = sm_info->main_segments *
DEF_RECLAIM_PREFREE_SEGMENTS / 100;
if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
if (!test_opt(sbi, LFS))
sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
INIT_LIST_HEAD(&sm_info->sit_entry_set);
if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) {
err = create_flush_cmd_control(sbi);
if (err)
return err;
}
err = create_discard_cmd_control(sbi);
if (err)
return err;
err = build_sit_info(sbi);
if (err)
return err;
err = build_free_segmap(sbi);
if (err)
return err;
err = build_curseg(sbi);
if (err)
return err;
/* reinit free segmap based on SIT */
build_sit_entries(sbi);
init_free_segmap(sbi);
err = build_dirty_segmap(sbi);
if (err)
return err;
init_min_max_mtime(sbi);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-476'], 'message': 'f2fs: fix a panic caused by NULL flush_cmd_control
Mount fs with option noflush_merge, boot failed for illegal address
fcc in function f2fs_issue_flush:
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush); -> Here, fcc illegal
return ret;
}
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Token *tokenize(char *line)
{
char c, *p = line;
enum pp_token_type type;
Token *list = NULL;
Token *t, **tail = &list;
while (*line) {
p = line;
if (*p == '%') {
p++;
if (*p == '+' && !nasm_isdigit(p[1])) {
p++;
type = TOK_PASTE;
} else if (nasm_isdigit(*p) ||
((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
do {
p++;
}
while (nasm_isdigit(*p));
type = TOK_PREPROC_ID;
} else if (*p == '{') {
p++;
while (*p) {
if (*p == '}')
break;
p[-1] = *p;
p++;
}
if (*p != '}')
nasm_error(ERR_WARNING | ERR_PASS1,
"unterminated %%{ construct");
p[-1] = '\0';
if (*p)
p++;
type = TOK_PREPROC_ID;
} else if (*p == '[') {
int lvl = 1;
line += 2; /* Skip the leading %[ */
p++;
while (lvl && (c = *p++)) {
switch (c) {
case ']':
lvl--;
break;
case '%':
if (*p == '[')
lvl++;
break;
case '\'':
case '\"':
case '`':
p = nasm_skip_string(p - 1) + 1;
break;
default:
break;
}
}
p--;
if (*p)
*p++ = '\0';
if (lvl)
nasm_error(ERR_NONFATAL|ERR_PASS1,
"unterminated %%[ construct");
type = TOK_INDIRECT;
} else if (*p == '?') {
type = TOK_PREPROC_Q; /* %? */
p++;
if (*p == '?') {
type = TOK_PREPROC_QQ; /* %?? */
p++;
}
} else if (*p == '!') {
type = TOK_PREPROC_ID;
p++;
if (isidchar(*p)) {
do {
p++;
}
while (isidchar(*p));
} else if (*p == '\'' || *p == '\"' || *p == '`') {
p = nasm_skip_string(p);
if (*p)
p++;
else
nasm_error(ERR_NONFATAL|ERR_PASS1,
"unterminated %%! string");
} else {
/* %! without string or identifier */
type = TOK_OTHER; /* Legacy behavior... */
}
} else if (isidchar(*p) ||
((*p == '!' || *p == '%' || *p == '$') &&
isidchar(p[1]))) {
do {
p++;
}
while (isidchar(*p));
type = TOK_PREPROC_ID;
} else {
type = TOK_OTHER;
if (*p == '%')
p++;
}
} else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
type = TOK_ID;
p++;
while (*p && isidchar(*p))
p++;
} else if (*p == '\'' || *p == '"' || *p == '`') {
/*
* A string token.
*/
type = TOK_STRING;
p = nasm_skip_string(p);
if (*p) {
p++;
} else {
nasm_error(ERR_WARNING|ERR_PASS1, "unterminated string");
/* Handling unterminated strings by UNV */
/* type = -1; */
}
} else if (p[0] == '$' && p[1] == '$') {
type = TOK_OTHER; /* TOKEN_BASE */
p += 2;
} else if (isnumstart(*p)) {
bool is_hex = false;
bool is_float = false;
bool has_e = false;
char c, *r;
/*
* A numeric token.
*/
if (*p == '$') {
p++;
is_hex = true;
}
for (;;) {
c = *p++;
if (!is_hex && (c == 'e' || c == 'E')) {
has_e = true;
if (*p == '+' || *p == '-') {
/*
* e can only be followed by +/- if it is either a
* prefixed hex number or a floating-point number
*/
p++;
is_float = true;
}
} else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
is_hex = true;
} else if (c == 'P' || c == 'p') {
is_float = true;
if (*p == '+' || *p == '-')
p++;
} else if (isnumchar(c))
; /* just advance */
else if (c == '.') {
/*
* we need to deal with consequences of the legacy
* parser, like "1.nolist" being two tokens
* (TOK_NUMBER, TOK_ID) here; at least give it
* a shot for now. In the future, we probably need
* a flex-based scanner with proper pattern matching
* to do it as well as it can be done. Nothing in
* the world is going to help the person who wants
* 0x123.p16 interpreted as two tokens, though.
*/
r = p;
while (*r == '_')
r++;
if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
(!is_hex && (*r == 'e' || *r == 'E')) ||
(*r == 'p' || *r == 'P')) {
p = r;
is_float = true;
} else
break; /* Terminate the token */
} else
break;
}
p--; /* Point to first character beyond number */
if (p == line+1 && *line == '$') {
type = TOK_OTHER; /* TOKEN_HERE */
} else {
if (has_e && !is_hex) {
/* 1e13 is floating-point, but 1e13h is not */
is_float = true;
}
type = is_float ? TOK_FLOAT : TOK_NUMBER;
}
} else if (nasm_isspace(*p)) {
type = TOK_WHITESPACE;
p = nasm_skip_spaces(p);
/*
* Whitespace just before end-of-line is discarded by
* pretending it's a comment; whitespace just before a
* comment gets lumped into the comment.
*/
if (!*p || *p == ';') {
type = TOK_COMMENT;
while (*p)
p++;
}
} else if (*p == ';') {
type = TOK_COMMENT;
while (*p)
p++;
} else {
/*
* Anything else is an operator of some kind. We check
* for all the double-character operators (>>, <<, //,
* %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
* else is a single-character operator.
*/
type = TOK_OTHER;
if ((p[0] == '>' && p[1] == '>') ||
(p[0] == '<' && p[1] == '<') ||
(p[0] == '/' && p[1] == '/') ||
(p[0] == '<' && p[1] == '=') ||
(p[0] == '>' && p[1] == '=') ||
(p[0] == '=' && p[1] == '=') ||
(p[0] == '!' && p[1] == '=') ||
(p[0] == '<' && p[1] == '>') ||
(p[0] == '&' && p[1] == '&') ||
(p[0] == '|' && p[1] == '|') ||
(p[0] == '^' && p[1] == '^')) {
p++;
}
p++;
}
/* Handling unterminated string by UNV */
/*if (type == -1)
{
*tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
t->text[p-line] = *line;
tail = &t->next;
}
else */
if (type != TOK_COMMENT) {
*tail = t = new_Token(NULL, type, line, p - line);
tail = &t->next;
}
line = p;
}
return list;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'preproc: Don't access offsting byte on unterminated strings
https://bugzilla.nasm.us/show_bug.cgi?id=3392446
Signed-off-by: Cyrill Gorcunov <[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: add_job(cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer, /* I - Destination printer */
mime_type_t *filetype) /* I - First print file type, if any */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr, /* Current attribute */
*auth_info; /* auth-info attribute */
const char *mandatory; /* Current mandatory job attribute */
const char *val; /* Default option value */
int priority; /* Job priority */
cupsd_job_t *job; /* Current job */
char job_uri[HTTP_MAX_URI]; /* Job URI */
int kbytes; /* Size of print file */
int i; /* Looping var */
int lowerpagerange; /* Page range bound */
int exact; /* Did we have an exact match? */
ipp_attribute_t *media_col, /* media-col attribute */
*media_margin; /* media-*-margin attribute */
ipp_t *unsup_col; /* media-col in unsupported response */
static const char * const readonly[] =/* List of read-only attributes */
{
"date-time-at-completed",
"date-time-at-creation",
"date-time-at-processing",
"job-detailed-status-messages",
"job-document-access-errors",
"job-id",
"job-impressions-completed",
"job-k-octets-completed",
"job-media-sheets-completed",
"job-pages-completed",
"job-printer-up-time",
"job-printer-uri",
"job-state",
"job-state-message",
"job-state-reasons",
"job-uri",
"number-of-documents",
"number-of-intervening-jobs",
"output-device-assigned",
"time-at-completed",
"time-at-creation",
"time-at-processing"
};
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))",
con, con->number, printer, printer->name,
filetype, filetype ? filetype->super : "none",
filetype ? filetype->type : "none");
/*
* Check remote printing to non-shared printer...
*/
if (!printer->shared &&
_cups_strcasecmp(con->http->hostname, "localhost") &&
_cups_strcasecmp(con->http->hostname, ServerName))
{
send_ipp_status(con, IPP_NOT_AUTHORIZED,
_("The printer or class is not shared."));
return (NULL);
}
/*
* Check policy...
*/
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return (NULL);
}
else if (printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
!con->username[0])
{
send_http_error(con, HTTP_UNAUTHORIZED, printer);
return (NULL);
}
#ifdef HAVE_SSL
else if (auth_info && !con->http->tls &&
!httpAddrLocalhost(con->http->hostaddr))
{
/*
* Require encryption of auth-info over non-local connections...
*/
send_http_error(con, HTTP_UPGRADE_REQUIRED, printer);
return (NULL);
}
#endif /* HAVE_SSL */
/*
* See if the printer is accepting jobs...
*/
if (!printer->accepting)
{
send_ipp_status(con, IPP_NOT_ACCEPTING,
_("Destination \"%s\" is not accepting jobs."),
printer->name);
return (NULL);
}
/*
* Validate job template attributes; for now just document-format,
* copies, job-sheets, number-up, page-ranges, mandatory attributes, and
* media...
*/
for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++)
{
if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL)
{
ippDeleteAttribute(con->request, attr);
if (StrictConformance)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]);
return (NULL);
}
cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]);
}
}
if (printer->pc)
{
for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory);
mandatory;
mandatory = (char *)cupsArrayNext(printer->pc->mandatory))
{
if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO))
{
/*
* Missing a required attribute...
*/
send_ipp_status(con, IPP_CONFLICT,
_("The \"%s\" attribute is required for print jobs."),
mandatory);
return (NULL);
}
}
}
if (filetype && printer->filetypes &&
!cupsArrayFind(printer->filetypes, filetype))
{
char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* MIME media type string */
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported format \"%s\"."), mimetype);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
return (NULL);
}
if ((attr = ippFindAttribute(con->request, "copies",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"copies", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "job-sheets",
IPP_TAG_ZERO)) != NULL)
{
if (attr->value_tag != IPP_TAG_KEYWORD &&
attr->value_tag != IPP_TAG_NAME)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type."));
return (NULL);
}
if (attr->num_values > 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Too many job-sheets values (%d > 2)."),
attr->num_values);
return (NULL);
}
for (i = 0; i < attr->num_values; i ++)
if (strcmp(attr->values[i].string.text, "none") &&
!cupsdFindBanner(attr->values[i].string.text))
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."),
attr->values[i].string.text);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "number-up",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer != 1 &&
attr->values[0].integer != 2 &&
attr->values[0].integer != 4 &&
attr->values[0].integer != 6 &&
attr->values[0].integer != 9 &&
attr->values[0].integer != 16)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"number-up", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "page-ranges",
IPP_TAG_RANGE)) != NULL)
{
for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++)
{
if (attr->values[i].range.lower < lowerpagerange ||
attr->values[i].range.lower > attr->values[i].range.upper)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad page-ranges values %d-%d."),
attr->values[i].range.lower,
attr->values[i].range.upper);
return (NULL);
}
lowerpagerange = attr->values[i].range.upper + 1;
}
}
/*
* Do media selection as needed...
*/
if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) &&
!ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) &&
_ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact))
{
if (!exact &&
(media_col = ippFindAttribute(con->request, "media-col",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins."));
unsup_col = ippNew();
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-bottom-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-bottom-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-left-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-left-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-right-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-right-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-top-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-top-margin", media_margin->values[0].integer);
ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col",
unsup_col);
ippDelete(unsup_col);
}
}
/*
* Make sure we aren't over our limit...
*/
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
cupsdCleanJobs();
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs."));
return (NULL);
}
if ((i = check_quotas(con, printer)) < 0)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached."));
return (NULL);
}
else if (i == 0)
{
send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print."));
return (NULL);
}
/*
* Create the job and set things up...
*/
if ((attr = ippFindAttribute(con->request, "job-priority",
IPP_TAG_INTEGER)) != NULL)
priority = attr->values[0].integer;
else
{
if ((val = cupsGetOption("job-priority", printer->num_options,
printer->options)) != NULL)
priority = atoi(val);
else
priority = 50;
ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority",
priority);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL)
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled");
else if ((attr->value_tag != IPP_TAG_NAME &&
attr->value_tag != IPP_TAG_NAMELANG) ||
attr->num_values != 1)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Bad job-name value: Wrong type or count."));
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
else if (!ippValidateAttribute(attr))
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"),
cupsLastErrorString());
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
if ((job = cupsdAddJob(priority, printer->name)) == NULL)
{
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("Unable to add job for destination \"%s\"."),
printer->name);
return (NULL);
}
job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE);
job->attrs = con->request;
job->dirty = 1;
con->request = ippNewRequest(job->attrs->request.op.operation_id);
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
add_job_uuid(job);
apply_printer_defaults(printer, job);
attr = ippFindAttribute(job->attrs, "requesting-user-name", IPP_TAG_NAME);
if (con->username[0])
{
cupsdSetString(&job->username, con->username);
if (attr)
ippSetString(job->attrs, &attr, 0, con->username);
}
else if (attr)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"add_job: requesting-user-name=\"%s\"",
attr->values[0].string.text);
cupsdSetString(&job->username, attr->values[0].string.text);
}
else
cupsdSetString(&job->username, "anonymous");
if (!attr)
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-user-name", NULL, job->username);
else
{
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
ippSetName(job->attrs, &attr, "job-originating-user-name");
}
if (con->username[0] || auth_info)
{
save_auth_info(con, job, auth_info);
/*
* Remove the auth-info attribute from the attribute data...
*/
if (auth_info)
ippDeleteAttribute(job->attrs, auth_info);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL)
cupsdSetString(&(job->name), attr->values[0].string.text);
if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name",
IPP_TAG_ZERO)) != NULL)
{
/*
* Request contains a job-originating-host-name attribute; validate it...
*/
if (attr->value_tag != IPP_TAG_NAME ||
attr->num_values != 1 ||
strcmp(con->http->hostname, "localhost"))
{
/*
* Can't override the value if we aren't connected via localhost.
* Also, we can only have 1 value and it must be a name value.
*/
ippDeleteAttribute(job->attrs, attr);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname);
}
else
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
}
else
{
/*
* No job-originating-host-name attribute, so use the hostname from
* the connection...
*/
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-host-name", NULL, con->http->hostname);
}
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed");
ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL)));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing");
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed");
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing");
/*
* Add remaining job attributes...
*/
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM,
"job-state", IPP_JOB_STOPPED);
job->state_value = (ipp_jstate_t)job->state->values[0].integer;
job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-state-reasons", NULL, "job-incoming");
job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0);
job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-media-sheets-completed", 0);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL,
printer->uri);
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer = 0;
else
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0);
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr)
{
if ((val = cupsGetOption("job-hold-until", printer->num_options,
printer->options)) == NULL)
val = "no-hold";
attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-hold-until", NULL, val);
}
if (printer->holding_new_jobs)
{
/*
* Hold all new jobs on this printer...
*/
if (attr && strcmp(attr->values[0].string.text, "no-hold"))
cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0);
else
cupsdSetJobHoldUntil(job, "indefinite", 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create");
}
else if (attr && strcmp(attr->values[0].string.text, "no-hold"))
{
/*
* Hold job until specified time...
*/
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
}
else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB)
{
job->hold_until = time(NULL) + MultipleOperationTimeout;
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
}
else
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification)
{
/*
* Add job sheets options...
*/
if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Adding default job-sheets values \"%s,%s\"...",
printer->job_sheets[0], printer->job_sheets[1]);
attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets",
2, NULL, NULL);
ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]);
ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]);
}
job->job_sheets = attr;
/*
* Enforce classification level if set...
*/
if (Classification)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Classification=\"%s\", ClassifyOverride=%d",
Classification ? Classification : "(null)",
ClassifyOverride);
if (ClassifyOverride)
{
if (!strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
!strcmp(attr->values[1].string.text, "none")))
{
/*
* Force the leading banner to have the classification on it...
*/
ippSetString(job->attrs, &attr, 0, Classification);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,none\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
else if (attr->num_values == 2 &&
strcmp(attr->values[0].string.text,
attr->values[1].string.text) &&
strcmp(attr->values[0].string.text, "none") &&
strcmp(attr->values[1].string.text, "none"))
{
/*
* Can't put two different security markings on the same document!
*/
ippSetString(job->attrs, &attr, 1, attr->values[0].string.text);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
else if (strcmp(attr->values[0].string.text, Classification) &&
strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
(strcmp(attr->values[1].string.text, Classification) &&
strcmp(attr->values[1].string.text, "none"))))
{
if (attr->num_values == 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s,%s\",fffff "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
}
else if (strcmp(attr->values[0].string.text, Classification) &&
(attr->num_values == 1 ||
strcmp(attr->values[1].string.text, Classification)))
{
/*
* Force the banner to have the classification on it...
*/
if (attr->num_values > 1 &&
!strcmp(attr->values[0].string.text, attr->values[1].string.text))
{
ippSetString(job->attrs, &attr, 0, Classification);
ippSetString(job->attrs, &attr, 1, Classification);
}
else
{
if (attr->num_values == 1 ||
strcmp(attr->values[0].string.text, "none"))
ippSetString(job->attrs, &attr, 0, Classification);
if (attr->num_values > 1 &&
strcmp(attr->values[1].string.text, "none"))
ippSetString(job->attrs, &attr, 1, Classification);
}
if (attr->num_values > 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
}
/*
* See if we need to add the starting sheet...
*/
if (!(printer->type & CUPS_PRINTER_REMOTE))
{
cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".",
attr->values[0].string.text);
if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0)
{
cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
"Aborting job because the start banner could not be "
"copied.");
return (NULL);
}
cupsdUpdateQuota(printer, job->username, 0, kbytes);
}
}
else if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) != NULL)
job->job_sheets = attr;
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, "");
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons",
NULL, job->reasons->values[0].string.text);
con->response->request.status.status_code = IPP_OK;
/*
* Add any job subscriptions...
*/
add_job_subscriptions(con, job);
/*
* Set all but the first two attributes to the job attributes group...
*/
for (attr = job->attrs->attrs->next->next; attr; attr = attr->next)
attr->group_tag = IPP_TAG_JOB;
/*
* Fire the "job created" event...
*/
cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created.");
/*
* Return the new job...
*/
return (job);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'DBUS notifications could crash the scheduler (Issue #5143)
- scheduler/ipp.c: Make sure requesting-user-name string is valid UTF-8.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_calcssexp(jpc_fix_t stepsize)
{
return jpc_firstone(stepsize) - JPC_FIX_FRACBITS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads
Fixes CVE-2018-9055 (denial of service via a reachable assertion due
to integer overflow).
Based on a patch from Fridrich Strba <[email protected]>. Instead of
switching to `int_fast32_t`, this patch splits jpc_firstone() into two
overloads, one for `int` and one for `jpc_fix_t`. This is safer
against future changes on `jpc_fix_t`. To avoid the overhead of 64
bit integer math on 32 bit CPUs, this leaves the `int` overload
around.
Closes https://github.com/jasper-maint/jasper/issues/9'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_firstone(int x)
{
int n;
/* The argument must be nonnegative. */
assert(x >= 0);
n = -1;
while (x > 0) {
x >>= 1;
++n;
}
return n;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads
Fixes CVE-2018-9055 (denial of service via a reachable assertion due
to integer overflow).
Based on a patch from Fridrich Strba <[email protected]>. Instead of
switching to `int_fast32_t`, this patch splits jpc_firstone() into two
overloads, one for `int` and one for `jpc_fix_t`. This is safer
against future changes on `jpc_fix_t`. To avoid the overhead of 64
bit integer math on 32 bit CPUs, this leaves the `int` overload
around.
Closes https://github.com/jasper-maint/jasper/issues/9'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_enc_enccblks(jpc_enc_t *enc)
{
jpc_enc_tcmpt_t *tcmpt;
jpc_enc_tcmpt_t *endcomps;
jpc_enc_rlvl_t *lvl;
jpc_enc_rlvl_t *endlvls;
jpc_enc_band_t *band;
jpc_enc_band_t *endbands;
jpc_enc_cblk_t *cblk;
jpc_enc_cblk_t *endcblks;
int i;
int j;
jpc_fix_t mx;
jpc_fix_t bmx;
jpc_fix_t v;
jpc_enc_tile_t *tile;
uint_fast32_t prcno;
jpc_enc_prc_t *prc;
tile = enc->curtile;
endcomps = &tile->tcmpts[tile->numtcmpts];
for (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) {
endlvls = &tcmpt->rlvls[tcmpt->numrlvls];
for (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) {
if (!lvl->bands) {
continue;
}
endbands = &lvl->bands[lvl->numbands];
for (band = lvl->bands; band != endbands; ++band) {
if (!band->data) {
continue;
}
for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
if (!prc->cblks) {
continue;
}
bmx = 0;
endcblks = &prc->cblks[prc->numcblks];
for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
mx = 0;
for (i = 0; i < jas_matrix_numrows(cblk->data); ++i) {
for (j = 0; j < jas_matrix_numcols(cblk->data); ++j) {
v = JAS_ABS(jas_matrix_get(cblk->data, i, j));
if (v > mx) {
mx = v;
}
}
}
if (mx > bmx) {
bmx = mx;
}
cblk->numbps = JAS_MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);
}
for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
cblk->numimsbs = band->numbps - cblk->numbps;
assert(cblk->numimsbs >= 0);
}
for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
if (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) {
return -1;
}
}
}
}
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads
Fixes CVE-2018-9055 (denial of service via a reachable assertion due
to integer overflow).
Based on a patch from Fridrich Strba <[email protected]>. Instead of
switching to `int_fast32_t`, this patch splits jpc_firstone() into two
overloads, one for `int` and one for `jpc_fix_t`. This is safer
against future changes on `jpc_fix_t`. To avoid the overhead of 64
bit integer math on 32 bit CPUs, this leaves the `int` overload
around.
Closes https://github.com/jasper-maint/jasper/issues/9'</s> |
<s>[INST] Given the following code containing errors, provide 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 LogOpenCLBuildFailure(MagickCLDevice device,const char *kernel,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
*log;
size_t
log_size;
(void) FormatLocaleString(filename,MagickPathExtent,"%s%s%s",
GetOpenCLCacheDirectory(),DirectorySeparator,"magick_badcl.cl");
(void) remove_utf8(filename);
(void) BlobToFile(filename,kernel,strlen(kernel),exception);
openCL_library->clGetProgramBuildInfo(device->program,device->deviceID,
CL_PROGRAM_BUILD_LOG,0,NULL,&log_size);
log=(char*)AcquireMagickMemory(log_size);
openCL_library->clGetProgramBuildInfo(device->program,device->deviceID,
CL_PROGRAM_BUILD_LOG,log_size,log,&log_size);
(void) FormatLocaleString(filename,MagickPathExtent,"%s%s%s",
GetOpenCLCacheDirectory(),DirectorySeparator,"magick_badcl.log");
(void) remove_utf8(filename);
(void) BlobToFile(filename,log,log_size,exception);
log=(char*)RelinquishMagickMemory(log);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/793'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,
const int argc,const char **argv,Image **images,ExceptionInfo *exception)
{
const char
*option;
ImageInfo
*mogrify_info;
MagickStatusType
status;
PixelInterpolateMethod
interpolate_method;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
count,
index;
/*
Apply options to the image list.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image **) NULL);
assert((*images)->previous == (Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
if ((argc <= 0) || (*argv == (char *) NULL))
return(MagickTrue);
interpolate_method=UndefinedInterpolatePixel;
mogrify_info=CloneImageInfo(image_info);
quantize_info=AcquireQuantizeInfo(mogrify_info);
status=MagickTrue;
for (i=0; i < (ssize_t) argc; i++)
{
if (*images == (Image *) NULL)
break;
option=argv[i];
if (IsCommandOption(option) == MagickFalse)
continue;
count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
count=MagickMax(count,0L);
if ((i+count) >= (ssize_t) argc)
break;
status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("affinity",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images,exception);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
i++;
break;
}
if (LocaleCompare("append",option+1) == 0)
{
Image
*append_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
append_image=AppendImages(*images,*option == '-' ? MagickTrue :
MagickFalse,exception);
if (append_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=append_image;
break;
}
if (LocaleCompare("average",option+1) == 0)
{
Image
*average_image;
/*
Average an image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
average_image=EvaluateImages(*images,MeanEvaluateOperator,
exception);
if (average_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=average_image;
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channel-fx",option+1) == 0)
{
Image
*channel_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
channel_image=ChannelFxImage(*images,argv[i+1],exception);
if (channel_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=channel_image;
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
clut_image=RemoveFirstImageFromList(images);
if (clut_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) ClutImage(image,clut_image,interpolate_method,exception);
clut_image=DestroyImage(clut_image);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
Image
*coalesce_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
coalesce_image=CoalesceImages(*images,exception);
if (coalesce_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=coalesce_image;
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
ColorspaceType
colorspace;
Image
*combine_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
colorspace=(*images)->colorspace;
if ((*images)->number_channels < GetImageListLength(*images))
colorspace=sRGBColorspace;
if (*option == '+')
colorspace=(ColorspaceType) ParseCommandOption(
MagickColorspaceOptions,MagickFalse,argv[i+1]);
combine_image=CombineImages(*images,colorspace,exception);
if (combine_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=combine_image;
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
double
distortion;
Image
*difference_image,
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
reconstruct_image=RemoveFirstImageFromList(images);
if (reconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
metric=UndefinedErrorMetric;
option=GetImageOption(mogrify_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
difference_image=CompareImages(image,reconstruct_image,metric,
&distortion,exception);
if (difference_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImage(*images);
*images=difference_image;
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
ComplexOperator
op;
Image
*complex_images;
(void) SyncImageSettings(mogrify_info,*images,exception);
op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,
MagickFalse,argv[i+1]);
complex_images=ComplexImages(*images,op,exception);
if (complex_images == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=complex_images;
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
CompositeOperator
compose;
const char*
value;
MagickBooleanType
clip_to_self;
Image
*mask_image,
*new_images,
*source_image;
RectangleInfo
geometry;
/* Compose value from "-compose" option only */
(void) SyncImageSettings(mogrify_info,*images,exception);
value=GetImageOption(mogrify_info,"compose");
if (value == (const char *) NULL)
compose=OverCompositeOp; /* use Over not source_image->compose */
else
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,value);
/* Get "clip-to-self" expert setting (false is normal) */
value=GetImageOption(mogrify_info,"compose:clip-to-self");
if (value == (const char *) NULL)
clip_to_self=MagickTrue;
else
clip_to_self=IsStringTrue(GetImageOption(mogrify_info,
"compose:clip-to-self")); /* if this is true */
value=GetImageOption(mogrify_info,"compose:outside-overlay");
if (value != (const char *) NULL) { /* or this false */
/* FUTURE: depreciate warning for "compose:outside-overlay"*/
clip_to_self=IsStringFalse(value);
}
new_images=RemoveFirstImageFromList(images);
source_image=RemoveFirstImageFromList(images);
if (source_image == (Image *) NULL)
break; /* FUTURE - produce Exception, rather than silent fail */
/* FUTURE: this should not be here! - should be part of -geometry */
if (source_image->geometry != (char *) NULL)
{
RectangleInfo
resize_geometry;
(void) ParseRegionGeometry(source_image,source_image->geometry,
&resize_geometry,exception);
if ((source_image->columns != resize_geometry.width) ||
(source_image->rows != resize_geometry.height))
{
Image
*resize_image;
resize_image=ResizeImage(source_image,resize_geometry.width,
resize_geometry.height,source_image->filter,exception);
if (resize_image != (Image *) NULL)
{
source_image=DestroyImage(source_image);
source_image=resize_image;
}
}
}
SetGeometry(source_image,&geometry);
(void) ParseAbsoluteGeometry(source_image->geometry,&geometry);
GravityAdjustGeometry(new_images->columns,new_images->rows,
new_images->gravity,&geometry);
mask_image=RemoveFirstImageFromList(images);
if (mask_image == (Image *) NULL)
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
else
{
if ((compose == DisplaceCompositeOp) ||
(compose == DistortCompositeOp))
{
status&=CompositeImage(source_image,mask_image,
CopyGreenCompositeOp,MagickTrue,0,0,exception);
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
}
else
{
Image
*clone_image;
clone_image=CloneImage(new_images,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
break;
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
status&=CompositeImage(new_images,mask_image,
CopyAlphaCompositeOp,MagickTrue,0,0,exception);
status&=CompositeImage(clone_image,new_images,
OverCompositeOp,clip_to_self,0,0,exception);
new_images=DestroyImage(new_images);
new_images=clone_image;
}
mask_image=DestroyImage(mask_image);
}
source_image=DestroyImage(source_image);
*images=DestroyImageList(*images);
*images=new_images;
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
(void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=(*images);
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,argv[i+1],&geometry,
exception);
status=CopyImagePixels(*images,source_image,&geometry,&offset,
exception);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
Image
*deconstruct_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer,
exception);
if (deconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=deconstruct_image;
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (*option == '+')
DeleteImages(images,"-1",exception);
else
DeleteImages(images,argv[i+1],exception);
break;
}
if (LocaleCompare("dither",option+1) == 0)
{
if (*option == '+')
{
quantize_info->dither_method=NoDitherMethod;
break;
}
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,argv[i+1]);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
Image
*duplicate_images;
if (*option == '+')
duplicate_images=DuplicateImages(*images,1,"-1",exception);
else
{
const char
*p;
size_t
number_duplicates;
number_duplicates=(size_t) StringToLong(argv[i+1]);
p=strchr(argv[i+1],',');
if (p == (const char *) NULL)
duplicate_images=DuplicateImages(*images,number_duplicates,
"-1",exception);
else
duplicate_images=DuplicateImages(*images,number_duplicates,p,
exception);
}
AppendImageToList(images, duplicate_images);
(void) SyncImagesSettings(mogrify_info,*images,exception);
break;
}
break;
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
Image
*evaluate_image;
MagickEvaluateOperator
op;
(void) SyncImageSettings(mogrify_info,*images,exception);
op=(MagickEvaluateOperator) ParseCommandOption(
MagickEvaluateOptions,MagickFalse,argv[i+1]);
evaluate_image=EvaluateImages(*images,op,exception);
if (evaluate_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=evaluate_image;
break;
}
break;
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
Image
*fourier_image;
/*
Implements the discrete Fourier transform (DFT).
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?
MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
*images=DestroyImage(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
Image
*flatten_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
flatten_image=MergeImageLayers(*images,FlattenLayer,exception);
if (flatten_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=flatten_image;
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
Image
*fx_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
fx_image=FxImage(*images,argv[i+1],exception);
if (fx_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=fx_image;
break;
}
break;
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
Image
*hald_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
hald_image=RemoveFirstImageFromList(images);
if (hald_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) HaldClutImage(image,hald_image,exception);
hald_image=DestroyImage(hald_image);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=image;
break;
}
break;
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*fourier_image,
*magnitude_image,
*phase_image;
/*
Implements the inverse fourier discrete Fourier transform (DFT).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
magnitude_image=RemoveFirstImageFromList(images);
phase_image=RemoveFirstImageFromList(images);
if (phase_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
fourier_image=InverseFourierTransformImage(magnitude_image,
phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImage(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*p,
*q;
index=0;
if (*option != '+')
index=(ssize_t) StringToLong(argv[i+1]);
p=RemoveLastImageFromList(images);
if (p == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
q=p;
if (index == 0)
PrependImageToList(images,q);
else
if (index == (ssize_t) GetImageListLength(*images))
AppendImageToList(images,q);
else
{
q=GetImageFromList(*images,index-1);
if (q == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
InsertImageInList(&q,p);
}
*images=GetFirstImageInList(q);
break;
}
if (LocaleCompare("interpolate",option+1) == 0)
{
interpolate_method=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,argv[i+1]);
break;
}
break;
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
Image
*layers;
LayerMethod
method;
(void) SyncImagesSettings(mogrify_info,*images,exception);
layers=(Image *) NULL;
method=(LayerMethod) ParseCommandOption(MagickLayerOptions,
MagickFalse,argv[i+1]);
switch (method)
{
case CoalesceLayer:
{
layers=CoalesceImages(*images,exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
layers=CompareImagesLayers(*images,method,exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
layers=MergeImageLayers(*images,method,exception);
break;
}
case DisposeLayer:
{
layers=DisposeImages(*images,exception);
break;
}
case OptimizeImageLayer:
{
layers=OptimizeImageLayers(*images,exception);
break;
}
case OptimizePlusLayer:
{
layers=OptimizePlusImageLayers(*images,exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(*images,exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(images,exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(images,exception);
break;
}
case OptimizeLayer:
{
/*
General Purpose, GIF Animation Optimizer.
*/
layers=CoalesceImages(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=layers;
layers=OptimizeImageLayers(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=layers;
layers=(Image *) NULL;
OptimizeImageTransparency(*images,exception);
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
case CompositeLayer:
{
CompositeOperator
compose;
Image
*source;
RectangleInfo
geometry;
/*
Split image sequence at the first 'NULL:' image.
*/
source=(*images);
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{
/*
Separate the two lists, junk the null: image.
*/
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
status=MagickFalse;
break;
}
/*
Adjust offset with gravity and virtual canvas.
*/
SetGeometry(*images,&geometry);
(void) ParseAbsoluteGeometry((*images)->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry((*images)->page.width != 0 ?
(*images)->page.width : (*images)->columns,
(*images)->page.height != 0 ? (*images)->page.height :
(*images)->rows,(*images)->gravity,&geometry);
compose=OverCompositeOp;
option=GetImageOption(mogrify_info,"compose");
if (option != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,option);
CompositeLayers(*images,compose,source,geometry.x,geometry.y,
exception);
source=DestroyImageList(source);
break;
}
}
if (layers == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=layers;
break;
}
break;
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images,exception);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
i++;
break;
}
if (LocaleCompare("maximum",option+1) == 0)
{
Image
*maximum_image;
/*
Maximum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);
if (maximum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=maximum_image;
break;
}
if (LocaleCompare("minimum",option+1) == 0)
{
Image
*minimum_image;
/*
Minimum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);
if (minimum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=minimum_image;
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),
exception);
if (morph_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
Image
*mosaic_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);
if (mosaic_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=mosaic_image;
break;
}
break;
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
char
*args,
token[MagickPathExtent];
const char
*p;
double
*arguments;
Image
*polynomial_image;
register ssize_t
x;
size_t
number_arguments;
/*
Polynomial image.
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
args=InterpretImageProperties(mogrify_info,*images,argv[i+1],
exception);
if (args == (char *) NULL)
break;
p=(char *) args;
for (x=0; *p != '\0'; x++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
}
number_arguments=(size_t) x;
arguments=(double *) AcquireQuantumMemory(number_arguments,
sizeof(*arguments));
if (arguments == (double *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,
"MemoryAllocationFailed",(*images)->filename);
(void) ResetMagickMemory(arguments,0,number_arguments*
sizeof(*arguments));
p=(char *) args;
for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arguments[x]=StringToDouble(token,(char **) NULL);
}
args=DestroyString(args);
polynomial_image=PolynomialImage(*images,number_arguments >> 1,
arguments,exception);
arguments=(double *) RelinquishMagickMemory(arguments);
if (polynomial_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=polynomial_image;
}
if (LocaleCompare("print",option+1) == 0)
{
char
*string;
(void) SyncImagesSettings(mogrify_info,*images,exception);
string=InterpretImageProperties(mogrify_info,*images,argv[i+1],
exception);
if (string == (char *) NULL)
break;
(void) FormatLocaleFile(stdout,"%s",string);
string=DestroyString(string);
}
if (LocaleCompare("process",option+1) == 0)
{
char
**arguments;
int
j,
number_arguments;
(void) SyncImagesSettings(mogrify_info,*images,exception);
arguments=StringToArgv(argv[i+1],&number_arguments);
if (arguments == (char **) NULL)
break;
if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))
{
char
breaker,
quote,
*token;
const char
*argument;
int
next,
token_status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg".
*/
length=strlen(argv[i+1]);
token=(char *) NULL;
if (~length >= (MagickPathExtent-1))
token=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
argument=argv[i+1];
token_info=AcquireTokenInfo();
token_status=Tokenizer(token_info,0,token,length,argument,"",
"=","\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (token_status == 0)
{
const char
*arg;
arg=(&(argument[next]));
(void) InvokeDynamicImageFilter(token,&(*images),1,&arg,
exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&(*images),
number_arguments-2,(const char **) arguments+2,exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
break;
}
case 'r':
{
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(images);
break;
}
break;
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
Image
*smush_image;
ssize_t
offset;
(void) SyncImagesSettings(mogrify_info,*images,exception);
offset=(ssize_t) StringToLong(argv[i+1]);
smush_image=SmushImages(*images,*option == '-' ? MagickTrue :
MagickFalse,offset,exception);
if (smush_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=smush_image;
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*swap;
ssize_t
swap_index;
index=(-1);
swap_index=(-2);
if (*option != '+')
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(argv[i+1],&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(*images,index);
q=GetImageFromList(*images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",(*images)->filename);
status=MagickFalse;
break;
}
if (p == q)
break;
swap=CloneImage(p,0,0,MagickTrue,exception);
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,exception));
ReplaceImageInList(&q,swap);
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("write",option+1) == 0)
{
char
key[MagickPathExtent];
Image
*write_images;
ImageInfo
*write_info;
(void) SyncImagesSettings(mogrify_info,*images,exception);
(void) FormatLocaleString(key,MagickPathExtent,"cache:%s",
argv[i+1]);
(void) DeleteImageRegistry(key);
write_images=(*images);
if (*option == '+')
write_images=CloneImageList(*images,exception);
write_info=CloneImageInfo(mogrify_info);
status&=WriteImages(write_info,write_images,argv[i+1],exception);
write_info=DestroyImageInfo(write_info);
if (*option == '+')
write_images=DestroyImageList(write_images);
break;
}
break;
}
default:
break;
}
i+=count;
}
quantize_info=DestroyQuantizeInfo(quantize_info);
mogrify_info=DestroyImageInfo(mogrify_info);
status&=MogrifyImageInfo(image_info,argc,argv,exception);
return(status != 0 ? MagickTrue : MagickFalse);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/802'</s> |
<s>[INST] Given the following code containing errors, provide 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 WriteGIFImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
int
c;
ImageInfo
*write_info;
MagickBooleanType
status;
MagickOffsetType
scene;
RectangleInfo
page;
register ssize_t
i;
register unsigned char
*q;
size_t
bits_per_pixel,
delay,
length,
one;
ssize_t
j,
opacity;
unsigned char
*colormap,
*global_colormap;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Allocate colormap.
*/
global_colormap=(unsigned char *) AcquireQuantumMemory(768UL,
sizeof(*global_colormap));
colormap=(unsigned char *) AcquireQuantumMemory(768UL,sizeof(*colormap));
if ((global_colormap == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < 768; i++)
colormap[i]=(unsigned char) 0;
/*
Write GIF header.
*/
write_info=CloneImageInfo(image_info);
if (LocaleCompare(write_info->magick,"GIF87") != 0)
(void) WriteBlob(image,6,(unsigned char *) "GIF89a");
else
{
(void) WriteBlob(image,6,(unsigned char *) "GIF87a");
write_info->adjoin=MagickFalse;
}
/*
Determine image bounding box.
*/
page.width=image->columns;
if (image->page.width > page.width)
page.width=image->page.width;
page.height=image->rows;
if (image->page.height > page.height)
page.height=image->page.height;
page.x=image->page.x;
page.y=image->page.y;
(void) WriteBlobLSBShort(image,(unsigned short) page.width);
(void) WriteBlobLSBShort(image,(unsigned short) page.height);
/*
Write images to file.
*/
if ((write_info->adjoin != MagickFalse) &&
(GetNextImageInList(image) != (Image *) NULL))
write_info->interlace=NoInterlace;
scene=0;
one=1;
do
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
opacity=(-1);
if (IsImageOpaque(image,exception) != MagickFalse)
{
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) SetImageType(image,PaletteType,exception);
}
else
{
double
alpha,
beta;
/*
Identify transparent colormap index.
*/
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) SetImageType(image,PaletteBilevelAlphaType,exception);
for (i=0; i < (ssize_t) image->colors; i++)
if (image->colormap[i].alpha != OpaqueAlpha)
{
if (opacity < 0)
{
opacity=i;
continue;
}
alpha=fabs(image->colormap[i].alpha-TransparentAlpha);
beta=fabs(image->colormap[opacity].alpha-TransparentAlpha);
if (alpha < beta)
opacity=i;
}
if (opacity == -1)
{
(void) SetImageType(image,PaletteBilevelAlphaType,exception);
for (i=0; i < (ssize_t) image->colors; i++)
if (image->colormap[i].alpha != OpaqueAlpha)
{
if (opacity < 0)
{
opacity=i;
continue;
}
alpha=fabs(image->colormap[i].alpha-TransparentAlpha);
beta=fabs(image->colormap[opacity].alpha-TransparentAlpha);
if (alpha < beta)
opacity=i;
}
}
if (opacity >= 0)
{
image->colormap[opacity].red=image->transparent_color.red;
image->colormap[opacity].green=image->transparent_color.green;
image->colormap[opacity].blue=image->transparent_color.blue;
}
}
if ((image->storage_class == DirectClass) || (image->colors > 256))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (bits_per_pixel=1; bits_per_pixel < 8; bits_per_pixel++)
if ((one << bits_per_pixel) >= image->colors)
break;
q=colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
}
for ( ; i < (ssize_t) (one << bits_per_pixel); i++)
{
*q++=(unsigned char) 0x0;
*q++=(unsigned char) 0x0;
*q++=(unsigned char) 0x0;
}
if ((GetPreviousImageInList(image) == (Image *) NULL) ||
(write_info->adjoin == MagickFalse))
{
/*
Write global colormap.
*/
c=0x80;
c|=(8-1) << 4; /* color resolution */
c|=(bits_per_pixel-1); /* size of global colormap */
(void) WriteBlobByte(image,(unsigned char) c);
for (j=0; j < (ssize_t) image->colors; j++)
if (IsPixelInfoEquivalent(&image->background_color,image->colormap+j))
break;
(void) WriteBlobByte(image,(unsigned char)
(j == (ssize_t) image->colors ? 0 : j)); /* background color */
(void) WriteBlobByte(image,(unsigned char) 0x00); /* reserved */
length=(size_t) (3*(one << bits_per_pixel));
(void) WriteBlob(image,length,colormap);
for (j=0; j < 768; j++)
global_colormap[j]=colormap[j];
}
if (LocaleCompare(write_info->magick,"GIF87") != 0)
{
const char
*value;
/*
Write graphics control extension.
*/
(void) WriteBlobByte(image,(unsigned char) 0x21);
(void) WriteBlobByte(image,(unsigned char) 0xf9);
(void) WriteBlobByte(image,(unsigned char) 0x04);
c=image->dispose << 2;
if (opacity >= 0)
c|=0x01;
(void) WriteBlobByte(image,(unsigned char) c);
delay=(size_t) (100*image->delay/MagickMax((size_t)
image->ticks_per_second,1));
(void) WriteBlobLSBShort(image,(unsigned short) delay);
(void) WriteBlobByte(image,(unsigned char) (opacity >= 0 ? opacity :
0));
(void) WriteBlobByte(image,(unsigned char) 0x00);
value=GetImageProperty(image,"comment",exception);
if ((LocaleCompare(write_info->magick,"GIF87") != 0) &&
(value != (const char *) NULL))
{
register const char
*p;
size_t
count;
/*
Write comment extension.
*/
(void) WriteBlobByte(image,(unsigned char) 0x21);
(void) WriteBlobByte(image,(unsigned char) 0xfe);
for (p=value; *p != '\0'; )
{
count=MagickMin(strlen(p),255);
(void) WriteBlobByte(image,(unsigned char) count);
for (i=0; i < (ssize_t) count; i++)
(void) WriteBlobByte(image,(unsigned char) *p++);
}
(void) WriteBlobByte(image,(unsigned char) 0x00);
}
if ((GetPreviousImageInList(image) == (Image *) NULL) &&
(GetNextImageInList(image) != (Image *) NULL) &&
(image->iterations != 1))
{
/*
Write Netscape Loop extension.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GIF Extension %s","NETSCAPE2.0");
(void) WriteBlobByte(image,(unsigned char) 0x21);
(void) WriteBlobByte(image,(unsigned char) 0xff);
(void) WriteBlobByte(image,(unsigned char) 0x0b);
(void) WriteBlob(image,11,(unsigned char *) "NETSCAPE2.0");
(void) WriteBlobByte(image,(unsigned char) 0x03);
(void) WriteBlobByte(image,(unsigned char) 0x01);
(void) WriteBlobLSBShort(image,(unsigned short) (image->iterations ?
image->iterations-1 : 0));
(void) WriteBlobByte(image,(unsigned char) 0x00);
}
if ((image->gamma != 1.0f/2.2f))
{
char
attributes[MagickPathExtent];
ssize_t
count;
/*
Write ImageMagick extension.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GIF Extension %s","ImageMagick");
(void) WriteBlobByte(image,(unsigned char) 0x21);
(void) WriteBlobByte(image,(unsigned char) 0xff);
(void) WriteBlobByte(image,(unsigned char) 0x0b);
(void) WriteBlob(image,11,(unsigned char *) "ImageMagick");
count=FormatLocaleString(attributes,MagickPathExtent,"gamma=%g",
image->gamma);
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlob(image,(size_t) count,(unsigned char *) attributes);
(void) WriteBlobByte(image,(unsigned char) 0x00);
}
ResetImageProfileIterator(image);
for ( ; ; )
{
char
*name;
const StringInfo
*profile;
name=GetNextImageProfile(image);
if (name == (const char *) NULL)
break;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0) ||
(LocaleCompare(name,"IPTC") == 0) ||
(LocaleCompare(name,"8BIM") == 0) ||
(LocaleNCompare(name,"gif:",4) == 0))
{
ssize_t
offset;
unsigned char
*datum;
datum=GetStringInfoDatum(profile);
length=GetStringInfoLength(profile);
(void) WriteBlobByte(image,(unsigned char) 0x21);
(void) WriteBlobByte(image,(unsigned char) 0xff);
(void) WriteBlobByte(image,(unsigned char) 0x0b);
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
/*
Write ICC extension.
*/
(void) WriteBlob(image,11,(unsigned char *) "ICCRGBG1012");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GIF Extension %s","ICCRGBG1012");
}
else
if ((LocaleCompare(name,"IPTC") == 0))
{
/*
Write IPTC extension.
*/
(void) WriteBlob(image,11,(unsigned char *) "MGKIPTC0000");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GIF Extension %s","MGKIPTC0000");
}
else
if ((LocaleCompare(name,"8BIM") == 0))
{
/*
Write 8BIM extension.
*/
(void) WriteBlob(image,11,(unsigned char *)
"MGK8BIM0000");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GIF Extension %s","MGK8BIM0000");
}
else
{
char
extension[MagickPathExtent];
/*
Write generic extension.
*/
(void) CopyMagickString(extension,name+4,
sizeof(extension));
(void) WriteBlob(image,11,(unsigned char *) extension);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GIF Extension %s",name);
}
offset=0;
while ((ssize_t) length > offset)
{
size_t
block_length;
if ((length-offset) < 255)
block_length=length-offset;
else
block_length=255;
(void) WriteBlobByte(image,(unsigned char) block_length);
(void) WriteBlob(image,(size_t) block_length,datum+offset);
offset+=(ssize_t) block_length;
}
(void) WriteBlobByte(image,(unsigned char) 0x00);
}
}
}
}
(void) WriteBlobByte(image,','); /* image separator */
/*
Write the image header.
*/
page.x=image->page.x;
page.y=image->page.y;
if ((image->page.width != 0) && (image->page.height != 0))
page=image->page;
(void) WriteBlobLSBShort(image,(unsigned short) (page.x < 0 ? 0 : page.x));
(void) WriteBlobLSBShort(image,(unsigned short) (page.y < 0 ? 0 : page.y));
(void) WriteBlobLSBShort(image,(unsigned short) image->columns);
(void) WriteBlobLSBShort(image,(unsigned short) image->rows);
c=0x00;
if (write_info->interlace != NoInterlace)
c|=0x40; /* pixel data is interlaced */
for (j=0; j < (ssize_t) (3*image->colors); j++)
if (colormap[j] != global_colormap[j])
break;
if (j == (ssize_t) (3*image->colors))
(void) WriteBlobByte(image,(unsigned char) c);
else
{
c|=0x80;
c|=(bits_per_pixel-1); /* size of local colormap */
(void) WriteBlobByte(image,(unsigned char) c);
length=(size_t) (3*(one << bits_per_pixel));
(void) WriteBlob(image,length,colormap);
}
/*
Write the image data.
*/
c=(int) MagickMax(bits_per_pixel,2);
(void) WriteBlobByte(image,(unsigned char) c);
status=EncodeImage(write_info,image,(size_t) MagickMax(bits_per_pixel,2)+1,
exception);
if (status == MagickFalse)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
write_info=DestroyImageInfo(write_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) WriteBlobByte(image,(unsigned char) 0x00);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
scene++;
status=SetImageProgress(image,SaveImagesTag,scene,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (write_info->adjoin != MagickFalse);
(void) WriteBlobByte(image,';'); /* terminator */
global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
write_info=DestroyImageInfo(write_info);
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/808'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rsock_init_unixsock(VALUE sock, VALUE path, int server)
{
struct sockaddr_un sockaddr;
socklen_t sockaddrlen;
int fd, status;
rb_io_t *fptr;
FilePathValue(path);
INIT_SOCKADDR_UN(&sockaddr, sizeof(struct sockaddr_un));
if (sizeof(sockaddr.sun_path) < (size_t)RSTRING_LEN(path)) {
rb_raise(rb_eArgError, "too long unix socket path (%ldbytes given but %dbytes max)",
RSTRING_LEN(path), (int)sizeof(sockaddr.sun_path));
}
memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
sockaddrlen = rsock_unix_sockaddr_len(path);
fd = rsock_socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
rsock_sys_fail_path("socket(2)", path);
}
if (server) {
status = bind(fd, (struct sockaddr*)&sockaddr, sockaddrlen);
}
else {
int prot;
struct unixsock_arg arg;
arg.sockaddr = &sockaddr;
arg.sockaddrlen = sockaddrlen;
arg.fd = fd;
status = (int)rb_protect(unixsock_connect_internal, (VALUE)&arg, &prot);
if (prot) {
close(fd);
rb_jump_tag(prot);
}
}
if (status < 0) {
int e = errno;
close(fd);
rsock_syserr_fail_path(e, "connect(2)", path);
}
if (server) {
if (listen(fd, SOMAXCONN) < 0) {
int e = errno;
close(fd);
rsock_syserr_fail_path(e, "listen(2)", path);
}
}
rsock_init_sock(sock, fd);
if (server) {
GetOpenFile(sock, fptr);
fptr->pathv = rb_str_new_frozen(path);
}
return sock;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'unixsocket.c: abstract namespace
* ext/socket/unixsocket.c (unixsock_path_value): fix r62991 for
Linux abstract namespace.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@63000 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rb_dir_s_empty_p(VALUE obj, VALUE dirname)
{
VALUE result, orig;
const char *path;
enum {false_on_notdir = 1};
GlobPathValue(dirname, FALSE);
orig = rb_str_dup_frozen(dirname);
dirname = rb_str_encode_ospath(dirname);
dirname = rb_str_dup_frozen(dirname);
path = RSTRING_PTR(dirname);
#if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT
{
u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) != 0)
rb_sys_fail_path(orig);
if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) {
al.commonattr = 0;
al.dirattr = ATTR_DIR_ENTRYCOUNT;
if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) == 0) {
if (attrbuf[0] >= 2 * sizeof(u_int32_t))
return attrbuf[1] ? Qfalse : Qtrue;
if (false_on_notdir) return Qfalse;
}
rb_sys_fail_path(orig);
}
}
#endif
result = (VALUE)rb_thread_call_without_gvl(nogvl_dir_empty_p, (void *)path,
RUBY_UBF_IO, 0);
if (result == Qundef) {
rb_sys_fail_path(orig);
}
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes
* dir.c (GlobPathValue): should be used in rb_push_glob only.
other methods should use FilePathValue.
https://hackerone.com/reports/302338
* dir.c (rb_push_glob): expand GlobPathValue
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dir_initialize(int argc, VALUE *argv, VALUE dir)
{
struct dir_data *dp;
rb_encoding *fsenc;
VALUE dirname, opt, orig;
static ID keyword_ids[1];
const char *path;
if (!keyword_ids[0]) {
keyword_ids[0] = rb_id_encoding();
}
fsenc = rb_filesystem_encoding();
rb_scan_args(argc, argv, "1:", &dirname, &opt);
if (!NIL_P(opt)) {
VALUE enc;
rb_get_kwargs(opt, keyword_ids, 0, 1, &enc);
if (enc != Qundef && !NIL_P(enc)) {
fsenc = rb_to_encoding(enc);
}
}
GlobPathValue(dirname, FALSE);
orig = rb_str_dup_frozen(dirname);
dirname = rb_str_encode_ospath(dirname);
dirname = rb_str_dup_frozen(dirname);
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dp);
if (dp->dir) closedir(dp->dir);
dp->dir = NULL;
RB_OBJ_WRITE(dir, &dp->path, Qnil);
dp->enc = fsenc;
path = RSTRING_PTR(dirname);
dp->dir = opendir_without_gvl(path);
if (dp->dir == NULL) {
int e = errno;
if (rb_gc_for_fd(e)) {
dp->dir = opendir_without_gvl(path);
}
#ifdef HAVE_GETATTRLIST
else if (e == EIO) {
u_int32_t attrbuf[1];
struct attrlist al = {ATTR_BIT_MAP_COUNT, 0};
if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW) == 0) {
dp->dir = opendir_without_gvl(path);
}
}
#endif
if (dp->dir == NULL) {
RB_GC_GUARD(dirname);
rb_syserr_fail_path(e, orig);
}
}
RB_OBJ_WRITE(dir, &dp->path, orig);
return dir;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes
* dir.c (GlobPathValue): should be used in rb_push_glob only.
other methods should use FilePathValue.
https://hackerone.com/reports/302338
* dir.c (rb_push_glob): expand GlobPathValue
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dir_glob_options(VALUE opt, VALUE *base, int *flags)
{
ID kw[2];
VALUE args[2];
kw[0] = rb_intern("base");
if (flags) kw[1] = rb_intern("flags");
rb_get_kwargs(opt, kw, 0, flags ? 2 : 1, args);
if (args[0] == Qundef || NIL_P(args[0])) {
*base = Qnil;
}
#if USE_OPENDIR_AT
else if (rb_typeddata_is_kind_of(args[0], &dir_data_type)) {
*base = args[0];
}
#endif
else {
GlobPathValue(args[0], TRUE);
if (!RSTRING_LEN(args[0])) args[0] = Qnil;
*base = args[0];
}
if (flags && args[1] != Qundef) {
*flags = NUM2INT(args[1]);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes
* dir.c (GlobPathValue): should be used in rb_push_glob only.
other methods should use FilePathValue.
https://hackerone.com/reports/302338
* dir.c (rb_push_glob): expand GlobPathValue
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rb_push_glob(VALUE str, int flags) /* '\0' is delimiter */
{
long offset = 0;
VALUE ary;
GlobPathValue(str, TRUE);
ary = rb_ary_new();
while (offset < RSTRING_LEN(str)) {
char *p, *pend;
int status;
p = RSTRING_PTR(str) + offset;
status = push_glob(ary, rb_enc_str_new(p, strlen(p), rb_enc_get(str)),
flags);
if (status) GLOB_JUMP_TAG(status);
if (offset >= RSTRING_LEN(str)) break;
p += strlen(p) + 1;
pend = RSTRING_PTR(str) + RSTRING_LEN(str);
while (p < pend && !*p)
p++;
offset = p - RSTRING_PTR(str);
}
return ary;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'merge revision(s) 62989:
dir.c: check NUL bytes
* dir.c (GlobPathValue): should be used in rb_push_glob only.
other methods should use FilePathValue.
https://hackerone.com/reports/302338
* dir.c (rb_push_glob): expand GlobPathValue
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_2_2@63015 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s> |
<s>[INST] Given the following code containing errors, provide 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 perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (ret || !write)
return ret;
if (sysctl_perf_cpu_time_max_percent == 100 ||
sysctl_perf_cpu_time_max_percent == 0) {
printk(KERN_WARNING
"perf: Dynamic interrupt throttling disabled, can hang your system!\n");
WRITE_ONCE(perf_sample_allowed_ns, 0);
} else {
update_perf_cpu_limits();
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'perf/core: Fix the perf_cpu_time_max_percent check
Use "proc_dointvec_minmax" instead of "proc_dointvec" to check the input
value from user-space.
If not, we can set a big value and some vars will overflow like
"sysctl_perf_event_sample_rate" which will cause a lot of unexpected
problems.
Signed-off-by: Tan Xiaojun <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: <[email protected]>
Cc: <[email protected]>
Cc: Alexander Shishkin <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[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 snd_pcm_control_ioctl(struct snd_card *card,
struct snd_ctl_file *control,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SNDRV_CTL_IOCTL_PCM_NEXT_DEVICE:
{
int device;
if (get_user(device, (int __user *)arg))
return -EFAULT;
mutex_lock(®ister_mutex);
device = snd_pcm_next(card, device);
mutex_unlock(®ister_mutex);
if (put_user(device, (int __user *)arg))
return -EFAULT;
return 0;
}
case SNDRV_CTL_IOCTL_PCM_INFO:
{
struct snd_pcm_info __user *info;
unsigned int device, subdevice;
int stream;
struct snd_pcm *pcm;
struct snd_pcm_str *pstr;
struct snd_pcm_substream *substream;
int err;
info = (struct snd_pcm_info __user *)arg;
if (get_user(device, &info->device))
return -EFAULT;
if (get_user(stream, &info->stream))
return -EFAULT;
if (stream < 0 || stream > 1)
return -EINVAL;
if (get_user(subdevice, &info->subdevice))
return -EFAULT;
mutex_lock(®ister_mutex);
pcm = snd_pcm_get(card, device);
if (pcm == NULL) {
err = -ENXIO;
goto _error;
}
pstr = &pcm->streams[stream];
if (pstr->substream_count == 0) {
err = -ENOENT;
goto _error;
}
if (subdevice >= pstr->substream_count) {
err = -ENXIO;
goto _error;
}
for (substream = pstr->substream; substream;
substream = substream->next)
if (substream->number == (int)subdevice)
break;
if (substream == NULL) {
err = -ENXIO;
goto _error;
}
err = snd_pcm_info_user(substream, info);
_error:
mutex_unlock(®ister_mutex);
return err;
}
case SNDRV_CTL_IOCTL_PCM_PREFER_SUBDEVICE:
{
int val;
if (get_user(val, (int __user *)arg))
return -EFAULT;
control->preferred_subdevice[SND_CTL_SUBDEV_PCM] = val;
return 0;
}
}
return -ENOIOCTLCMD;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: pcm: prevent UAF in snd_pcm_info
When the device descriptor is closed, the `substream->runtime` pointer
is freed. But another thread may be in the ioctl handler, case
SNDRV_CTL_IOCTL_PCM_INFO. This case calls snd_pcm_info_user() which
calls snd_pcm_info() which accesses the now freed `substream->runtime`.
Note: this fixes CVE-2017-0861
Signed-off-by: Robb Glasser <[email protected]>
Signed-off-by: Nick Desaulniers <[email protected]>
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: do_ed_script (char const *inname, char const *outname,
bool *outname_needs_removal, FILE *ofp)
{
static char const editor_program[] = EDITOR_PROGRAM;
file_offset beginning_of_this_line;
FILE *pipefp = 0;
size_t chars_read;
if (! dry_run && ! skip_rest_of_patch) {
int exclusive = *outname_needs_removal ? 0 : O_EXCL;
if (inerrno != ENOENT)
{
*outname_needs_removal = true;
copy_file (inname, outname, 0, exclusive, instat.st_mode, true);
}
sprintf (buf, "%s %s%s", editor_program,
verbosity == VERBOSE ? "" : "- ",
outname);
fflush (stdout);
pipefp = popen(buf, binary_transput ? "wb" : "w");
if (!pipefp)
pfatal ("Can't open pipe to %s", quotearg (buf));
}
for (;;) {
char ed_command_letter;
beginning_of_this_line = file_tell (pfp);
chars_read = get_line ();
if (! chars_read) {
next_intuit_at(beginning_of_this_line,p_input_line);
break;
}
ed_command_letter = get_ed_command_letter (buf);
if (ed_command_letter) {
if (pipefp)
if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
write_fatal ();
if (ed_command_letter != 'd' && ed_command_letter != 's') {
p_pass_comments_through = true;
while ((chars_read = get_line ()) != 0) {
if (pipefp)
if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
write_fatal ();
if (chars_read == 2 && strEQ (buf, ".\n"))
break;
}
p_pass_comments_through = false;
}
}
else {
next_intuit_at(beginning_of_this_line,p_input_line);
break;
}
}
if (!pipefp)
return;
if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, pipefp) == 0
|| fflush (pipefp) != 0)
write_fatal ();
if (pclose (pipefp) != 0)
fatal ("%s FAILED", editor_program);
if (ofp)
{
FILE *ifp = fopen (outname, binary_transput ? "rb" : "r");
int c;
if (!ifp)
pfatal ("can't open '%s'", outname);
while ((c = getc (ifp)) != EOF)
if (putc (c, ofp) == EOF)
write_fatal ();
if (ferror (ifp) || fclose (ifp) != 0)
read_fatal ();
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix arbitrary command execution in ed-style patches (CVE-2018-1000156)
* src/pch.c (do_ed_script): Write ed script to a temporary file instead
of piping it to ed: this will cause ed to abort on invalid commands
instead of rejecting them and carrying on.
* tests/ed-style: New test case.
* tests/Makefile.am (TESTS): Add test case.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_enc_encodemainhdr(jpc_enc_t *enc)
{
jpc_siz_t *siz;
jpc_cod_t *cod;
jpc_qcd_t *qcd;
int i;
long startoff;
long mainhdrlen;
jpc_enc_cp_t *cp;
jpc_qcc_t *qcc;
jpc_enc_tccp_t *tccp;
uint_fast16_t cmptno;
jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
jpc_fix_t mctsynweight;
jpc_enc_tcp_t *tcp;
jpc_tsfb_t *tsfb;
jpc_tsfb_band_t *bandinfo;
uint_fast16_t numbands;
uint_fast16_t bandno;
uint_fast16_t rlvlno;
uint_fast16_t analgain;
jpc_fix_t absstepsize;
char buf[1024];
jpc_com_t *com;
cp = enc->cp;
startoff = jas_stream_getrwcount(enc->out);
/* Write SOC marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
jas_eprintf("cannot create SOC marker\n");
return -1;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SOC marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
/* Write SIZ marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
jas_eprintf("cannot create SIZ marker\n");
return -1;
}
siz = &enc->mrk->parms.siz;
siz->caps = 0;
siz->xoff = cp->imgareatlx;
siz->yoff = cp->imgareatly;
siz->width = cp->refgrdwidth;
siz->height = cp->refgrdheight;
siz->tilexoff = cp->tilegrdoffx;
siz->tileyoff = cp->tilegrdoffy;
siz->tilewidth = cp->tilewidth;
siz->tileheight = cp->tileheight;
siz->numcomps = cp->numcmpts;
siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
assert(siz->comps);
for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
siz->comps[i].prec = cp->ccps[i].prec;
siz->comps[i].sgnd = cp->ccps[i].sgnd;
siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SIZ marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
jas_eprintf("cannot create COM marker\n");
return -1;
}
sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
com = &enc->mrk->parms.com;
com->len = JAS_CAST(uint_fast16_t, strlen(buf));
com->regid = JPC_COM_LATIN;
if (!(com->data = JAS_CAST(jas_uchar *, jas_strdup(buf)))) {
abort();
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COM marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#if 0
if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
return -1;
}
crg = &enc->mrk->parms.crg;
crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write CRG marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#endif
tcp = &cp->tcp;
tccp = &cp->tccp;
for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
bandinfos);
jpc_tsfb_destroy(tsfb);
mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
numbands = 3 * tccp->maxrlvls - 2;
for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
++bandno, ++bandinfo) {
rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
rlvlno, bandinfo->orient);
if (!tcp->intmode) {
absstepsize = jpc_fix_div(jpc_inttofix(1 <<
(analgain + 1)), bandinfo->synenergywt);
} else {
absstepsize = jpc_inttofix(1);
}
cp->ccps[cmptno].stepsizes[bandno] =
jpc_abstorelstepsize(absstepsize,
cp->ccps[cmptno].prec + analgain);
}
cp->ccps[cmptno].numstepsizes = numbands;
}
if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
jas_eprintf("cannot create COD marker\n");
return -1;
}
cod = &enc->mrk->parms.cod;
cod->csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
cod->compparms.numrlvls = cp->tccp.maxrlvls;
cod->prg = cp->tcp.prg;
cod->numlyrs = cp->tcp.numlyrs;
cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
cod->compparms.cblksty = cp->tccp.cblksty;
cod->compparms.qmfbid = cp->tccp.qmfbid;
cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
if (tccp->csty & JPC_COX_PRT) {
for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
}
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COD marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
jas_eprintf("cannot create QCD marker\n");
return -1;
}
qcd = &enc->mrk->parms.qcd;
qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
qcd->compparms.numguard = cp->tccp.numgbits;
qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write marker\n");
return -1;
}
/* We do not want the step size array to be freed! */
qcd->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
tccp = &cp->tccp;
for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
jas_eprintf("cannot create QCC marker\n");
return -1;
}
qcc = &enc->mrk->parms.qcc;
qcc->compno = cmptno;
qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
qcc->compparms.numguard = cp->tccp.numgbits;
qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write marker\n");
return -1;
}
/* We do not want the step size array to be freed! */
qcc->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
}
#define MAINTLRLEN 2
mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
enc->len += mainhdrlen;
if (enc->cp->totalsize != UINT_FAST32_MAX) {
uint_fast32_t overhead;
overhead = mainhdrlen + MAINTLRLEN;
enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
(enc->cp->totalsize - overhead) : 0;
} else {
enc->mainbodysize = UINT_FAST32_MAX;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'jpc_enc: jpc_abstorelstepsize() returns error instead of aborting
Fixes CVE-2018-9252
Closes https://github.com/jasper-maint/jasper/issues/16'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_enc_encodemainbody(jpc_enc_t *enc)
{
int tileno;
int tilex;
int tiley;
int i;
jpc_sot_t *sot;
jpc_enc_tcmpt_t *comp;
jpc_enc_tcmpt_t *endcomps;
jpc_enc_band_t *band;
jpc_enc_band_t *endbands;
jpc_enc_rlvl_t *lvl;
int rlvlno;
jpc_qcc_t *qcc;
jpc_cod_t *cod;
int adjust;
int j;
int absbandno;
long numbytes;
long tilehdrlen;
long tilelen;
jpc_enc_tile_t *tile;
jpc_enc_cp_t *cp;
double rho;
int lyrno;
int cmptno;
int samestepsizes;
jpc_enc_ccp_t *ccps;
jpc_enc_tccp_t *tccp;
int bandno;
uint_fast32_t x;
uint_fast32_t y;
int mingbits;
int actualnumbps;
jpc_fix_t mxmag;
jpc_fix_t mag;
int numgbits;
cp = enc->cp;
/* Avoid compile warnings. */
numbytes = 0;
for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {
tilex = tileno % cp->numhtiles;
tiley = tileno / cp->numhtiles;
if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image,
tileno))) {
jas_eprintf("cannot create tile\n");
return -1;
}
tile = enc->curtile;
if (jas_getdbglevel() >= 10) {
jpc_enc_dump(enc);
}
endcomps = &tile->tcmpts[tile->numtcmpts];
for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {
if (!cp->ccps[cmptno].sgnd) {
adjust = 1 << (cp->ccps[cmptno].prec - 1);
for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
*jas_matrix_getref(comp->data, i, j) -= adjust;
}
}
}
}
if (!tile->intmode) {
endcomps = &tile->tcmpts[tile->numtcmpts];
for (comp = tile->tcmpts; comp != endcomps; ++comp) {
jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
}
}
switch (tile->mctid) {
case JPC_MCT_RCT:
assert(jas_image_numcmpts(enc->image) == 3);
jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
tile->tcmpts[2].data);
break;
case JPC_MCT_ICT:
assert(jas_image_numcmpts(enc->image) == 3);
jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
tile->tcmpts[2].data);
break;
default:
break;
}
for (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
comp = &tile->tcmpts[i];
jpc_tsfb_analyze(comp->tsfb, comp->data);
}
endcomps = &tile->tcmpts[tile->numtcmpts];
for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {
mingbits = 0;
absbandno = 0;
/* All bands must have a corresponding quantizer step size,
even if they contain no samples and are never coded. */
/* Some bands may not be hit by the loop below, so we must
initialize all of the step sizes to a sane value. */
memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {
if (!lvl->bands) {
absbandno += rlvlno ? 3 : 1;
continue;
}
endbands = &lvl->bands[lvl->numbands];
for (band = lvl->bands; band != endbands; ++band) {
if (!band->data) {
++absbandno;
continue;
}
actualnumbps = 0;
mxmag = 0;
for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {
for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) {
mag = JAS_ABS(jas_matrix_get(band->data, y, x));
if (mag > mxmag) {
mxmag = mag;
}
}
}
if (tile->intmode) {
actualnumbps = jpc_fix_firstone(mxmag) + 1;
} else {
actualnumbps = jpc_fix_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
}
numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
band->analgain);
#if 0
jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);
#endif
if (numgbits > mingbits) {
mingbits = numgbits;
}
if (!tile->intmode) {
band->absstepsize = jpc_fix_div(jpc_inttofix(1
<< (band->analgain + 1)),
band->synweight);
} else {
band->absstepsize = jpc_inttofix(1);
}
band->stepsize = jpc_abstorelstepsize(
band->absstepsize, cp->ccps[cmptno].prec +
band->analgain);
band->numbps = cp->tccp.numgbits +
JPC_QCX_GETEXPN(band->stepsize) - 1;
if ((!tile->intmode) && band->data) {
jpc_quantize(band->data, band->absstepsize);
}
comp->stepsizes[absbandno] = band->stepsize;
++absbandno;
}
}
assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
if (!tile->intmode) {
jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
} else {
jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
}
#if 0
jas_eprintf("mingbits %d\n", mingbits);
#endif
if (mingbits > cp->tccp.numgbits) {
jas_eprintf("error: too few guard bits (need at least %d)\n",
mingbits);
return -1;
}
}
if (!(enc->tmpstream = jas_stream_memopen(0, 0))) {
jas_eprintf("cannot open tmp file\n");
return -1;
}
/* Write the tile header. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {
return -1;
}
sot = &enc->mrk->parms.sot;
sot->len = 0;
sot->tileno = tileno;
sot->partno = 0;
sot->numparts = 1;
if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SOT marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
/************************************************************************/
/************************************************************************/
/************************************************************************/
tccp = &cp->tccp;
for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) {
comp = &tile->tcmpts[cmptno];
if (comp->numrlvls != tccp->maxrlvls) {
if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
return -1;
}
/* XXX = this is not really correct. we are using comp #0's precint sizes
and other characteristics */
comp = &tile->tcmpts[0];
cod = &enc->mrk->parms.cod;
cod->compparms.csty = 0;
cod->compparms.numdlvls = comp->numrlvls - 1;
cod->prg = tile->prg;
cod->numlyrs = tile->numlyrs;
cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);
cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);
cod->compparms.cblksty = comp->cblksty;
cod->compparms.qmfbid = comp->qmfbid;
cod->mctrans = (tile->mctid != JPC_MCT_NONE);
for (i = 0; i < comp->numrlvls; ++i) {
cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;
cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;
}
if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
}
}
for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int,
cp->numcmpts); ++cmptno, ++comp) {
ccps = &cp->ccps[cmptno];
if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {
samestepsizes = 1;
for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes);
++bandno) {
if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
samestepsizes = 0;
break;
}
}
} else {
samestepsizes = 0;
}
if (!samestepsizes) {
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
return -1;
}
qcc = &enc->mrk->parms.qcc;
qcc->compno = cmptno;
qcc->compparms.numguard = cp->tccp.numgbits;
qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcc->compparms.numstepsizes = comp->numstepsizes;
qcc->compparms.stepsizes = comp->stepsizes;
if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
return -1;
}
qcc->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
}
}
/* Write a SOD marker to indicate the end of the tile header. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
return -1;
}
if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SOD marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
assert(tilehdrlen >= 0);
/************************************************************************/
/************************************************************************/
/************************************************************************/
if (jpc_enc_enccblks(enc)) {
abort();
return -1;
}
cp = enc->cp;
rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /
((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
cp->imgareatly));
tile->rawsize = cp->rawsize * rho;
for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {
tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(
cp->tcp.ilyrrates[lyrno]);
}
#if !defined(__clang__)
// WARNING:
// Some versions of Clang (e.g., 3.7.1 and 3.8.1) appear to generate
// incorrect code for the following line.
tile->lyrsizes[tile->numlyrs - 1] =
(cp->totalsize != UINT_FAST32_MAX) ?
(rho * enc->mainbodysize) : UINT_FAST32_MAX;
#else
if (cp->totalsize != UINT_FAST32_MAX) {
tile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize);
} else {
tile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX;
}
#endif
//jas_eprintf("TESTING %ld %ld\n", cp->totalsize != UINT_FAST32_MAX, tile->lyrsizes[0]);
for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {
if (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) {
tile->lyrsizes[lyrno] -= tilehdrlen;
} else {
tile->lyrsizes[lyrno] = 0;
}
}
}
if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {
return -1;
}
#if 0
jas_eprintf("ENCODE TILE DATA\n");
#endif
if (jpc_enc_encodetiledata(enc)) {
jas_eprintf("dotile failed\n");
return -1;
}
/************************************************************************/
/************************************************************************/
/************************************************************************/
/************************************************************************/
/************************************************************************/
/************************************************************************/
tilelen = jas_stream_tell(enc->tmpstream);
if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
return -1;
}
jpc_putuint32(enc->tmpstream, tilelen);
if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
return -1;
}
if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
return -1;
}
enc->len += tilelen;
jas_stream_close(enc->tmpstream);
enc->tmpstream = 0;
jpc_enc_tile_destroy(enc->curtile);
enc->curtile = 0;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'jpc_enc: jpc_abstorelstepsize() returns error instead of aborting
Fixes CVE-2018-9252
Closes https://github.com/jasper-maint/jasper/issues/16'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pk_transaction_authorize_actions_finished_cb (GObject *source_object,
GAsyncResult *res,
struct AuthorizeActionsData *data)
{
const gchar *action_id = NULL;
PkTransactionPrivate *priv = data->transaction->priv;
g_autoptr(GError) error = NULL;
g_autoptr(PolkitAuthorizationResult) result = NULL;
g_assert (data->actions && data->actions->len > 0);
/* get the first action */
action_id = g_ptr_array_index (data->actions, 0);
/* finish the call */
result = polkit_authority_check_authorization_finish (priv->authority, res, &error);
/* failed because the request was cancelled */
if (g_cancellable_is_cancelled (priv->cancellable)) {
/* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */
priv->waiting_for_auth = FALSE;
pk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED);
pk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED,
"The authentication was cancelled due to a timeout.");
pk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0);
goto out;
}
/* failed, maybe polkit is messed up? */
if (result == NULL) {
g_autofree gchar *message = NULL;
priv->waiting_for_auth = FALSE;
g_warning ("failed to check for auth: %s", error->message);
/* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */
pk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED);
message = g_strdup_printf ("Failed to check for authentication: %s", error->message);
pk_transaction_error_code_emit (data->transaction,
PK_ERROR_ENUM_NOT_AUTHORIZED,
message);
pk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0);
goto out;
}
/* did not auth */
if (!polkit_authorization_result_get_is_authorized (result)) {
if (g_strcmp0 (action_id, "org.freedesktop.packagekit.package-install") == 0 &&
pk_bitfield_contain (priv->cached_transaction_flags,
PK_TRANSACTION_FLAG_ENUM_ALLOW_REINSTALL)) {
g_debug ("allowing just reinstallation");
pk_bitfield_add (priv->cached_transaction_flags,
PK_TRANSACTION_FLAG_ENUM_JUST_REINSTALL);
} else {
priv->waiting_for_auth = FALSE;
/* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */
pk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED);
pk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED,
"Failed to obtain authentication.");
pk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0);
syslog (LOG_AUTH | LOG_NOTICE,
"uid %i failed to obtain auth",
priv->uid);
goto out;
}
}
if (data->actions->len <= 1) {
/* authentication finished successfully */
priv->waiting_for_auth = FALSE;
pk_transaction_set_state (data->transaction, PK_TRANSACTION_STATE_READY);
/* log success too */
syslog (LOG_AUTH | LOG_INFO,
"uid %i obtained auth for %s",
priv->uid, action_id);
} else {
/* process the rest of actions */
g_ptr_array_remove_index (data->actions, 0);
pk_transaction_authorize_actions (data->transaction, data->role, data->actions);
}
out:
g_ptr_array_unref (data->actions);
g_free (data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287'], 'message': 'Do not set JUST_REINSTALL on any kind of auth failure
If we try to continue the auth queue when it has been cancelled (or failed)
then we fall upon the obscure JUST_REINSTALL transaction flag which only the
DNF backend actually verifies.
Many thanks to Matthias Gerstner <[email protected]> for spotting the problem.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pk_transaction_role_to_action_only_trusted (PkRoleEnum role)
{
const gchar *policy = NULL;
switch (role) {
case PK_ROLE_ENUM_UPDATE_PACKAGES:
policy = "org.freedesktop.packagekit.system-update";
break;
case PK_ROLE_ENUM_INSTALL_SIGNATURE:
policy = "org.freedesktop.packagekit.system-trust-signing-key";
break;
case PK_ROLE_ENUM_REPO_ENABLE:
case PK_ROLE_ENUM_REPO_SET_DATA:
case PK_ROLE_ENUM_REPO_REMOVE:
policy = "org.freedesktop.packagekit.system-sources-configure";
break;
case PK_ROLE_ENUM_REFRESH_CACHE:
policy = "org.freedesktop.packagekit.system-sources-refresh";
break;
case PK_ROLE_ENUM_REMOVE_PACKAGES:
policy = "org.freedesktop.packagekit.package-remove";
break;
case PK_ROLE_ENUM_INSTALL_PACKAGES:
policy = "org.freedesktop.packagekit.package-install";
break;
case PK_ROLE_ENUM_INSTALL_FILES:
policy = "org.freedesktop.packagekit.package-install";
break;
case PK_ROLE_ENUM_ACCEPT_EULA:
policy = "org.freedesktop.packagekit.package-eula-accept";
break;
case PK_ROLE_ENUM_CANCEL:
policy = "org.freedesktop.packagekit.cancel-foreign";
break;
case PK_ROLE_ENUM_REPAIR_SYSTEM:
policy = "org.freedesktop.packagekit.repair-system";
break;
default:
break;
}
return policy;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287'], 'message': 'Reinstallation and downgrade require authorization
Added new policy actions:
* org.freedesktop.packagekit.package-reinstall
* org.freedesktop.packagekit.package-downgrade
The first does not depend or require any other actions to be authorized
except for org.freedesktop.packagekit.package-install-untrusted in case
of reinstallation of not trusted package. The same applies to second one
plus it implies org.freedesktop.packagekit.package-install action (if
the user is authorized to downgrade, he's authorized to install as
well).
Now the authorization can spawn up to 3 asynchronous calls to polkit for
single package because each transaction flag (allow-downgrade,
allow-reinstall) the client supplies needs to be checked separately.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pk_transaction_obtain_authorization (PkTransaction *transaction,
PkRoleEnum role,
GError **error)
{
const gchar *action_id;
const gchar *text;
PkTransactionPrivate *priv = transaction->priv;
_cleanup_free_ gchar *package_ids = NULL;
_cleanup_object_unref_ PolkitDetails *details = NULL;
_cleanup_string_free_ GString *string = NULL;
g_return_val_if_fail (priv->sender != NULL, FALSE);
/* we don't need to authenticate at all to just download
* packages or if we're running unit tests */
if (pk_bitfield_contain (transaction->priv->cached_transaction_flags,
PK_TRANSACTION_FLAG_ENUM_ONLY_DOWNLOAD) ||
pk_bitfield_contain (transaction->priv->cached_transaction_flags,
PK_TRANSACTION_FLAG_ENUM_SIMULATE) ||
priv->skip_auth_check == TRUE) {
g_debug ("No authentication required");
pk_transaction_set_state (transaction, PK_TRANSACTION_STATE_READY);
return TRUE;
}
/* we should always have subject */
if (priv->subject == NULL) {
g_set_error (error,
PK_TRANSACTION_ERROR,
PK_TRANSACTION_ERROR_REFUSED_BY_POLICY,
"subject %s not found", priv->sender);
return FALSE;
}
/* map the roles to policykit rules */
if (pk_bitfield_contain (transaction->priv->cached_transaction_flags,
PK_TRANSACTION_FLAG_ENUM_ONLY_TRUSTED)) {
action_id = pk_transaction_role_to_action_only_trusted (role);
} else {
action_id = pk_transaction_role_to_action_allow_untrusted (role);
}
/* log */
syslog (LOG_AUTH | LOG_INFO,
"uid %i is trying to obtain %s auth (only_trusted:%i)",
priv->uid,
action_id,
pk_bitfield_contain (transaction->priv->cached_transaction_flags,
PK_TRANSACTION_FLAG_ENUM_ONLY_TRUSTED));
/* set transaction state */
pk_transaction_set_state (transaction,
PK_TRANSACTION_STATE_WAITING_FOR_AUTH);
/* check subject */
priv->waiting_for_auth = TRUE;
/* insert details about the authorization */
details = polkit_details_new ();
/* do we have package details? */
if (priv->cached_package_id != NULL)
package_ids = g_strdup (priv->cached_package_id);
else if (priv->cached_package_ids != NULL)
package_ids = pk_package_ids_to_string (priv->cached_package_ids);
/* save optional stuff */
if (package_ids != NULL)
polkit_details_insert (details, "package_ids", package_ids);
if (priv->cmdline != NULL)
polkit_details_insert (details, "cmdline", priv->cmdline);
/* do not use the default icon and wording for some roles */
if (role == PK_ROLE_ENUM_INSTALL_PACKAGES &&
role == PK_ROLE_ENUM_UPDATE_PACKAGES &&
!pk_bitfield_contain (priv->cached_transaction_flags, PK_TRANSACTION_FLAG_ENUM_ONLY_TRUSTED)) {
/* don't use the friendly PackageKit icon as this is
* might be a ricky authorisation */
polkit_details_insert (details, "polkit.icon_name", "emblem-important");
string = g_string_new ("");
/* TRANSLATORS: is not GPG signed */
g_string_append (string, g_dgettext (GETTEXT_PACKAGE, N_("The software is not from a trusted source.")));
g_string_append (string, "\n");
/* UpdatePackages */
if (priv->role == PK_ROLE_ENUM_UPDATE_PACKAGES) {
/* TRANSLATORS: user has to trust provider -- I know, this sucks */
text = g_dngettext (GETTEXT_PACKAGE,
N_("Do not update this package unless you are sure it is safe to do so."),
N_("Do not update these packages unless you are sure it is safe to do so."),
g_strv_length (priv->cached_package_ids));
g_string_append (string, text);
}
/* InstallPackages */
if (priv->role == PK_ROLE_ENUM_INSTALL_PACKAGES) {
/* TRANSLATORS: user has to trust provider -- I know, this sucks */
text = g_dngettext (GETTEXT_PACKAGE,
N_("Do not install this package unless you are sure it is safe to do so."),
N_("Do not install these packages unless you are sure it is safe to do so."),
g_strv_length (priv->cached_package_ids));
g_string_append (string, text);
}
if (string->len > 0) {
polkit_details_insert (details, "polkit.gettext_domain", GETTEXT_PACKAGE);
polkit_details_insert (details, "polkit.message", string->str);
}
}
/* do authorization async */
polkit_authority_check_authorization (priv->authority,
priv->subject,
action_id,
details,
POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION,
priv->cancellable,
(GAsyncReadyCallback) pk_transaction_action_obtain_authorization_finished_cb,
transaction);
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287'], 'message': 'Reinstallation and downgrade require authorization
Added new policy actions:
* org.freedesktop.packagekit.package-reinstall
* org.freedesktop.packagekit.package-downgrade
The first does not depend or require any other actions to be authorized
except for org.freedesktop.packagekit.package-install-untrusted in case
of reinstallation of not trusted package. The same applies to second one
plus it implies org.freedesktop.packagekit.package-install action (if
the user is authorized to downgrade, he's authorized to install as
well).
Now the authorization can spawn up to 3 asynchronous calls to polkit for
single package because each transaction flag (allow-downgrade,
allow-reinstall) the client supplies needs to be checked separately.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDFObjectHandle::parseInternal(PointerHolder<InputSource> input,
std::string const& object_description,
QPDFTokenizer& tokenizer, bool& empty,
StringDecrypter* decrypter, QPDF* context,
bool content_stream)
{
// This method must take care not to resolve any objects. Don't
// check the type of any object without first ensuring that it is
// a direct object. Otherwise, doing so may have the side effect
// of reading the object and changing the file pointer.
empty = false;
QPDFObjectHandle object;
std::vector<std::vector<QPDFObjectHandle> > olist_stack;
olist_stack.push_back(std::vector<QPDFObjectHandle>());
std::vector<parser_state_e> state_stack;
state_stack.push_back(st_top);
std::vector<qpdf_offset_t> offset_stack;
qpdf_offset_t offset = input->tell();
offset_stack.push_back(offset);
bool done = false;
while (! done)
{
std::vector<QPDFObjectHandle>& olist = olist_stack.back();
parser_state_e state = state_stack.back();
offset = offset_stack.back();
object = QPDFObjectHandle();
QPDFTokenizer::Token token =
tokenizer.readToken(input, object_description, true);
switch (token.getType())
{
case QPDFTokenizer::tt_eof:
if (! content_stream)
{
QTC::TC("qpdf", "QPDFObjectHandle eof in parseInternal");
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"unexpected EOF"));
}
state = st_eof;
break;
case QPDFTokenizer::tt_bad:
QTC::TC("qpdf", "QPDFObjectHandle bad token in parse");
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
token.getErrorMessage()));
object = newNull();
break;
case QPDFTokenizer::tt_brace_open:
case QPDFTokenizer::tt_brace_close:
QTC::TC("qpdf", "QPDFObjectHandle bad brace");
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"treating unexpected brace token as null"));
object = newNull();
break;
case QPDFTokenizer::tt_array_close:
if (state == st_array)
{
state = st_stop;
}
else
{
QTC::TC("qpdf", "QPDFObjectHandle bad array close");
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"treating unexpected array close token as null"));
object = newNull();
}
break;
case QPDFTokenizer::tt_dict_close:
if (state == st_dictionary)
{
state = st_stop;
}
else
{
QTC::TC("qpdf", "QPDFObjectHandle bad dictionary close");
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"unexpected dictionary close token"));
object = newNull();
}
break;
case QPDFTokenizer::tt_array_open:
case QPDFTokenizer::tt_dict_open:
olist_stack.push_back(std::vector<QPDFObjectHandle>());
state = st_start;
offset_stack.push_back(input->tell());
state_stack.push_back(
(token.getType() == QPDFTokenizer::tt_array_open) ?
st_array : st_dictionary);
break;
case QPDFTokenizer::tt_bool:
object = newBool((token.getValue() == "true"));
break;
case QPDFTokenizer::tt_null:
object = newNull();
break;
case QPDFTokenizer::tt_integer:
object = newInteger(QUtil::string_to_ll(token.getValue().c_str()));
break;
case QPDFTokenizer::tt_real:
object = newReal(token.getValue());
break;
case QPDFTokenizer::tt_name:
object = newName(token.getValue());
break;
case QPDFTokenizer::tt_word:
{
std::string const& value = token.getValue();
if (content_stream)
{
object = QPDFObjectHandle::newOperator(value);
}
else if ((value == "R") && (state != st_top) &&
(olist.size() >= 2) &&
(! olist.at(olist.size() - 1).isIndirect()) &&
(olist.at(olist.size() - 1).isInteger()) &&
(! olist.at(olist.size() - 2).isIndirect()) &&
(olist.at(olist.size() - 2).isInteger()))
{
if (context == 0)
{
QTC::TC("qpdf", "QPDFObjectHandle indirect without context");
throw std::logic_error(
"QPDFObjectHandle::parse called without context"
" on an object with indirect references");
}
// Try to resolve indirect objects
object = newIndirect(
context,
olist.at(olist.size() - 2).getIntValue(),
olist.at(olist.size() - 1).getIntValue());
olist.pop_back();
olist.pop_back();
}
else if ((value == "endobj") && (state == st_top))
{
// We just saw endobj without having read
// anything. Treat this as a null and do not move
// the input source's offset.
object = newNull();
input->seek(input->getLastOffset(), SEEK_SET);
empty = true;
}
else
{
QTC::TC("qpdf", "QPDFObjectHandle treat word as string");
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"unknown token while reading object;"
" treating as string"));
object = newString(value);
}
}
break;
case QPDFTokenizer::tt_string:
{
std::string val = token.getValue();
if (decrypter)
{
decrypter->decryptString(val);
}
object = QPDFObjectHandle::newString(val);
}
break;
default:
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"treating unknown token type as null while "
"reading object"));
object = newNull();
break;
}
if ((! object.isInitialized()) &&
(! ((state == st_start) ||
(state == st_stop) ||
(state == st_eof))))
{
throw std::logic_error(
"QPDFObjectHandle::parseInternal: "
"unexpected uninitialized object");
object = newNull();
}
switch (state)
{
case st_eof:
if (state_stack.size() > 1)
{
warn(context,
QPDFExc(qpdf_e_damaged_pdf, input->getName(),
object_description,
input->getLastOffset(),
"parse error while reading object"));
}
done = true;
// In content stream mode, leave object uninitialized to
// indicate EOF
if (! content_stream)
{
object = newNull();
}
break;
case st_dictionary:
case st_array:
setObjectDescriptionFromInput(
object, context, object_description, input,
input->getLastOffset());
olist.push_back(object);
break;
case st_top:
done = true;
break;
case st_start:
break;
case st_stop:
if ((state_stack.size() < 2) || (olist_stack.size() < 2))
{
throw std::logic_error(
"QPDFObjectHandle::parseInternal: st_stop encountered"
" with insufficient elements in stack");
}
parser_state_e old_state = state_stack.back();
state_stack.pop_back();
if (old_state == st_array)
{
object = newArray(olist);
setObjectDescriptionFromInput(
object, context, object_description, input, offset);
}
else if (old_state == st_dictionary)
{
// Convert list to map. Alternating elements are keys.
// Attempt to recover more or less gracefully from
// invalid dictionaries.
std::set<std::string> names;
for (std::vector<QPDFObjectHandle>::iterator iter =
olist.begin();
iter != olist.end(); ++iter)
{
if ((! (*iter).isIndirect()) && (*iter).isName())
{
names.insert((*iter).getName());
}
}
std::map<std::string, QPDFObjectHandle> dict;
int next_fake_key = 1;
for (unsigned int i = 0; i < olist.size(); ++i)
{
QPDFObjectHandle key_obj = olist.at(i);
QPDFObjectHandle val;
if (key_obj.isIndirect() || (! key_obj.isName()))
{
bool found_fake = false;
std::string candidate;
while (! found_fake)
{
candidate =
"/QPDFFake" +
QUtil::int_to_string(next_fake_key++);
found_fake = (names.count(candidate) == 0);
QTC::TC("qpdf", "QPDFObjectHandle found fake",
(found_fake ? 0 : 1));
}
warn(context,
QPDFExc(
qpdf_e_damaged_pdf,
input->getName(), object_description, offset,
"expected dictionary key but found"
" non-name object; inserting key " +
candidate));
val = key_obj;
key_obj = newName(candidate);
}
else if (i + 1 >= olist.size())
{
QTC::TC("qpdf", "QPDFObjectHandle no val for last key");
warn(context,
QPDFExc(
qpdf_e_damaged_pdf,
input->getName(), object_description, offset,
"dictionary ended prematurely; "
"using null as value for last key"));
val = newNull();
setObjectDescriptionFromInput(
val, context, object_description, input, offset);
}
else
{
val = olist.at(++i);
}
dict[key_obj.getName()] = val;
}
object = newDictionary(dict);
setObjectDescriptionFromInput(
object, context, object_description, input, offset);
}
olist_stack.pop_back();
offset_stack.pop_back();
if (state_stack.back() == st_top)
{
done = true;
}
else
{
olist_stack.back().push_back(object);
}
}
}
setObjectDescriptionFromInput(
object, context, object_description, input, offset);
return object;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-674'], 'message': 'Limit depth of nesting in direct objects (fixes #202)
This fixes CVE-2018-9918.'</s> |
<s>[INST] Given the following code containing errors, provide 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 kernel_wait4(pid_t upid, int __user *stat_addr, int options,
struct rusage *ru)
{
struct wait_opts wo;
struct pid *pid = NULL;
enum pid_type type;
long ret;
if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
__WNOTHREAD|__WCLONE|__WALL))
return -EINVAL;
if (upid == -1)
type = PIDTYPE_MAX;
else if (upid < 0) {
type = PIDTYPE_PGID;
pid = find_get_pid(-upid);
} else if (upid == 0) {
type = PIDTYPE_PGID;
pid = get_task_pid(current, PIDTYPE_PGID);
} else /* upid > 0 */ {
type = PIDTYPE_PID;
pid = find_get_pid(upid);
}
wo.wo_type = type;
wo.wo_pid = pid;
wo.wo_flags = options | WEXITED;
wo.wo_info = NULL;
wo.wo_stat = 0;
wo.wo_rusage = ru;
ret = do_wait(&wo);
put_pid(pid);
if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
ret = -EFAULT;
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'kernel/exit.c: avoid undefined behaviour when calling wait4()
wait4(-2147483648, 0x20, 0, 0xdd0000) triggers:
UBSAN: Undefined behaviour in kernel/exit.c:1651:9
The related calltrace is as follows:
negation of -2147483648 cannot be represented in type 'int':
CPU: 9 PID: 16482 Comm: zj Tainted: G B ---- ------- 3.10.0-327.53.58.71.x86_64+ #66
Hardware name: Huawei Technologies Co., Ltd. Tecal RH2285 /BC11BTSA , BIOS CTSAV036 04/27/2011
Call Trace:
dump_stack+0x19/0x1b
ubsan_epilogue+0xd/0x50
__ubsan_handle_negate_overflow+0x109/0x14e
SyS_wait4+0x1cb/0x1e0
system_call_fastpath+0x16/0x1b
Exclude the overflow to avoid the UBSAN warning.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: zhongjiang <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Aneesh Kumar K.V <[email protected]>
Cc: Kirill A. Shutemov <[email protected]>
Cc: Xishi Qiu <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
bool ret = true;
/*
* We have to make sure to not race with the victim exit path
* and cause premature new oom victim selection:
* __oom_reap_task_mm exit_mm
* mmget_not_zero
* mmput
* atomic_dec_and_test
* exit_oom_victim
* [...]
* out_of_memory
* select_bad_process
* # no TIF_MEMDIE task selects new victim
* unmap_page_range # frees some memory
*/
mutex_lock(&oom_lock);
if (!down_read_trylock(&mm->mmap_sem)) {
ret = false;
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
/*
* If the mm has invalidate_{start,end}() notifiers that could block,
* sleep to give the oom victim some more time.
* TODO: we really want to get rid of this ugly hack and make sure that
* notifiers cannot block for unbounded amount of time
*/
if (mm_has_blockable_invalidate_notifiers(mm)) {
up_read(&mm->mmap_sem);
schedule_timeout_idle(HZ);
goto unlock_oom;
}
/*
* MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't
* work on the mm anymore. The check for MMF_OOM_SKIP must run
* under mmap_sem for reading because it serializes against the
* down_write();up_write() cycle in exit_mmap().
*/
if (test_bit(MMF_OOM_SKIP, &mm->flags)) {
up_read(&mm->mmap_sem);
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
trace_start_task_reaping(tsk->pid);
/*
* Tell all users of get_user/copy_from_user etc... that the content
* is no longer stable. No barriers really needed because unmapping
* should imply barriers already and the reader would hit a page fault
* if it stumbled over a reaped memory.
*/
set_bit(MMF_UNSTABLE, &mm->flags);
for (vma = mm->mmap ; vma; vma = vma->vm_next) {
if (!can_madv_dontneed_vma(vma))
continue;
/*
* Only anonymous pages have a good chance to be dropped
* without additional steps which we cannot afford as we
* are OOM already.
*
* We do not even care about fs backed pages because all
* which are reclaimable have already been reclaimed and
* we do not want to block exit_mmap by keeping mm ref
* count elevated without a good reason.
*/
if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {
const unsigned long start = vma->vm_start;
const unsigned long end = vma->vm_end;
tlb_gather_mmu(&tlb, mm, start, end);
mmu_notifier_invalidate_range_start(mm, start, end);
unmap_page_range(&tlb, vma, start, end, NULL);
mmu_notifier_invalidate_range_end(mm, start, end);
tlb_finish_mmu(&tlb, start, end);
}
}
pr_info("oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n",
task_pid_nr(tsk), tsk->comm,
K(get_mm_counter(mm, MM_ANONPAGES)),
K(get_mm_counter(mm, MM_FILEPAGES)),
K(get_mm_counter(mm, MM_SHMEMPAGES)));
up_read(&mm->mmap_sem);
trace_finish_task_reaping(tsk->pid);
unlock_oom:
mutex_unlock(&oom_lock);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'mm, oom: fix concurrent munlock and oom reaper unmap, v3
Since exit_mmap() is done without the protection of mm->mmap_sem, it is
possible for the oom reaper to concurrently operate on an mm until
MMF_OOM_SKIP is set.
This allows munlock_vma_pages_all() to concurrently run while the oom
reaper is operating on a vma. Since munlock_vma_pages_range() depends
on clearing VM_LOCKED from vm_flags before actually doing the munlock to
determine if any other vmas are locking the same memory, the check for
VM_LOCKED in the oom reaper is racy.
This is especially noticeable on architectures such as powerpc where
clearing a huge pmd requires serialize_against_pte_lookup(). If the pmd
is zapped by the oom reaper during follow_page_mask() after the check
for pmd_none() is bypassed, this ends up deferencing a NULL ptl or a
kernel oops.
Fix this by manually freeing all possible memory from the mm before
doing the munlock and then setting MMF_OOM_SKIP. The oom reaper can not
run on the mm anymore so the munlock is safe to do in exit_mmap(). It
also matches the logic that the oom reaper currently uses for
determining when to set MMF_OOM_SKIP itself, so there's no new risk of
excessive oom killing.
This issue fixes CVE-2018-1000200.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 212925802454 ("mm: oom: let oom_reap_task and exit_mmap run concurrently")
Signed-off-by: David Rientjes <[email protected]>
Suggested-by: Tetsuo Handa <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: Andrea Arcangeli <[email protected]>
Cc: <[email protected]> [4.14+]
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void exit_mmap(struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
unsigned long nr_accounted = 0;
/* mm's last user has gone, and its about to be pulled down */
mmu_notifier_release(mm);
if (mm->locked_vm) {
vma = mm->mmap;
while (vma) {
if (vma->vm_flags & VM_LOCKED)
munlock_vma_pages_all(vma);
vma = vma->vm_next;
}
}
arch_exit_mmap(mm);
vma = mm->mmap;
if (!vma) /* Can happen if dup_mmap() received an OOM */
return;
lru_add_drain();
flush_cache_mm(mm);
tlb_gather_mmu(&tlb, mm, 0, -1);
/* update_hiwater_rss(mm) here? but nobody should be looking */
/* Use -1 here to ensure all VMAs in the mm are unmapped */
unmap_vmas(&tlb, vma, 0, -1);
if (unlikely(mm_is_oom_victim(mm))) {
/*
* Wait for oom_reap_task() to stop working on this
* mm. Because MMF_OOM_SKIP is already set before
* calling down_read(), oom_reap_task() will not run
* on this "mm" post up_write().
*
* mm_is_oom_victim() cannot be set from under us
* either because victim->mm is already set to NULL
* under task_lock before calling mmput and oom_mm is
* set not NULL by the OOM killer only if victim->mm
* is found not NULL while holding the task_lock.
*/
set_bit(MMF_OOM_SKIP, &mm->flags);
down_write(&mm->mmap_sem);
up_write(&mm->mmap_sem);
}
free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
tlb_finish_mmu(&tlb, 0, -1);
/*
* Walk the list again, actually closing and freeing it,
* with preemption enabled, without holding any MM locks.
*/
while (vma) {
if (vma->vm_flags & VM_ACCOUNT)
nr_accounted += vma_pages(vma);
vma = remove_vma(vma);
}
vm_unacct_memory(nr_accounted);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'mm, oom: fix concurrent munlock and oom reaper unmap, v3
Since exit_mmap() is done without the protection of mm->mmap_sem, it is
possible for the oom reaper to concurrently operate on an mm until
MMF_OOM_SKIP is set.
This allows munlock_vma_pages_all() to concurrently run while the oom
reaper is operating on a vma. Since munlock_vma_pages_range() depends
on clearing VM_LOCKED from vm_flags before actually doing the munlock to
determine if any other vmas are locking the same memory, the check for
VM_LOCKED in the oom reaper is racy.
This is especially noticeable on architectures such as powerpc where
clearing a huge pmd requires serialize_against_pte_lookup(). If the pmd
is zapped by the oom reaper during follow_page_mask() after the check
for pmd_none() is bypassed, this ends up deferencing a NULL ptl or a
kernel oops.
Fix this by manually freeing all possible memory from the mm before
doing the munlock and then setting MMF_OOM_SKIP. The oom reaper can not
run on the mm anymore so the munlock is safe to do in exit_mmap(). It
also matches the logic that the oom reaper currently uses for
determining when to set MMF_OOM_SKIP itself, so there's no new risk of
excessive oom killing.
This issue fixes CVE-2018-1000200.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 212925802454 ("mm: oom: let oom_reap_task and exit_mmap run concurrently")
Signed-off-by: David Rientjes <[email protected]>
Suggested-by: Tetsuo Handa <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: Andrea Arcangeli <[email protected]>
Cc: <[email protected]> [4.14+]
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat)
{
int code = gs_distance_transform_inverse(dx, dy, pmat, pdist);
double rounded;
if (code == gs_error_undefinedresult) {
/* The CTM is degenerate.
Can't know the distance in user space.
Set zero because we believe it is not important for rendering.
We want to copy the text to PDF to make it searchable.
Bug 689006.
*/
pdist->x = pdist->y = 0;
} else if (code < 0)
return code;
/* If the distance is very close to integers, round it. */
if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005)
pdist->x = rounded;
if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005)
pdist->y = rounded;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'pdfwrite - Guard against trying to output an infinite number
Bug #699255 " Buffer overflow on pprintg1 due to mishandle postscript file data to pdf"
The file uses an enormous parameter to xyxhow, causing an overflow in
the calculation of text positioning (value > 1e39).
Since this is basically a nonsense value, and PostScript only supports
real values up to 1e38, this patch follows the same approach as for
a degenerate CTM, and treats it as 0.
Adobe Acrobat Distiller throws a limitcheck error, so we could do that
instead if this approach proves to be a problem.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ppm_load_read_header(FILE *fp,
pnm_struct *img)
{
/* PPM Headers Variable Declaration */
gchar *ptr;
//gchar *retval;
gchar header[MAX_CHARS_IN_ROW];
gint maxval;
int channel_count;
/* Check the PPM file Type P3 or P6 */
if (fgets (header, MAX_CHARS_IN_ROW, fp) == NULL ||
header[0] != ASCII_P ||
(header[1] != PIXMAP_ASCII_GRAY &&
header[1] != PIXMAP_ASCII &&
header[1] != PIXMAP_RAW_GRAY &&
header[1] != PIXMAP_RAW))
{
g_warning ("Image is not a portable pixmap");
return FALSE;
}
img->type = header[1];
if (img->type == PIXMAP_RAW_GRAY || img->type == PIXMAP_ASCII_GRAY)
channel_count = CHANNEL_COUNT_GRAY;
else
channel_count = CHANNEL_COUNT;
/* Check the Comments */
while((fgets (header, MAX_CHARS_IN_ROW, fp)) && (header[0] == '#'))
;
/* Get Width and Height */
errno = 0;
img->width = strtol (header, &ptr, 10);
if (errno)
{
g_warning ("Error reading width: %s", strerror(errno));
return FALSE;
}
else if (img->width < 0)
{
g_warning ("Error: width is negative");
return FALSE;
}
img->height = strtol (ptr, &ptr, 10);
if (errno)
{
g_warning ("Error reading height: %s", strerror(errno));
return FALSE;
}
else if (img->width < 0)
{
g_warning ("Error: height is negative");
return FALSE;
}
if (fgets (header, MAX_CHARS_IN_ROW, fp))
maxval = strtol (header, &ptr, 10);
else
maxval = 0;
if ((maxval != 255) && (maxval != 65535))
{
g_warning ("Image is not an 8-bit or 16-bit portable pixmap");
return FALSE;
}
switch (maxval)
{
case 255:
img->bpc = sizeof (guchar);
break;
case 65535:
img->bpc = sizeof (gushort);
break;
default:
g_warning ("%s: Programmer stupidity error", G_STRLOC);
}
/* Later on, img->numsamples is multiplied with img->bpc to allocate
* memory. Ensure it doesn't overflow. */
if (!img->width || !img->height ||
G_MAXSIZE / img->width / img->height / CHANNEL_COUNT < img->bpc)
{
g_warning ("Illegal width/height: %ld/%ld", img->width, img->height);
return FALSE;
}
img->channels = channel_count;
img->numsamples = img->width * img->height * channel_count;
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'ppm-load: limit max permitted buffer allocation to 2GB
Fixing bug #795248'</s> |
<s>[INST] Given the following code containing errors, provide 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 *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=(size_t) ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
break;
}
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(unsigned long)mng_get_long(p);
mng_info->mng_height=(unsigned long)mng_get_long(&p[4]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (length < 2)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]);
mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
if (mng_info->global_plte == (png_colorp) NULL)
{
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
mng_info=MngInfoFreeStruct(mng_info);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (((p-chunk) < (long) length) && *p)
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && ((p-chunk) < (ssize_t) (length-4)))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && ((p-chunk) < (ssize_t) (length-4)))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && ((p-chunk) < (ssize_t) (length-16)))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=16;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(unsigned long) mng_get_long(p);
basi_width=(unsigned long) mng_get_long(&p[4]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(png_uint_32) p[12] << 8) & png_uint_32) p[13];
else
basi_red=0;
if (length > 15)
basi_green=(png_uint_32) p[14] << 8) & png_uint_32) p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(png_uint_32) p[16] << 8) & png_uint_32) p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(png_uint_32) p[18] << 8) & png_uint_32) p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
if (prev != (PixelPacket *) NULL)
prev=(PixelPacket *) RelinquishMagickMemory(prev);
if (next != (PixelPacket *) NULL)
next=(PixelPacket *) RelinquishMagickMemory(next);
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) memcpy(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) memcpy(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
if (q == (PixelPacket *) NULL)
break;
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'Fixed infinite loop (#1095).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int php_iconv_stream_filter_append_bucket(
php_iconv_stream_filter *self,
php_stream *stream, php_stream_filter *filter,
php_stream_bucket_brigade *buckets_out,
const char *ps, size_t buf_len, size_t *consumed,
int persistent TSRMLS_DC)
{
php_stream_bucket *new_bucket;
char *out_buf = NULL;
size_t out_buf_size;
char *pd, *pt;
size_t ocnt, prev_ocnt, icnt, tcnt;
size_t initial_out_buf_size;
if (ps == NULL) {
initial_out_buf_size = 64;
icnt = 1;
} else {
initial_out_buf_size = buf_len;
icnt = buf_len;
}
out_buf_size = ocnt = prev_ocnt = initial_out_buf_size;
if (NULL == (out_buf = pemalloc(out_buf_size, persistent))) {
return FAILURE;
}
pd = out_buf;
if (self->stub_len > 0) {
pt = self->stub;
tcnt = self->stub_len;
while (tcnt > 0) {
if (iconv(self->cd, &pt, &tcnt, &pd, &ocnt) == (size_t)-1) {
#if ICONV_SUPPORTS_ERRNO
switch (errno) {
case EILSEQ:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): invalid multibyte sequence", self->from_charset, self->to_charset);
goto out_failure;
case EINVAL:
if (ps != NULL) {
if (icnt > 0) {
if (self->stub_len >= sizeof(self->stub)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): insufficient buffer", self->from_charset, self->to_charset);
goto out_failure;
}
self->stub[self->stub_len++] = *(ps++);
icnt--;
pt = self->stub;
tcnt = self->stub_len;
} else {
tcnt = 0;
break;
}
}
break;
case E2BIG: {
char *new_out_buf;
size_t new_out_buf_size;
new_out_buf_size = out_buf_size << 1;
if (new_out_buf_size < out_buf_size) {
/* whoa! no bigger buckets are sold anywhere... */
if (NULL == (new_bucket = php_stream_bucket_new(stream, out_buf, (out_buf_size - ocnt), 1, persistent TSRMLS_CC))) {
goto out_failure;
}
php_stream_bucket_append(buckets_out, new_bucket TSRMLS_CC);
out_buf_size = ocnt = initial_out_buf_size;
if (NULL == (out_buf = pemalloc(out_buf_size, persistent))) {
return FAILURE;
}
pd = out_buf;
} else {
if (NULL == (new_out_buf = perealloc(out_buf, new_out_buf_size, persistent))) {
if (NULL == (new_bucket = php_stream_bucket_new(stream, out_buf, (out_buf_size - ocnt), 1, persistent TSRMLS_CC))) {
goto out_failure;
}
php_stream_bucket_append(buckets_out, new_bucket TSRMLS_CC);
return FAILURE;
}
pd = new_out_buf + (pd - out_buf);
ocnt += (new_out_buf_size - out_buf_size);
out_buf = new_out_buf;
out_buf_size = new_out_buf_size;
}
} break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): unknown error", self->from_charset, self->to_charset);
goto out_failure;
}
#else
if (ocnt == prev_ocnt) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): unknown error", self->from_charset, self->to_charset);
goto out_failure;
}
#endif
}
prev_ocnt = ocnt;
}
memmove(self->stub, pt, tcnt);
self->stub_len = tcnt;
}
while (icnt > 0) {
if ((ps == NULL ? iconv(self->cd, NULL, NULL, &pd, &ocnt):
iconv(self->cd, (char **)&ps, &icnt, &pd, &ocnt)) == (size_t)-1) {
#if ICONV_SUPPORTS_ERRNO
switch (errno) {
case EILSEQ:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): invalid multibyte sequence", self->from_charset, self->to_charset);
goto out_failure;
case EINVAL:
if (ps != NULL) {
if (icnt > sizeof(self->stub)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): insufficient buffer", self->from_charset, self->to_charset);
goto out_failure;
}
memcpy(self->stub, ps, icnt);
self->stub_len = icnt;
ps += icnt;
icnt = 0;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): unexpected octet values", self->from_charset, self->to_charset);
goto out_failure;
}
break;
case E2BIG: {
char *new_out_buf;
size_t new_out_buf_size;
new_out_buf_size = out_buf_size << 1;
if (new_out_buf_size < out_buf_size) {
/* whoa! no bigger buckets are sold anywhere... */
if (NULL == (new_bucket = php_stream_bucket_new(stream, out_buf, (out_buf_size - ocnt), 1, persistent TSRMLS_CC))) {
goto out_failure;
}
php_stream_bucket_append(buckets_out, new_bucket TSRMLS_CC);
out_buf_size = ocnt = initial_out_buf_size;
if (NULL == (out_buf = pemalloc(out_buf_size, persistent))) {
return FAILURE;
}
pd = out_buf;
} else {
if (NULL == (new_out_buf = perealloc(out_buf, new_out_buf_size, persistent))) {
if (NULL == (new_bucket = php_stream_bucket_new(stream, out_buf, (out_buf_size - ocnt), 1, persistent TSRMLS_CC))) {
goto out_failure;
}
php_stream_bucket_append(buckets_out, new_bucket TSRMLS_CC);
return FAILURE;
}
pd = new_out_buf + (pd - out_buf);
ocnt += (new_out_buf_size - out_buf_size);
out_buf = new_out_buf;
out_buf_size = new_out_buf_size;
}
} break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): unknown error", self->from_charset, self->to_charset);
goto out_failure;
}
#else
if (ocnt == prev_ocnt) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "iconv stream filter (\"%s\"=>\"%s\"): unknown error", self->from_charset, self->to_charset);
goto out_failure;
}
#endif
} else {
if (ps == NULL) {
break;
}
}
prev_ocnt = ocnt;
}
if (out_buf_size - ocnt > 0) {
if (NULL == (new_bucket = php_stream_bucket_new(stream, out_buf, (out_buf_size - ocnt), 1, persistent TSRMLS_CC))) {
goto out_failure;
}
php_stream_bucket_append(buckets_out, new_bucket TSRMLS_CC);
} else {
pefree(out_buf, persistent);
}
*consumed += buf_len - icnt;
return SUCCESS;
out_failure:
pefree(out_buf, persistent);
return FAILURE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'Fix bug #76249 - fail on invalid sequences'</s> |
<s>[INST] Given the following code containing errors, provide 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 phar_do_404(phar_archive_data *phar, char *fname, int fname_len, char *f404, int f404_len, char *entry, int entry_len TSRMLS_DC) /* {{{ */
{
sapi_header_line ctr = {0};
phar_entry_info *info;
if (phar && f404_len) {
info = phar_get_entry_info(phar, f404, f404_len, NULL, 1 TSRMLS_CC);
if (info) {
phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0 TSRMLS_CC);
return;
}
}
ctr.response_code = 404;
ctr.line_len = sizeof("HTTP/1.0 404 Not Found")-1;
ctr.line = "HTTP/1.0 404 Not Found";
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
sapi_send_headers(TSRMLS_C);
PHPWRITE("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ", sizeof("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ") - 1);
PHPWRITE(entry, entry_len);
PHPWRITE(" Not Found</h1>\n </body>\n</html>", sizeof(" Not Found</h1>\n </body>\n</html>") - 1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-79'], 'message': 'Fix #76129 - remove more potential unfiltered outputs for phar'</s> |
<s>[INST] Given the following code containing errors, provide 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 ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0;
int64_t total_samples = 0, infilesize;
RiffChunkHeader riff_chunk_header;
ChunkHeader chunk_header;
WaveHeader WaveHeader;
DS64Chunk ds64_chunk;
uint32_t bcount;
CLEAR (WaveHeader);
CLEAR (ds64_chunk);
infilesize = DoGetFileSize (infile);
if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) {
error_line ("can't handle .WAV files larger than 4 GB (non-standard)!");
return WAVPACK_SOFT_ERROR;
}
memcpy (&riff_chunk_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) ||
bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) ||
bcount != sizeof (ChunkHeader)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat);
if (!strncmp (chunk_header.ckID, "ds64", 4)) {
if (chunk_header.ckSize < sizeof (DS64Chunk) ||
!DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) ||
bcount != sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
got_ds64 = 1;
WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat);
if (debug_logging_mode)
error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d",
(long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64,
(long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength);
if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
while (ds64_chunk.tableLength--) {
CS64Chunk cs64_chunk;
if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) ||
bcount != sizeof (CS64Chunk) ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
}
}
else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and
int supported = TRUE, format; // make sure it's a .wav file we can handle
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .WAV format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this WAV file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else if (config->float_norm_exp)
error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)",
config->float_norm_exp - 126, 150 - config->float_norm_exp);
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop
int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ?
ds64_chunk.dataSize64 : chunk_header.ckSize;
if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required)
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) {
error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (config->qmode & QMODE_IGNORE_LENGTH) {
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
total_samples = data_chunk_size / WaveHeader.BlockAlign;
if (got_ds64 && total_samples != ds64_chunk.sampleCount64) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (!total_samples) {
error_line ("this .WAV file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L;
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'issue #30 issue #31 issue #32: no multiple format chunks in WAV or W64'</s> |
<s>[INST] Given the following code containing errors, provide 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 ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
// loop through all elements of the DSDIFF header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk;
if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);
prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (eptr - cptr >= dff_chunk_header.ckDataSize) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'issue #33, sanitize size of unknown chunks before malloc()'</s> |
<s>[INST] Given the following code containing errors, provide 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 ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0;
int64_t total_samples = 0, infilesize;
RiffChunkHeader riff_chunk_header;
ChunkHeader chunk_header;
WaveHeader WaveHeader;
DS64Chunk ds64_chunk;
uint32_t bcount;
CLEAR (WaveHeader);
CLEAR (ds64_chunk);
infilesize = DoGetFileSize (infile);
if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) {
error_line ("can't handle .WAV files larger than 4 GB (non-standard)!");
return WAVPACK_SOFT_ERROR;
}
memcpy (&riff_chunk_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) ||
bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) ||
bcount != sizeof (ChunkHeader)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat);
if (!strncmp (chunk_header.ckID, "ds64", 4)) {
if (chunk_header.ckSize < sizeof (DS64Chunk) ||
!DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) ||
bcount != sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
got_ds64 = 1;
WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat);
if (debug_logging_mode)
error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d",
(long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64,
(long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength);
if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
while (ds64_chunk.tableLength--) {
CS64Chunk cs64_chunk;
if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) ||
bcount != sizeof (CS64Chunk) ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
}
}
else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and
int supported = TRUE, format; // make sure it's a .wav file we can handle
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .WAV format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this WAV file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else if (config->float_norm_exp)
error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)",
config->float_norm_exp - 126, 150 - config->float_norm_exp);
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop
int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ?
ds64_chunk.dataSize64 : chunk_header.ckSize;
if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required)
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) {
error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (config->qmode & QMODE_IGNORE_LENGTH) {
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
total_samples = data_chunk_size / WaveHeader.BlockAlign;
if (got_ds64 && total_samples != ds64_chunk.sampleCount64) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (!total_samples) {
error_line ("this .WAV file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L;
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'issue #33, sanitize size of unknown chunks before malloc()'</s> |
<s>[INST] Given the following code containing errors, provide 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_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
{
vm_flags_t vm_flags = vma->vm_flags;
int write = (gup_flags & FOLL_WRITE);
int foreign = (gup_flags & FOLL_REMOTE);
if (vm_flags & (VM_IO | VM_PFNMAP))
return -EFAULT;
if (write) {
if (!(vm_flags & VM_WRITE)) {
if (!(gup_flags & FOLL_FORCE))
return -EFAULT;
/*
* We used to let the write,force case do COW in a
* VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
* set a breakpoint in a read-only mapping of an
* executable, without corrupting the file (yet only
* when that file had been opened for writing!).
* Anon pages in shared mappings are surprising: now
* just reject it.
*/
if (!is_cow_mapping(vm_flags))
return -EFAULT;
}
} else if (!(vm_flags & VM_READ)) {
if (!(gup_flags & FOLL_FORCE))
return -EFAULT;
/*
* Is there actually any vma we can reach here which does not
* have VM_MAYREAD set?
*/
if (!(vm_flags & VM_MAYREAD))
return -EFAULT;
}
/*
* gups are always data accesses, not instruction
* fetches, so execute=false here
*/
if (!arch_vma_access_permitted(vma, write, false, foreign))
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'proc: do not access cmdline nor environ from file-backed areas
proc_pid_cmdline_read() and environ_read() directly access the target
process' VM to retrieve the command line and environment. If this
process remaps these areas onto a file via mmap(), the requesting
process may experience various issues such as extra delays if the
underlying device is slow to respond.
Let's simply refuse to access file-backed areas in these functions.
For this we add a new FOLL_ANON gup flag that is passed to all calls
to access_remote_vm(). The code already takes care of such failures
(including unmapped areas). Accesses via /proc/pid/mem were not
changed though.
This was assigned CVE-2018-1120.
Note for stable backports: the patch may apply to kernels prior to 4.11
but silently miss one location; it must be checked that no call to
access_remote_vm() keeps zero as the last argument.
Reported-by: Qualys Security Advisory <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: [email protected]
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t proc_pid_cmdline_read(struct file *file, char __user *buf,
size_t _count, loff_t *pos)
{
struct task_struct *tsk;
struct mm_struct *mm;
char *page;
unsigned long count = _count;
unsigned long arg_start, arg_end, env_start, env_end;
unsigned long len1, len2, len;
unsigned long p;
char c;
ssize_t rv;
BUG_ON(*pos < 0);
tsk = get_proc_task(file_inode(file));
if (!tsk)
return -ESRCH;
mm = get_task_mm(tsk);
put_task_struct(tsk);
if (!mm)
return 0;
/* Check if process spawned far enough to have cmdline. */
if (!mm->env_end) {
rv = 0;
goto out_mmput;
}
page = (char *)__get_free_page(GFP_KERNEL);
if (!page) {
rv = -ENOMEM;
goto out_mmput;
}
down_read(&mm->mmap_sem);
arg_start = mm->arg_start;
arg_end = mm->arg_end;
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
BUG_ON(arg_start > arg_end);
BUG_ON(env_start > env_end);
len1 = arg_end - arg_start;
len2 = env_end - env_start;
/* Empty ARGV. */
if (len1 == 0) {
rv = 0;
goto out_free_page;
}
/*
* Inherently racy -- command line shares address space
* with code and data.
*/
rv = access_remote_vm(mm, arg_end - 1, &c, 1, 0);
if (rv <= 0)
goto out_free_page;
rv = 0;
if (c == '\0') {
/* Command line (set of strings) occupies whole ARGV. */
if (len1 <= *pos)
goto out_free_page;
p = arg_start + *pos;
len = len1 - *pos;
while (count > 0 && len > 0) {
unsigned int _count;
int nr_read;
_count = min3(count, len, PAGE_SIZE);
nr_read = access_remote_vm(mm, p, page, _count, 0);
if (nr_read < 0)
rv = nr_read;
if (nr_read <= 0)
goto out_free_page;
if (copy_to_user(buf, page, nr_read)) {
rv = -EFAULT;
goto out_free_page;
}
p += nr_read;
len -= nr_read;
buf += nr_read;
count -= nr_read;
rv += nr_read;
}
} else {
/*
* Command line (1 string) occupies ARGV and
* extends into ENVP.
*/
struct {
unsigned long p;
unsigned long len;
} cmdline[2] = {
{ .p = arg_start, .len = len1 },
{ .p = env_start, .len = len2 },
};
loff_t pos1 = *pos;
unsigned int i;
i = 0;
while (i < 2 && pos1 >= cmdline[i].len) {
pos1 -= cmdline[i].len;
i++;
}
while (i < 2) {
p = cmdline[i].p + pos1;
len = cmdline[i].len - pos1;
while (count > 0 && len > 0) {
unsigned int _count, l;
int nr_read;
bool final;
_count = min3(count, len, PAGE_SIZE);
nr_read = access_remote_vm(mm, p, page, _count, 0);
if (nr_read < 0)
rv = nr_read;
if (nr_read <= 0)
goto out_free_page;
/*
* Command line can be shorter than whole ARGV
* even if last "marker" byte says it is not.
*/
final = false;
l = strnlen(page, nr_read);
if (l < nr_read) {
nr_read = l;
final = true;
}
if (copy_to_user(buf, page, nr_read)) {
rv = -EFAULT;
goto out_free_page;
}
p += nr_read;
len -= nr_read;
buf += nr_read;
count -= nr_read;
rv += nr_read;
if (final)
goto out_free_page;
}
/* Only first chunk can be read partially. */
pos1 = 0;
i++;
}
}
out_free_page:
free_page((unsigned long)page);
out_mmput:
mmput(mm);
if (rv > 0)
*pos += rv;
return rv;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'proc: do not access cmdline nor environ from file-backed areas
proc_pid_cmdline_read() and environ_read() directly access the target
process' VM to retrieve the command line and environment. If this
process remaps these areas onto a file via mmap(), the requesting
process may experience various issues such as extra delays if the
underlying device is slow to respond.
Let's simply refuse to access file-backed areas in these functions.
For this we add a new FOLL_ANON gup flag that is passed to all calls
to access_remote_vm(). The code already takes care of such failures
(including unmapped areas). Accesses via /proc/pid/mem were not
changed though.
This was assigned CVE-2018-1120.
Note for stable backports: the patch may apply to kernels prior to 4.11
but silently miss one location; it must be checked that no call to
access_remote_vm() keeps zero as the last argument.
Reported-by: Qualys Security Advisory <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: [email protected]
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool verify_authorizer(Connection *con, int peer_type, int protocol, bufferlist& auth, bufferlist& auth_reply,
bool& isvalid, CryptoKey& session_key) {
return ms_deliver_verify_authorizer(con, peer_type, protocol, auth,
auth_reply, isvalid, session_key);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: virtual bool ms_verify_authorizer(Connection *con, int peer_type,
int protocol, bufferlist& authorizer,
bufferlist& authorizer_reply,
bool& isvalid, CryptoKey& session_key) {
/* always succeed */
isvalid = true;
return true;
}; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide 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 CephxServiceHandler::handle_request(bufferlist::iterator& indata, bufferlist& result_bl, uint64_t& global_id, AuthCapsInfo& caps, uint64_t *auid)
{
int ret = 0;
struct CephXRequestHeader cephx_header;
::decode(cephx_header, indata);
switch (cephx_header.request_type) {
case CEPHX_GET_AUTH_SESSION_KEY:
{
ldout(cct, 10) << "handle_request get_auth_session_key for " << entity_name << dendl;
CephXAuthenticate req;
::decode(req, indata);
CryptoKey secret;
if (!key_server->get_secret(entity_name, secret)) {
ldout(cct, 0) << "couldn't find entity name: " << entity_name << dendl;
ret = -EPERM;
break;
}
if (!server_challenge) {
ret = -EPERM;
break;
}
uint64_t expected_key;
std::string error;
cephx_calc_client_server_challenge(cct, secret, server_challenge,
req.client_challenge, &expected_key, error);
if (!error.empty()) {
ldout(cct, 0) << " cephx_calc_client_server_challenge error: " << error << dendl;
ret = -EPERM;
break;
}
ldout(cct, 20) << " checking key: req.key=" << hex << req.key
<< " expected_key=" << expected_key << dec << dendl;
if (req.key != expected_key) {
ldout(cct, 0) << " unexpected key: req.key=" << hex << req.key
<< " expected_key=" << expected_key << dec << dendl;
ret = -EPERM;
break;
}
CryptoKey session_key;
CephXSessionAuthInfo info;
bool should_enc_ticket = false;
EntityAuth eauth;
if (! key_server->get_auth(entity_name, eauth)) {
ret = -EPERM;
break;
}
CephXServiceTicketInfo old_ticket_info;
if (cephx_decode_ticket(cct, key_server, CEPH_ENTITY_TYPE_AUTH,
req.old_ticket, old_ticket_info)) {
global_id = old_ticket_info.ticket.global_id;
ldout(cct, 10) << "decoded old_ticket with global_id=" << global_id << dendl;
should_enc_ticket = true;
}
info.ticket.init_timestamps(ceph_clock_now(), cct->_conf->auth_mon_ticket_ttl);
info.ticket.name = entity_name;
info.ticket.global_id = global_id;
info.ticket.auid = eauth.auid;
info.validity += cct->_conf->auth_mon_ticket_ttl;
if (auid) *auid = eauth.auid;
key_server->generate_secret(session_key);
info.session_key = session_key;
info.service_id = CEPH_ENTITY_TYPE_AUTH;
if (!key_server->get_service_secret(CEPH_ENTITY_TYPE_AUTH, info.service_secret, info.secret_id)) {
ldout(cct, 0) << " could not get service secret for auth subsystem" << dendl;
ret = -EIO;
break;
}
vector<CephXSessionAuthInfo> info_vec;
info_vec.push_back(info);
build_cephx_response_header(cephx_header.request_type, 0, result_bl);
if (!cephx_build_service_ticket_reply(cct, eauth.key, info_vec, should_enc_ticket,
old_ticket_info.session_key, result_bl)) {
ret = -EIO;
}
if (!key_server->get_service_caps(entity_name, CEPH_ENTITY_TYPE_MON, caps)) {
ldout(cct, 0) << " could not get mon caps for " << entity_name << dendl;
ret = -EACCES;
} else {
char *caps_str = caps.caps.c_str();
if (!caps_str || !caps_str[0]) {
ldout(cct,0) << "mon caps null for " << entity_name << dendl;
ret = -EACCES;
}
}
}
break;
case CEPHX_GET_PRINCIPAL_SESSION_KEY:
{
ldout(cct, 10) << "handle_request get_principal_session_key" << dendl;
bufferlist tmp_bl;
CephXServiceTicketInfo auth_ticket_info;
if (!cephx_verify_authorizer(cct, key_server, indata, auth_ticket_info, tmp_bl)) {
ret = -EPERM;
break;
}
CephXServiceTicketRequest ticket_req;
::decode(ticket_req, indata);
ldout(cct, 10) << " ticket_req.keys = " << ticket_req.keys << dendl;
ret = 0;
vector<CephXSessionAuthInfo> info_vec;
int found_services = 0;
int service_err = 0;
for (uint32_t service_id = 1; service_id <= ticket_req.keys;
service_id <<= 1) {
if (ticket_req.keys & service_id) {
ldout(cct, 10) << " adding key for service "
<< ceph_entity_type_name(service_id) << dendl;
CephXSessionAuthInfo info;
int r = key_server->build_session_auth_info(service_id,
auth_ticket_info, info);
// tolerate missing MGR rotating key for the purposes of upgrades.
if (r < 0) {
ldout(cct, 10) << " missing key for service "
<< ceph_entity_type_name(service_id) << dendl;
service_err = r;
continue;
}
info.validity += cct->_conf->auth_service_ticket_ttl;
info_vec.push_back(info);
++found_services;
}
}
if (!found_services && service_err) {
ldout(cct, 10) << __func__ << " did not find any service keys" << dendl;
ret = service_err;
}
CryptoKey no_key;
build_cephx_response_header(cephx_header.request_type, ret, result_bl);
cephx_build_service_ticket_reply(cct, auth_ticket_info.session_key, info_vec, false, no_key, result_bl);
}
break;
case CEPHX_GET_ROTATING_KEY:
{
ldout(cct, 10) << "handle_request getting rotating secret for " << entity_name << dendl;
build_cephx_response_header(cephx_header.request_type, 0, result_bl);
if (!key_server->get_rotating_encrypted(entity_name, result_bl)) {
ret = -EPERM;
break;
}
}
break;
default:
ldout(cct, 10) << "handle_request unknown op " << cephx_header.request_type << dendl;
return -EINVAL;
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool AuthNoneAuthorizeHandler::verify_authorizer(CephContext *cct, KeyStore *keys,
bufferlist& authorizer_data, bufferlist& authorizer_reply,
EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info, CryptoKey& session_key,
uint64_t *auid)
{
bufferlist::iterator iter = authorizer_data.begin();
try {
__u8 struct_v = 1;
::decode(struct_v, iter);
::decode(entity_name, iter);
::decode(global_id, iter);
} catch (const buffer::error &err) {
ldout(cct, 0) << "AuthNoneAuthorizeHandle::verify_authorizer() failed to decode" << dendl;
return false;
}
caps_info.allow_all = true;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool ms_verify_authorizer(Connection *con, int peer_type,
int protocol, bufferlist& authorizer,
bufferlist& authorizer_reply,
bool& isvalid, CryptoKey& session_key) override {
/* always succeed */
isvalid = true;
return true;
}; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool SimpleMessenger::verify_authorizer(Connection *con, int peer_type,
int protocol, bufferlist& authorizer, bufferlist& authorizer_reply,
bool& isvalid,CryptoKey& session_key)
{
return ms_deliver_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply, isvalid,session_key);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool ms_deliver_verify_authorizer(Connection *con, int peer_type,
int protocol, bufferlist& authorizer, bufferlist& authorizer_reply,
bool& isvalid, CryptoKey& session_key) {
for (list<Dispatcher*>::iterator p = dispatchers.begin();
p != dispatchers.end();
++p) {
if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply, isvalid, session_key))
return true;
}
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool CephxAuthorizeHandler::verify_authorizer(CephContext *cct, KeyStore *keys,
bufferlist& authorizer_data, bufferlist& authorizer_reply,
EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info, CryptoKey& session_key, uint64_t *auid)
{
bufferlist::iterator iter = authorizer_data.begin();
if (!authorizer_data.length()) {
ldout(cct, 1) << "verify authorizer, authorizer_data.length()=0" << dendl;
return false;
}
CephXServiceTicketInfo auth_ticket_info;
bool isvalid = cephx_verify_authorizer(cct, keys, iter, auth_ticket_info, authorizer_reply);
if (isvalid) {
caps_info = auth_ticket_info.ticket.caps;
entity_name = auth_ticket_info.ticket.name;
global_id = auth_ticket_info.ticket.global_id;
session_key = auth_ticket_info.session_key;
if (auid) *auid = auth_ticket_info.ticket.auid;
}
return isvalid;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CephXAuthorizer *CephXTicketHandler::build_authorizer(uint64_t global_id) const
{
CephXAuthorizer *a = new CephXAuthorizer(cct);
a->session_key = session_key;
a->nonce = ((uint64_t)rand() << 32) + rand();
__u8 authorizer_v = 1;
::encode(authorizer_v, a->bl);
::encode(global_id, a->bl);
::encode(service_id, a->bl);
::encode(ticket, a->bl);
CephXAuthorize msg;
msg.nonce = a->nonce;
std::string error;
if (encode_encrypt(cct, msg, session_key, a->bl, error)) {
ldout(cct, 0) << "failed to encrypt authorizer: " << error << dendl;
delete a;
return 0;
}
return a;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool ms_verify_authorizer(Connection *con, int peer_type, int protocol,
bufferlist& authorizer, bufferlist& authorizer_reply,
bool& isvalid, CryptoKey& session_key) override {
isvalid = true;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool ms_verify_authorizer(Connection *con, int peer_type, int protocol,
bufferlist& authorizer, bufferlist& authorizer_reply,
bool& isvalid, CryptoKey& session_key) override {
isvalid = true;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool MDSDaemon::ms_verify_authorizer(Connection *con, int peer_type,
int protocol, bufferlist& authorizer_data, bufferlist& authorizer_reply,
bool& is_valid, CryptoKey& session_key)
{
Mutex::Locker l(mds_lock);
if (stopping) {
return false;
}
if (beacon.get_want_state() == CEPH_MDS_STATE_DNE)
return false;
AuthAuthorizeHandler *authorize_handler = 0;
switch (peer_type) {
case CEPH_ENTITY_TYPE_MDS:
authorize_handler = authorize_handler_cluster_registry->get_handler(protocol);
break;
default:
authorize_handler = authorize_handler_service_registry->get_handler(protocol);
}
if (!authorize_handler) {
dout(0) << "No AuthAuthorizeHandler found for protocol " << protocol << dendl;
is_valid = false;
return true;
}
AuthCapsInfo caps_info;
EntityName name;
uint64_t global_id;
RotatingKeyRing *keys = monc->rotating_secrets.get();
if (keys) {
is_valid = authorize_handler->verify_authorizer(
cct, keys,
authorizer_data, authorizer_reply, name, global_id, caps_info,
session_key);
} else {
dout(10) << __func__ << " no rotating_keys (yet), denied" << dendl;
is_valid = false;
}
if (is_valid) {
entity_name_t n(con->get_peer_type(), global_id);
// We allow connections and assign Session instances to connections
// even if we have not been assigned a rank, because clients with
// "allow *" are allowed to connect and do 'tell' operations before
// we have a rank.
Session *s = NULL;
if (mds_rank) {
// If we do hold a rank, see if this is an existing client establishing
// a new connection, rather than a new client
s = mds_rank->sessionmap.get_session(n);
}
// Wire up a Session* to this connection
// It doesn't go into a SessionMap instance until it sends an explicit
// request to open a session (initial state of Session is `closed`)
if (!s) {
s = new Session;
s->info.auth_name = name;
s->info.inst.addr = con->get_peer_addr();
s->info.inst.name = n;
dout(10) << " new session " << s << " for " << s->info.inst << " con " << con << dendl;
con->set_priv(s);
s->connection = con;
} else {
dout(10) << " existing session " << s << " for " << s->info.inst << " existing con " << s->connection
<< ", new/authorizing con " << con << dendl;
con->set_priv(s->get());
// Wait until we fully accept the connection before setting
// s->connection. In particular, if there are multiple incoming
// connection attempts, they will all get their authorizer
// validated, but some of them may "lose the race" and get
// dropped. We only want to consider the winner(s). See
// ms_handle_accept(). This is important for Sessions we replay
// from the journal on recovery that don't have established
// messenger state; we want the con from only the winning
// connect attempt(s). (Normal reconnects that don't follow MDS
// recovery are reconnected to the existing con by the
// messenger.)
}
if (caps_info.allow_all) {
// Flag for auth providers that don't provide cap strings
s->auth_caps.set_allow_all();
} else {
bufferlist::iterator p = caps_info.caps.begin();
string auth_cap_str;
try {
::decode(auth_cap_str, p);
dout(10) << __func__ << ": parsing auth_cap_str='" << auth_cap_str << "'" << dendl;
std::ostringstream errstr;
if (!s->auth_caps.parse(g_ceph_context, auth_cap_str, &errstr)) {
dout(1) << __func__ << ": auth cap parse error: " << errstr.str()
<< " parsing '" << auth_cap_str << "'" << dendl;
clog->warn() << name << " mds cap '" << auth_cap_str
<< "' does not parse: " << errstr.str();
is_valid = false;
}
} catch (buffer::error& e) {
// Assume legacy auth, defaults to:
// * permit all filesystem ops
// * permit no `tell` ops
dout(1) << __func__ << ": cannot decode auth caps bl of length " << caps_info.caps.length() << dendl;
is_valid = false;
}
}
}
return true; // we made a decision (see is_valid)
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide 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 Pipe::accept()
{
ldout(msgr->cct,10) << "accept" << dendl;
assert(pipe_lock.is_locked());
assert(state == STATE_ACCEPTING);
pipe_lock.Unlock();
// vars
bufferlist addrs;
entity_addr_t socket_addr;
socklen_t len;
int r;
char banner[strlen(CEPH_BANNER)+1];
bufferlist addrbl;
ceph_msg_connect connect;
ceph_msg_connect_reply reply;
Pipe *existing = 0;
bufferptr bp;
bufferlist authorizer, authorizer_reply;
bool authorizer_valid;
uint64_t feat_missing;
bool replaced = false;
// this variable denotes if the connection attempt from peer is a hard
// reset or not, it is true if there is an existing connection and the
// connection sequence from peer is equal to zero
bool is_reset_from_peer = false;
CryptoKey session_key;
int removed; // single-use down below
// this should roughly mirror pseudocode at
// http://ceph.com/wiki/Messaging_protocol
int reply_tag = 0;
uint64_t existing_seq = -1;
// used for reading in the remote acked seq on connect
uint64_t newly_acked_seq = 0;
recv_reset();
set_socket_options();
// announce myself.
r = tcp_write(CEPH_BANNER, strlen(CEPH_BANNER));
if (r < 0) {
ldout(msgr->cct,10) << "accept couldn't write banner" << dendl;
goto fail_unlocked;
}
// and my addr
::encode(msgr->my_inst.addr, addrs, 0); // legacy
port = msgr->my_inst.addr.get_port();
// and peer's socket addr (they might not know their ip)
sockaddr_storage ss;
len = sizeof(ss);
r = ::getpeername(sd, (sockaddr*)&ss, &len);
if (r < 0) {
ldout(msgr->cct,0) << "accept failed to getpeername " << cpp_strerror(errno) << dendl;
goto fail_unlocked;
}
socket_addr.set_sockaddr((sockaddr*)&ss);
::encode(socket_addr, addrs, 0); // legacy
r = tcp_write(addrs.c_str(), addrs.length());
if (r < 0) {
ldout(msgr->cct,10) << "accept couldn't write my+peer addr" << dendl;
goto fail_unlocked;
}
ldout(msgr->cct,1) << "accept sd=" << sd << " " << socket_addr << dendl;
// identify peer
if (tcp_read(banner, strlen(CEPH_BANNER)) < 0) {
ldout(msgr->cct,10) << "accept couldn't read banner" << dendl;
goto fail_unlocked;
}
if (memcmp(banner, CEPH_BANNER, strlen(CEPH_BANNER))) {
banner[strlen(CEPH_BANNER)] = 0;
ldout(msgr->cct,1) << "accept peer sent bad banner '" << banner << "' (should be '" << CEPH_BANNER << "')" << dendl;
goto fail_unlocked;
}
{
bufferptr tp(sizeof(ceph_entity_addr));
addrbl.push_back(std::move(tp));
}
if (tcp_read(addrbl.c_str(), addrbl.length()) < 0) {
ldout(msgr->cct,10) << "accept couldn't read peer_addr" << dendl;
goto fail_unlocked;
}
{
bufferlist::iterator ti = addrbl.begin();
::decode(peer_addr, ti);
}
ldout(msgr->cct,10) << "accept peer addr is " << peer_addr << dendl;
if (peer_addr.is_blank_ip()) {
// peer apparently doesn't know what ip they have; figure it out for them.
int port = peer_addr.get_port();
peer_addr.u = socket_addr.u;
peer_addr.set_port(port);
ldout(msgr->cct,0) << "accept peer addr is really " << peer_addr
<< " (socket is " << socket_addr << ")" << dendl;
}
set_peer_addr(peer_addr); // so that connection_state gets set up
while (1) {
if (tcp_read((char*)&connect, sizeof(connect)) < 0) {
ldout(msgr->cct,10) << "accept couldn't read connect" << dendl;
goto fail_unlocked;
}
authorizer.clear();
if (connect.authorizer_len) {
bp = buffer::create(connect.authorizer_len);
if (tcp_read(bp.c_str(), connect.authorizer_len) < 0) {
ldout(msgr->cct,10) << "accept couldn't read connect authorizer" << dendl;
goto fail_unlocked;
}
authorizer.push_back(std::move(bp));
authorizer_reply.clear();
}
ldout(msgr->cct,20) << "accept got peer connect_seq " << connect.connect_seq
<< " global_seq " << connect.global_seq
<< dendl;
msgr->lock.Lock(); // FIXME
pipe_lock.Lock();
if (msgr->dispatch_queue.stop)
goto shutting_down;
if (state != STATE_ACCEPTING) {
goto shutting_down;
}
// note peer's type, flags
set_peer_type(connect.host_type);
policy = msgr->get_policy(connect.host_type);
ldout(msgr->cct,10) << "accept of host_type " << connect.host_type
<< ", policy.lossy=" << policy.lossy
<< " policy.server=" << policy.server
<< " policy.standby=" << policy.standby
<< " policy.resetcheck=" << policy.resetcheck
<< dendl;
memset(&reply, 0, sizeof(reply));
reply.protocol_version = msgr->get_proto_version(peer_type, false);
msgr->lock.Unlock();
// mismatch?
ldout(msgr->cct,10) << "accept my proto " << reply.protocol_version
<< ", their proto " << connect.protocol_version << dendl;
if (connect.protocol_version != reply.protocol_version) {
reply.tag = CEPH_MSGR_TAG_BADPROTOVER;
goto reply;
}
// require signatures for cephx?
if (connect.authorizer_protocol == CEPH_AUTH_CEPHX) {
if (peer_type == CEPH_ENTITY_TYPE_OSD ||
peer_type == CEPH_ENTITY_TYPE_MDS ||
peer_type == CEPH_ENTITY_TYPE_MGR) {
if (msgr->cct->_conf->cephx_require_signatures ||
msgr->cct->_conf->cephx_cluster_require_signatures) {
ldout(msgr->cct,10) << "using cephx, requiring MSG_AUTH feature bit for cluster" << dendl;
policy.features_required |= CEPH_FEATURE_MSG_AUTH;
}
if (msgr->cct->_conf->cephx_require_version >= 2 ||
msgr->cct->_conf->cephx_cluster_require_version >= 2) {
ldout(msgr->cct,10) << "using cephx, requiring cephx v2 feature bit for cluster" << dendl;
policy.features_required |= CEPH_FEATUREMASK_CEPHX_V2;
}
} else {
if (msgr->cct->_conf->cephx_require_signatures ||
msgr->cct->_conf->cephx_service_require_signatures) {
ldout(msgr->cct,10) << "using cephx, requiring MSG_AUTH feature bit for service" << dendl;
policy.features_required |= CEPH_FEATURE_MSG_AUTH;
}
if (msgr->cct->_conf->cephx_require_version >= 2 ||
msgr->cct->_conf->cephx_service_require_version >= 2) {
ldout(msgr->cct,10) << "using cephx, requiring cephx v2 feature bit for cluster" << dendl;
policy.features_required |= CEPH_FEATUREMASK_CEPHX_V2;
}
}
}
feat_missing = policy.features_required & ~(uint64_t)connect.features;
if (feat_missing) {
ldout(msgr->cct,1) << "peer missing required features " << std::hex << feat_missing << std::dec << dendl;
reply.tag = CEPH_MSGR_TAG_FEATURES;
goto reply;
}
// Check the authorizer. If not good, bail out.
pipe_lock.Unlock();
if (!msgr->verify_authorizer(connection_state.get(), peer_type, connect.authorizer_protocol, authorizer,
authorizer_reply, authorizer_valid, session_key) ||
!authorizer_valid) {
ldout(msgr->cct,0) << "accept: got bad authorizer" << dendl;
pipe_lock.Lock();
if (state != STATE_ACCEPTING)
goto shutting_down_msgr_unlocked;
reply.tag = CEPH_MSGR_TAG_BADAUTHORIZER;
session_security.reset();
goto reply;
}
// We've verified the authorizer for this pipe, so set up the session security structure. PLR
ldout(msgr->cct,10) << "accept: setting up session_security." << dendl;
retry_existing_lookup:
msgr->lock.Lock();
pipe_lock.Lock();
if (msgr->dispatch_queue.stop)
goto shutting_down;
if (state != STATE_ACCEPTING)
goto shutting_down;
// existing?
existing = msgr->_lookup_pipe(peer_addr);
if (existing) {
existing->pipe_lock.Lock(true); // skip lockdep check (we are locking a second Pipe here)
if (existing->reader_dispatching) {
/** we need to wait, or we can deadlock if downstream
* fast_dispatchers are (naughtily!) waiting on resources
* held by somebody trying to make use of the SimpleMessenger lock.
* So drop locks, wait, and retry. It just looks like a slow network
* to everybody else.
*
* We take a ref to existing here since it might get reaped before we
* wake up (see bug #15870). We can be confident that it lived until
* locked it since we held the msgr lock from _lookup_pipe through to
* locking existing->lock and checking reader_dispatching.
*/
existing->get();
pipe_lock.Unlock();
msgr->lock.Unlock();
existing->notify_on_dispatch_done = true;
while (existing->reader_dispatching)
existing->cond.Wait(existing->pipe_lock);
existing->pipe_lock.Unlock();
existing->put();
existing = nullptr;
goto retry_existing_lookup;
}
if (connect.global_seq < existing->peer_global_seq) {
ldout(msgr->cct,10) << "accept existing " << existing << ".gseq " << existing->peer_global_seq
<< " > " << connect.global_seq << ", RETRY_GLOBAL" << dendl;
reply.tag = CEPH_MSGR_TAG_RETRY_GLOBAL;
reply.global_seq = existing->peer_global_seq; // so we can send it below..
existing->pipe_lock.Unlock();
msgr->lock.Unlock();
goto reply;
} else {
ldout(msgr->cct,10) << "accept existing " << existing << ".gseq " << existing->peer_global_seq
<< " <= " << connect.global_seq << ", looks ok" << dendl;
}
if (existing->policy.lossy) {
ldout(msgr->cct,0) << "accept replacing existing (lossy) channel (new one lossy="
<< policy.lossy << ")" << dendl;
existing->was_session_reset();
goto replace;
}
ldout(msgr->cct,0) << "accept connect_seq " << connect.connect_seq
<< " vs existing " << existing->connect_seq
<< " state " << existing->get_state_name() << dendl;
if (connect.connect_seq == 0 && existing->connect_seq > 0) {
ldout(msgr->cct,0) << "accept peer reset, then tried to connect to us, replacing" << dendl;
// this is a hard reset from peer
is_reset_from_peer = true;
if (policy.resetcheck)
existing->was_session_reset(); // this resets out_queue, msg_ and connect_seq #'s
goto replace;
}
if (connect.connect_seq < existing->connect_seq) {
// old attempt, or we sent READY but they didn't get it.
ldout(msgr->cct,10) << "accept existing " << existing << ".cseq " << existing->connect_seq
<< " > " << connect.connect_seq << ", RETRY_SESSION" << dendl;
goto retry_session;
}
if (connect.connect_seq == existing->connect_seq) {
// if the existing connection successfully opened, and/or
// subsequently went to standby, then the peer should bump
// their connect_seq and retry: this is not a connection race
// we need to resolve here.
if (existing->state == STATE_OPEN ||
existing->state == STATE_STANDBY) {
ldout(msgr->cct,10) << "accept connection race, existing " << existing
<< ".cseq " << existing->connect_seq
<< " == " << connect.connect_seq
<< ", OPEN|STANDBY, RETRY_SESSION" << dendl;
goto retry_session;
}
// connection race?
if (peer_addr < msgr->my_inst.addr ||
existing->policy.server) {
// incoming wins
ldout(msgr->cct,10) << "accept connection race, existing " << existing << ".cseq " << existing->connect_seq
<< " == " << connect.connect_seq << ", or we are server, replacing my attempt" << dendl;
if (!(existing->state == STATE_CONNECTING ||
existing->state == STATE_WAIT))
lderr(msgr->cct) << "accept race bad state, would replace, existing="
<< existing->get_state_name()
<< " " << existing << ".cseq=" << existing->connect_seq
<< " == " << connect.connect_seq
<< dendl;
assert(existing->state == STATE_CONNECTING ||
existing->state == STATE_WAIT);
goto replace;
} else {
// our existing outgoing wins
ldout(msgr->cct,10) << "accept connection race, existing " << existing << ".cseq " << existing->connect_seq
<< " == " << connect.connect_seq << ", sending WAIT" << dendl;
assert(peer_addr > msgr->my_inst.addr);
if (!(existing->state == STATE_CONNECTING))
lderr(msgr->cct) << "accept race bad state, would send wait, existing="
<< existing->get_state_name()
<< " " << existing << ".cseq=" << existing->connect_seq
<< " == " << connect.connect_seq
<< dendl;
assert(existing->state == STATE_CONNECTING);
// make sure our outgoing connection will follow through
existing->_send_keepalive();
reply.tag = CEPH_MSGR_TAG_WAIT;
existing->pipe_lock.Unlock();
msgr->lock.Unlock();
goto reply;
}
}
assert(connect.connect_seq > existing->connect_seq);
assert(connect.global_seq >= existing->peer_global_seq);
if (policy.resetcheck && // RESETSESSION only used by servers; peers do not reset each other
existing->connect_seq == 0) {
ldout(msgr->cct,0) << "accept we reset (peer sent cseq " << connect.connect_seq
<< ", " << existing << ".cseq = " << existing->connect_seq
<< "), sending RESETSESSION" << dendl;
reply.tag = CEPH_MSGR_TAG_RESETSESSION;
msgr->lock.Unlock();
existing->pipe_lock.Unlock();
goto reply;
}
// reconnect
ldout(msgr->cct,10) << "accept peer sent cseq " << connect.connect_seq
<< " > " << existing->connect_seq << dendl;
goto replace;
} // existing
else if (connect.connect_seq > 0) {
// we reset, and they are opening a new session
ldout(msgr->cct,0) << "accept we reset (peer sent cseq " << connect.connect_seq << "), sending RESETSESSION" << dendl;
msgr->lock.Unlock();
reply.tag = CEPH_MSGR_TAG_RESETSESSION;
goto reply;
} else {
// new session
ldout(msgr->cct,10) << "accept new session" << dendl;
existing = NULL;
goto open;
}
ceph_abort();
retry_session:
assert(existing->pipe_lock.is_locked());
assert(pipe_lock.is_locked());
reply.tag = CEPH_MSGR_TAG_RETRY_SESSION;
reply.connect_seq = existing->connect_seq + 1;
existing->pipe_lock.Unlock();
msgr->lock.Unlock();
goto reply;
reply:
assert(pipe_lock.is_locked());
reply.features = ((uint64_t)connect.features & policy.features_supported) | policy.features_required;
reply.authorizer_len = authorizer_reply.length();
pipe_lock.Unlock();
r = tcp_write((char*)&reply, sizeof(reply));
if (r < 0)
goto fail_unlocked;
if (reply.authorizer_len) {
r = tcp_write(authorizer_reply.c_str(), authorizer_reply.length());
if (r < 0)
goto fail_unlocked;
}
}
replace:
assert(existing->pipe_lock.is_locked());
assert(pipe_lock.is_locked());
// if it is a hard reset from peer, we don't need a round-trip to negotiate in/out sequence
if ((connect.features & CEPH_FEATURE_RECONNECT_SEQ) && !is_reset_from_peer) {
reply_tag = CEPH_MSGR_TAG_SEQ;
existing_seq = existing->in_seq;
}
ldout(msgr->cct,10) << "accept replacing " << existing << dendl;
existing->stop();
existing->unregister_pipe();
replaced = true;
if (existing->policy.lossy) {
// disconnect from the Connection
assert(existing->connection_state);
if (existing->connection_state->clear_pipe(existing))
msgr->dispatch_queue.queue_reset(existing->connection_state.get());
} else {
// queue a reset on the new connection, which we're dumping for the old
msgr->dispatch_queue.queue_reset(connection_state.get());
// drop my Connection, and take a ref to the existing one. do not
// clear existing->connection_state, since read_message and
// write_message both dereference it without pipe_lock.
connection_state = existing->connection_state;
// make existing Connection reference us
connection_state->reset_pipe(this);
if (existing->delay_thread) {
existing->delay_thread->steal_for_pipe(this);
delay_thread = existing->delay_thread;
existing->delay_thread = NULL;
delay_thread->flush();
}
// steal incoming queue
uint64_t replaced_conn_id = conn_id;
conn_id = existing->conn_id;
existing->conn_id = replaced_conn_id;
// reset the in_seq if this is a hard reset from peer,
// otherwise we respect our original connection's value
in_seq = is_reset_from_peer ? 0 : existing->in_seq;
in_seq_acked = in_seq;
// steal outgoing queue and out_seq
existing->requeue_sent();
out_seq = existing->out_seq;
ldout(msgr->cct,10) << "accept re-queuing on out_seq " << out_seq << " in_seq " << in_seq << dendl;
for (map<int, list<Message*> >::iterator p = existing->out_q.begin();
p != existing->out_q.end();
++p)
out_q[p->first].splice(out_q[p->first].begin(), p->second);
}
existing->stop_and_wait();
existing->pipe_lock.Unlock();
open:
// open
assert(pipe_lock.is_locked());
connect_seq = connect.connect_seq + 1;
peer_global_seq = connect.global_seq;
assert(state == STATE_ACCEPTING);
state = STATE_OPEN;
ldout(msgr->cct,10) << "accept success, connect_seq = " << connect_seq << ", sending READY" << dendl;
// send READY reply
reply.tag = (reply_tag ? reply_tag : CEPH_MSGR_TAG_READY);
reply.features = policy.features_supported;
reply.global_seq = msgr->get_global_seq();
reply.connect_seq = connect_seq;
reply.flags = 0;
reply.authorizer_len = authorizer_reply.length();
if (policy.lossy)
reply.flags = reply.flags | CEPH_MSG_CONNECT_LOSSY;
connection_state->set_features((uint64_t)reply.features & (uint64_t)connect.features);
ldout(msgr->cct,10) << "accept features " << connection_state->get_features() << dendl;
session_security.reset(
get_auth_session_handler(msgr->cct,
connect.authorizer_protocol,
session_key,
connection_state->get_features()));
// notify
msgr->dispatch_queue.queue_accept(connection_state.get());
msgr->ms_deliver_handle_fast_accept(connection_state.get());
// ok!
if (msgr->dispatch_queue.stop)
goto shutting_down;
removed = msgr->accepting_pipes.erase(this);
assert(removed == 1);
register_pipe();
msgr->lock.Unlock();
pipe_lock.Unlock();
r = tcp_write((char*)&reply, sizeof(reply));
if (r < 0) {
goto fail_registered;
}
if (reply.authorizer_len) {
r = tcp_write(authorizer_reply.c_str(), authorizer_reply.length());
if (r < 0) {
goto fail_registered;
}
}
if (reply_tag == CEPH_MSGR_TAG_SEQ) {
if (tcp_write((char*)&existing_seq, sizeof(existing_seq)) < 0) {
ldout(msgr->cct,2) << "accept write error on in_seq" << dendl;
goto fail_registered;
}
if (tcp_read((char*)&newly_acked_seq, sizeof(newly_acked_seq)) < 0) {
ldout(msgr->cct,2) << "accept read error on newly_acked_seq" << dendl;
goto fail_registered;
}
}
pipe_lock.Lock();
discard_requeued_up_to(newly_acked_seq);
if (state != STATE_CLOSED) {
ldout(msgr->cct,10) << "accept starting writer, state " << get_state_name() << dendl;
start_writer();
}
ldout(msgr->cct,20) << "accept done" << dendl;
maybe_start_delay_thread();
return 0; // success.
fail_registered:
ldout(msgr->cct, 10) << "accept fault after register" << dendl;
if (msgr->cct->_conf->ms_inject_internal_delays) {
ldout(msgr->cct, 10) << " sleep for " << msgr->cct->_conf->ms_inject_internal_delays << dendl;
utime_t t;
t.set_from_double(msgr->cct->_conf->ms_inject_internal_delays);
t.sleep();
}
fail_unlocked:
pipe_lock.Lock();
if (state != STATE_CLOSED) {
bool queued = is_queued();
ldout(msgr->cct, 10) << " queued = " << (int)queued << dendl;
if (queued) {
state = policy.server ? STATE_STANDBY : STATE_CONNECTING;
} else if (replaced) {
state = STATE_STANDBY;
} else {
state = STATE_CLOSED;
state_closed = true;
}
fault();
if (queued || replaced)
start_writer();
}
return -1;
shutting_down:
msgr->lock.Unlock();
shutting_down_msgr_unlocked:
assert(pipe_lock.is_locked());
if (msgr->cct->_conf->ms_inject_internal_delays) {
ldout(msgr->cct, 10) << " sleep for " << msgr->cct->_conf->ms_inject_internal_delays << dendl;
utime_t t;
t.set_from_double(msgr->cct->_conf->ms_inject_internal_delays);
t.sleep();
}
state = STATE_CLOSED;
state_closed = true;
fault();
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge
Allow the accepting side of a connection to reject an initial authorizer
with a random challenge. The connecting side then has to respond with an
updated authorizer proving they are able to decrypt the service's challenge
and that the new authorizer was produced for this specific connection
instance.
The accepting side requires this challenge and response unconditionally
if the client side advertises they have the feature bit. Servers wishing
to require this improved level of authentication simply have to require
the appropriate feature.
Signed-off-by: Sage Weil <[email protected]>
(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)
# Conflicts:
# src/auth/Auth.h
# src/auth/cephx/CephxProtocol.cc
# src/auth/cephx/CephxProtocol.h
# src/auth/none/AuthNoneProtocol.h
# src/msg/Dispatcher.h
# src/msg/async/AsyncConnection.cc
- const_iterator
- ::decode vs decode
- AsyncConnection ctor arg noise
- get_random_bytes(), not cct->random()'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gxps_images_create_from_tiff (GXPSArchive *zip,
const gchar *image_uri,
GError **error)
{
#ifdef HAVE_LIBTIFF
TIFF *tiff;
TiffBuffer buffer;
GXPSImage *image;
gint width, height;
guint16 res_unit;
float res_x, res_y;
gint stride;
guchar *data;
guchar *p;
if (!gxps_archive_read_entry (zip, image_uri,
&buffer.buffer,
&buffer.buffer_len,
error)) {
g_set_error (error,
GXPS_ERROR,
GXPS_ERROR_SOURCE_NOT_FOUND,
"Image source %s not found in archive",
image_uri);
return NULL;
}
buffer.pos = 0;
_tiff_push_handlers ();
tiff = TIFFClientOpen ("libgxps-tiff", "r", &buffer,
_tiff_read,
_tiff_write,
_tiff_seek,
_tiff_close,
_tiff_size,
_tiff_map_file,
_tiff_unmap_file);
if (!tiff || _tiff_error) {
fill_tiff_error (error, image_uri);
if (tiff)
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
return NULL;
}
if (!TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width) || _tiff_error) {
fill_tiff_error (error, image_uri);
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
return NULL;
}
if (!TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height) || _tiff_error) {
fill_tiff_error (error, image_uri);
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
return NULL;
}
if (width <= 0 || height <= 0) {
fill_tiff_error (error, image_uri);
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
return NULL;
}
image = g_slice_new (GXPSImage);
image->surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24,
width, height);
image->res_x = 96;
image->res_y = 96;
if (!TIFFGetField (tiff, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = 0;
if (TIFFGetField (tiff, TIFFTAG_XRESOLUTION, &res_x)) {
if (res_unit == 2) { /* inches */
image->res_x = res_x;
} else if (res_unit == 3) { /* centimeters */
image->res_x = res_x * CENTIMETERS_PER_INCH;
}
}
if (TIFFGetField (tiff, TIFFTAG_YRESOLUTION, &res_y)) {
if (res_unit == 2) { /* inches */
image->res_y = res_y;
} else if (res_unit == 3) { /* centimeters */
image->res_y = res_y * CENTIMETERS_PER_INCH;
}
}
if (cairo_surface_status (image->surface)) {
g_set_error (error,
GXPS_ERROR,
GXPS_ERROR_IMAGE,
"Error loading TIFF image %s: %s",
image_uri,
cairo_status_to_string (cairo_surface_status (image->surface)));
gxps_image_free (image);
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
return NULL;
}
data = cairo_image_surface_get_data (image->surface);
if (!TIFFReadRGBAImageOriented (tiff, width, height,
(uint32 *)data,
ORIENTATION_TOPLEFT, 1) || _tiff_error) {
fill_tiff_error (error, image_uri);
gxps_image_free (image);
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
return NULL;
}
TIFFClose (tiff);
_tiff_pop_handlers ();
g_free (buffer.buffer);
stride = cairo_image_surface_get_stride (image->surface);
p = data;
while (p < data + (height * stride)) {
guint32 *pixel = (guint32 *)p;
guint8 r = TIFFGetR (*pixel);
guint8 g = TIFFGetG (*pixel);
guint8 b = TIFFGetB (*pixel);
guint8 a = TIFFGetA (*pixel);
*pixel = (a << 24) | (r << 16) | (g << 8) | b;
p += 4;
}
cairo_surface_mark_dirty (image->surface);
return image;
#else
return NULL;
#endif /* #ifdef HAVE_LIBTIFF */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'gxps-archive: Ensure gxps_archive_read_entry() fills the GError in case of failure
And fix the callers to not overwrite the GError.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gxps_archive_read_entry (GXPSArchive *archive,
const gchar *path,
guchar **buffer,
gsize *bytes_read,
GError **error)
{
GInputStream *stream;
gssize entry_size;
gboolean retval;
stream = gxps_archive_open (archive, path);
if (!stream)
/* TODO: Error */
return FALSE;
entry_size = archive_entry_size (GXPS_ARCHIVE_INPUT_STREAM (stream)->entry);
if (entry_size <= 0) {
gssize bytes;
guchar buf[BUFFER_SIZE];
guint buffer_size = BUFFER_SIZE * 4;
/* In some cases, I don't know why, archive_entry_size() returns 0,
* but the entry can be read, so let's try here.
*/
*bytes_read = 0;
*buffer = g_malloc (buffer_size);
do {
bytes = g_input_stream_read (stream, &buf, BUFFER_SIZE, NULL, error);
if (*error != NULL) {
g_free (*buffer);
g_object_unref (stream);
return FALSE;
}
if (*bytes_read + bytes > buffer_size) {
buffer_size += BUFFER_SIZE * 4;
*buffer = g_realloc (*buffer, buffer_size);
}
memcpy (*buffer + *bytes_read, buf, bytes);
*bytes_read += bytes;
} while (bytes > 0);
g_object_unref (stream);
if (*bytes_read == 0) {
/* TODO: Error */
g_free (*buffer);
return FALSE;
}
return TRUE;
}
*buffer = g_malloc (entry_size);
retval = g_input_stream_read_all (stream,
*buffer, entry_size,
bytes_read, NULL,
error);
if (!retval)
g_free (*buffer);
g_object_unref (stream);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'gxps-archive: Ensure gxps_archive_read_entry() fills the GError in case of failure
And fix the callers to not overwrite the GError.'</s> |
<s>[INST] Given the following code containing errors, provide 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 dccp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
const struct dccp_sock *dp = dccp_sk(sk);
const int flags = msg->msg_flags;
const int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
int rc, size;
long timeo;
trace_dccp_probe(sk, len);
if (len > dp->dccps_mss_cache)
return -EMSGSIZE;
lock_sock(sk);
if (dccp_qpolicy_full(sk)) {
rc = -EAGAIN;
goto out_release;
}
timeo = sock_sndtimeo(sk, noblock);
/*
* We have to use sk_stream_wait_connect here to set sk_write_pending,
* so that the trick in dccp_rcv_request_sent_state_process.
*/
/* Wait for a connection to finish. */
if ((1 << sk->sk_state) & ~(DCCPF_OPEN | DCCPF_PARTOPEN))
if ((rc = sk_stream_wait_connect(sk, &timeo)) != 0)
goto out_release;
size = sk->sk_prot->max_header + len;
release_sock(sk);
skb = sock_alloc_send_skb(sk, size, noblock, &rc);
lock_sock(sk);
if (skb == NULL)
goto out_release;
skb_reserve(skb, sk->sk_prot->max_header);
rc = memcpy_from_msg(skb_put(skb, len), msg, len);
if (rc != 0)
goto out_discard;
rc = dccp_msghdr_parse(msg, skb);
if (rc != 0)
goto out_discard;
dccp_qpolicy_push(sk, skb);
/*
* The xmit_timer is set if the TX CCID is rate-based and will expire
* when congestion control permits to release further packets into the
* network. Window-based CCIDs do not use this timer.
*/
if (!timer_pending(&dp->dccps_xmit_timer))
dccp_write_xmit(sk);
out_release:
release_sock(sk);
return rc ? : len;
out_discard:
kfree_skb(skb);
goto out_release;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'dccp: check sk for closed state in dccp_sendmsg()
dccp_disconnect() sets 'dp->dccps_hc_tx_ccid' tx handler to NULL,
therefore if DCCP socket is disconnected and dccp_sendmsg() is
called after it, it will cause a NULL pointer dereference in
dccp_write_xmit().
This crash and the reproducer was reported by syzbot. Looks like
it is reproduced if commit 69c64866ce07 ("dccp: CVE-2017-8824:
use-after-free in DCCP code") is applied.
Reported-by: [email protected]
Signed-off-by: Alexey Kodanev <[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 cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,
unsigned long arg)
{
struct cdrom_changer_info *info;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n");
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return -ENOSYS;
/* cannot select disc or select current disc */
if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)
return media_changed(cdi, 1);
if ((unsigned int)arg >= cdi->capacity)
return -EINVAL;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
ret = cdrom_read_mech_status(cdi, info);
if (!ret)
ret = info->slots[arg].change;
kfree(info);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'cdrom: information leak in cdrom_ioctl_media_changed()
This cast is wrong. "cdi->capacity" is an int and "arg" is an unsigned
long. The way the check is written now, if one of the high 32 bits is
set then we could read outside the info->slots[] array.
This bug is pretty old and it predates git.
Reviewed-by: Christoph Hellwig <[email protected]>
Cc: [email protected]
Signed-off-by: Dan Carpenter <[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 addECSOption(char* packet, const size_t& packetSize, uint16_t* len, const ComboAddress& remote, int stamp)
{
string EDNSRR;
struct dnsheader* dh = (struct dnsheader*) packet;
EDNSSubnetOpts eso;
if(stamp < 0)
eso.source = Netmask(remote);
else {
ComboAddress stamped(remote);
*((char*)&stamped.sin4.sin_addr.s_addr)=stamp;
eso.source = Netmask(stamped);
}
string optRData=makeEDNSSubnetOptsString(eso);
string record;
generateEDNSOption(EDNSOptionCode::ECS, optRData, record);
generateOptRR(record, EDNSRR);
uint16_t arcount = ntohs(dh->arcount);
/* does it fit in the existing buffer? */
if (packetSize - *len > EDNSRR.size()) {
arcount++;
dh->arcount = htons(arcount);
memcpy(packet + *len, EDNSRR.c_str(), EDNSRR.size());
*len += EDNSRR.size();
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'dnsreplay: Bail out on a too small outgoing buffer'</s> |
<s>[INST] Given the following code containing errors, provide 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 ldb_kv_index_dn_attr(struct ldb_module *module,
struct ldb_kv_private *ldb_kv,
const char *attr,
struct ldb_dn *dn,
struct dn_list *list,
enum key_truncation *truncation)
{
struct ldb_context *ldb;
struct ldb_dn *key;
struct ldb_val val;
int ret;
ldb = ldb_module_get_ctx(module);
/* work out the index key from the parent DN */
val.data = (uint8_t *)((uintptr_t)ldb_dn_get_casefold(dn));
val.length = strlen((char *)val.data);
key = ldb_kv_index_key(ldb, ldb_kv, attr, &val, NULL, truncation);
if (!key) {
ldb_oom(ldb);
return LDB_ERR_OPERATIONS_ERROR;
}
ret = ldb_kv_dn_list_load(module, ldb_kv, key, list);
talloc_free(key);
if (ret != LDB_SUCCESS) {
return ret;
}
if (list->count == 0) {
return LDB_ERR_NO_SUCH_OBJECT;
}
return LDB_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 Add NULL check for ldb_dn_get_casefold() in ltdb_index_dn_attr()
Signed-off-by: Andrej Gessel <[email protected]>
Reviewed-by: Douglas Bagnall <[email protected]>
Reviewed-by: Andrew Bartlett <[email protected]>
BUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'</s> |
<s>[INST] Given the following code containing errors, provide 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 ldb_kv_search_dn1(struct ldb_module *module,
struct ldb_dn *dn,
struct ldb_message *msg,
unsigned int unpack_flags)
{
void *data = ldb_module_get_private(module);
struct ldb_kv_private *ldb_kv =
talloc_get_type(data, struct ldb_kv_private);
int ret;
uint8_t guid_key[LDB_KV_GUID_KEY_SIZE];
struct ldb_val key = {
.data = guid_key,
.length = sizeof(guid_key)
};
TALLOC_CTX *tdb_key_ctx = NULL;
if (ldb_kv->cache->GUID_index_attribute == NULL ||
ldb_dn_is_special(dn)) {
tdb_key_ctx = talloc_new(msg);
if (!tdb_key_ctx) {
return ldb_module_oom(module);
}
/* form the key */
key = ldb_kv_key_dn(module, tdb_key_ctx, dn);
if (!key.data) {
TALLOC_FREE(tdb_key_ctx);
return LDB_ERR_OPERATIONS_ERROR;
}
} else {
/*
* Look in the index to find the key for this DN.
*
* the tdb_key memory is allocated above, msg is just
* used for internal memory.
*
*/
ret = ldb_kv_key_dn_from_idx(module, ldb_kv, msg, dn, &key);
if (ret != LDB_SUCCESS) {
return ret;
}
}
ret = ldb_kv_search_key(module, ldb_kv, key, msg, unpack_flags);
TALLOC_FREE(tdb_key_ctx);
if (ret != LDB_SUCCESS) {
return ret;
}
if ((unpack_flags & LDB_UNPACK_DATA_FLAG_NO_DN) == 0) {
if (!msg->dn) {
msg->dn = ldb_dn_copy(msg, dn);
}
if (!msg->dn) {
return LDB_ERR_OPERATIONS_ERROR;
}
}
return LDB_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 ldb_tdb: Check for DN validity in add, rename and search
This ensures we fail with a good error code before an eventual ldb_dn_get_casefold() which
would otherwise fail.
Signed-off-by: Andrew Bartlett <[email protected]>
Reviewed-by: Douglas Bagnall <[email protected]>
BUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'</s> |
<s>[INST] Given the following code containing errors, provide 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 ldb_kv_search(struct ldb_kv_context *ctx)
{
struct ldb_context *ldb;
struct ldb_module *module = ctx->module;
struct ldb_request *req = ctx->req;
void *data = ldb_module_get_private(module);
struct ldb_kv_private *ldb_kv =
talloc_get_type(data, struct ldb_kv_private);
int ret;
ldb = ldb_module_get_ctx(module);
ldb_request_set_state(req, LDB_ASYNC_PENDING);
if (ldb_kv->kv_ops->lock_read(module) != 0) {
return LDB_ERR_OPERATIONS_ERROR;
}
if (ldb_kv_cache_load(module) != 0) {
ldb_kv->kv_ops->unlock_read(module);
return LDB_ERR_OPERATIONS_ERROR;
}
if (req->op.search.tree == NULL) {
ldb_kv->kv_ops->unlock_read(module);
return LDB_ERR_OPERATIONS_ERROR;
}
ctx->tree = req->op.search.tree;
ctx->scope = req->op.search.scope;
ctx->base = req->op.search.base;
ctx->attrs = req->op.search.attrs;
if ((req->op.search.base == NULL) || (ldb_dn_is_null(req->op.search.base) == true)) {
/* Check what we should do with a NULL dn */
switch (req->op.search.scope) {
case LDB_SCOPE_BASE:
ldb_asprintf_errstring(ldb,
"NULL Base DN invalid for a base search");
ret = LDB_ERR_INVALID_DN_SYNTAX;
break;
case LDB_SCOPE_ONELEVEL:
ldb_asprintf_errstring(ldb,
"NULL Base DN invalid for a one-level search");
ret = LDB_ERR_INVALID_DN_SYNTAX;
break;
case LDB_SCOPE_SUBTREE:
default:
/* We accept subtree searches from a NULL base DN, ie over the whole DB */
ret = LDB_SUCCESS;
}
} else if (ldb_dn_is_valid(req->op.search.base) == false) {
/* We don't want invalid base DNs here */
ldb_asprintf_errstring(ldb,
"Invalid Base DN: %s",
ldb_dn_get_linearized(req->op.search.base));
ret = LDB_ERR_INVALID_DN_SYNTAX;
} else if (req->op.search.scope == LDB_SCOPE_BASE) {
/*
* If we are LDB_SCOPE_BASE, do just one search and
* return early. This is critical to ensure we do not
* go into the index code for special DNs, as that
* will try to look up an index record for a special
* record (which doesn't exist).
*/
ret = ldb_kv_search_and_return_base(ldb_kv, ctx);
ldb_kv->kv_ops->unlock_read(module);
return ret;
} else if (ldb_kv->check_base) {
/*
* This database has been marked as
* 'checkBaseOnSearch', so do a spot check of the base
* dn. Also optimise the subsequent filter by filling
* in the ctx->base to be exactly case correct
*/
ret = ldb_kv_search_base(
module, ctx, req->op.search.base, &ctx->base);
if (ret == LDB_ERR_NO_SUCH_OBJECT) {
ldb_asprintf_errstring(ldb,
"No such Base DN: %s",
ldb_dn_get_linearized(req->op.search.base));
}
} else {
/* If we are not checking the base DN life is easy */
ret = LDB_SUCCESS;
}
if (ret == LDB_SUCCESS) {
uint32_t match_count = 0;
ret = ldb_kv_search_indexed(ctx, &match_count);
if (ret == LDB_ERR_NO_SUCH_OBJECT) {
/* Not in the index, therefore OK! */
ret = LDB_SUCCESS;
}
/* Check if we got just a normal error.
* In that case proceed to a full search unless we got a
* callback error */
if (!ctx->request_terminated && ret != LDB_SUCCESS) {
/* Not indexed, so we need to do a full scan */
if (ldb_kv->warn_unindexed ||
ldb_kv->disable_full_db_scan) {
/* useful for debugging when slow performance
* is caused by unindexed searches */
char *expression = ldb_filter_from_tree(ctx, ctx->tree);
ldb_debug(ldb, LDB_DEBUG_ERROR, "ldb FULL SEARCH: %s SCOPE: %s DN: %s",
expression,
req->op.search.scope==LDB_SCOPE_BASE?"base":
req->op.search.scope==LDB_SCOPE_ONELEVEL?"one":
req->op.search.scope==LDB_SCOPE_SUBTREE?"sub":"UNKNOWN",
ldb_dn_get_linearized(req->op.search.base));
talloc_free(expression);
}
if (match_count != 0) {
/* the indexing code gave an error
* after having returned at least one
* entry. This means the indexes are
* corrupt or a database record is
* corrupt. We cannot continue with a
* full search or we may return
* duplicate entries
*/
ldb_kv->kv_ops->unlock_read(module);
return LDB_ERR_OPERATIONS_ERROR;
}
if (ldb_kv->disable_full_db_scan) {
ldb_set_errstring(ldb,
"ldb FULL SEARCH disabled");
ldb_kv->kv_ops->unlock_read(module);
return LDB_ERR_INAPPROPRIATE_MATCHING;
}
ret = ldb_kv_search_full(ctx);
if (ret != LDB_SUCCESS) {
ldb_set_errstring(ldb, "Indexed and full searches both failed!\n");
}
}
}
ldb_kv->kv_ops->unlock_read(module);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 ldb_tdb: Check for DN validity in add, rename and search
This ensures we fail with a good error code before an eventual ldb_dn_get_casefold() which
would otherwise fail.
Signed-off-by: Andrew Bartlett <[email protected]>
Reviewed-by: Douglas Bagnall <[email protected]>
BUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'</s> |
<s>[INST] Given the following code containing errors, provide 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 *etm_setup_aux(int event_cpu, void **pages,
int nr_pages, bool overwrite)
{
int cpu;
cpumask_t *mask;
struct coresight_device *sink;
struct etm_event_data *event_data = NULL;
event_data = alloc_event_data(event_cpu);
if (!event_data)
return NULL;
/*
* In theory nothing prevent tracers in a trace session from being
* associated with different sinks, nor having a sink per tracer. But
* until we have HW with this kind of topology we need to assume tracers
* in a trace session are using the same sink. Therefore go through
* the coresight bus and pick the first enabled sink.
*
* When operated from sysFS users are responsible to enable the sink
* while from perf, the perf tools will do it based on the choice made
* on the cmd line. As such the "enable_sink" flag in sysFS is reset.
*/
sink = coresight_get_enabled_sink(true);
if (!sink)
goto err;
INIT_WORK(&event_data->work, free_event_data);
mask = &event_data->mask;
/* Setup the path for each CPU in a trace session */
for_each_cpu(cpu, mask) {
struct coresight_device *csdev;
csdev = per_cpu(csdev_src, cpu);
if (!csdev)
goto err;
/*
* Building a path doesn't enable it, it simply builds a
* list of devices from source to sink that can be
* referenced later when the path is actually needed.
*/
event_data->path[cpu] = coresight_build_path(csdev, sink);
if (IS_ERR(event_data->path[cpu]))
goto err;
}
if (!sink_ops(sink)->alloc_buffer)
goto err;
/* Get the AUX specific data from the sink buffer */
event_data->snk_config =
sink_ops(sink)->alloc_buffer(sink, cpu, pages,
nr_pages, overwrite);
if (!event_data->snk_config)
goto err;
out:
return event_data;
err:
etm_free_aux(event_data);
event_data = NULL;
goto out;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'coresight: fix kernel panic caused by invalid CPU
Commit d52c9750f150 ("coresight: reset "enable_sink" flag when need be")
caused a kernel panic because of the using of an invalid value: after
'for_each_cpu(cpu, mask)', value of local variable 'cpu' become invalid,
causes following 'cpu_to_node' access invalid memory area.
This patch brings the deleted 'cpu = cpumask_first(mask)' back.
Panic log:
$ perf record -e cs_etm// ls
Unable to handle kernel paging request at virtual address fffe801804af4f10
pgd = ffff8017ce031600
[fffe801804af4f10] *pgd=0000000000000000, *pud=0000000000000000
Internal error: Oops: 96000004 [#1] SMP
Modules linked in:
CPU: 33 PID: 1619 Comm: perf Not tainted 4.7.1+ #16
Hardware name: Huawei Taishan 2280 /CH05TEVBA, BIOS 1.10 11/24/2016
task: ffff8017cb0c8400 ti: ffff8017cb154000 task.ti: ffff8017cb154000
PC is at tmc_alloc_etf_buffer+0x60/0xd4
LR is at tmc_alloc_etf_buffer+0x44/0xd4
pc : [<ffff000008633df8>] lr : [<ffff000008633ddc>] pstate: 60000145
sp : ffff8017cb157b40
x29: ffff8017cb157b40 x28: 0000000000000000
...skip...
7a60: ffff000008c64dc8 0000000000000006 0000000000000253 ffffffffffffffff
7a80: 0000000000000000 0000000000000000 ffff0000080872cc 0000000000000001
[<ffff000008633df8>] tmc_alloc_etf_buffer+0x60/0xd4
[<ffff000008632b9c>] etm_setup_aux+0x1dc/0x1e8
[<ffff00000816eed4>] rb_alloc_aux+0x2b0/0x338
[<ffff00000816a5e4>] perf_mmap+0x414/0x568
[<ffff0000081ab694>] mmap_region+0x324/0x544
[<ffff0000081abbe8>] do_mmap+0x334/0x3e0
[<ffff000008191150>] vm_mmap_pgoff+0xa4/0xc8
[<ffff0000081a9a30>] SyS_mmap_pgoff+0xb0/0x22c
[<ffff0000080872e4>] sys_mmap+0x18/0x28
[<ffff0000080843f0>] el0_svc_naked+0x24/0x28
Code: 912040a5 d0001c00 f873d821 911c6000 (b8656822)
---[ end trace 98933da8f92b0c9a ]---
Signed-off-by: Wang Nan <[email protected]>
Cc: Xia Kaixu <[email protected]>
Cc: Li Zefan <[email protected]>
Cc: Mathieu Poirier <[email protected]>
Cc: [email protected]
Cc: [email protected]
Fixes: d52c9750f150 ("coresight: reset "enable_sink" flag when need be")
Signed-off-by: Mathieu Poirier <[email protected]>
Cc: stable <[email protected]> # 4.10
Signed-off-by: Greg Kroah-Hartman <[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: struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
name_link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (!skip_perm_check &&
key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'KEYS: prevent creating a different user's keyrings
It was possible for an unprivileged user to create the user and user
session keyrings for another user. For example:
sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u
keyctl add keyring _uid_ses.4000 "" @u
sleep 15' &
sleep 1
sudo -u '#4000' keyctl describe @u
sudo -u '#4000' keyctl describe @us
This is problematic because these "fake" keyrings won't have the right
permissions. In particular, the user who created them first will own
them and will have full access to them via the possessor permissions,
which can be used to compromise the security of a user's keys:
-4: alswrv-----v------------ 3000 0 keyring: _uid.4000
-5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000
Fix it by marking user and user session keyrings with a flag
KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session
keyring by name, skip all keyrings that don't have the flag set.
Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed")
Cc: <[email protected]> [v2.6.26+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[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: PackLinuxElf64::canPack()
{
union {
unsigned char buf[sizeof(Elf64_Ehdr) + 14*sizeof(Elf64_Phdr)];
//struct { Elf64_Ehdr ehdr; Elf64_Phdr phdr; } e;
} u;
COMPILE_TIME_ASSERT(sizeof(u) <= 1024)
fi->readx(u.buf, sizeof(u.buf));
fi->seek(0, SEEK_SET);
Elf64_Ehdr const *const ehdr = (Elf64_Ehdr *) u.buf;
// now check the ELF header
if (checkEhdr(ehdr) != 0)
return false;
// additional requirements for linux/elf386
if (get_te16(&ehdr->e_ehsize) != sizeof(*ehdr)) {
throwCantPack("invalid Ehdr e_ehsize; try '--force-execve'");
return false;
}
if (e_phoff != sizeof(*ehdr)) {// Phdrs not contiguous with Ehdr
throwCantPack("non-contiguous Ehdr/Phdr; try '--force-execve'");
return false;
}
// The first PT_LOAD64 must cover the beginning of the file (0==p_offset).
Elf64_Phdr const *phdr = phdri;
for (unsigned j=0; j < e_phnum; ++phdr, ++j) {
if (j >= 14) {
throwCantPack("too many ElfXX_Phdr; try '--force-execve'");
return false;
}
unsigned const p_type = get_te32(&phdr->p_type);
if (1!=exetype && PT_LOAD64 == p_type) { // 1st PT_LOAD
exetype = 1;
load_va = get_te64(&phdr->p_vaddr); // class data member
upx_uint64_t const p_offset = get_te64(&phdr->p_offset);
upx_uint64_t const off = ~page_mask & load_va;
if (off && off == p_offset) { // specific hint
throwCantPack("Go-language PT_LOAD: try hemfix.c, or try '--force-execve'");
// Fixing it inside upx fails because packExtent() reads original file.
return false;
}
if (0 != p_offset) { // 1st PT_LOAD must cover Ehdr and Phdr
throwCantPack("first PT_LOAD.p_offset != 0; try '--force-execve'");
return false;
}
hatch_off = ~3ul & (3+ get_te64(&phdr->p_memsz));
break;
}
}
// We want to compress position-independent executable (gcc -pie)
// main programs, but compressing a shared library must be avoided
// because the result is no longer usable. In theory, there is no way
// to tell them apart: both are just ET_DYN. Also in theory,
// neither the presence nor the absence of any particular symbol name
// can be used to tell them apart; there are counterexamples.
// However, we will use the following heuristic suggested by
// Peter S. Mazinger <[email protected]> September 2005:
// If a ET_DYN has __libc_start_main as a global undefined symbol,
// then the file is a position-independent executable main program
// (that depends on libc.so.6) and is eligible to be compressed.
// Otherwise (no __libc_start_main as global undefined): skip it.
// Also allow __uClibc_main and __uClibc_start_main .
if (Elf64_Ehdr::ET_DYN==get_te16(&ehdr->e_type)) {
// The DT_SYMTAB has no designated length. Read the whole file.
alloc_file_image(file_image, file_size);
fi->seek(0, SEEK_SET);
fi->readx(file_image, file_size);
memcpy(&ehdri, ehdr, sizeof(Elf64_Ehdr));
phdri= (Elf64_Phdr *)((size_t)e_phoff + file_image); // do not free() !!
shdri= (Elf64_Shdr *)((size_t)e_shoff + file_image); // do not free() !!
sec_dynsym = elf_find_section_type(Elf64_Shdr::SHT_DYNSYM);
if (sec_dynsym)
sec_dynstr = get_te32(&sec_dynsym->sh_link) + shdri;
sec_strndx = &shdri[get_te16(&ehdr->e_shstrndx)];
shstrtab = (char const *)(get_te64(&sec_strndx->sh_offset) + file_image);
if (Elf64_Shdr::SHT_STRTAB != get_te32(&sec_strndx->sh_type)
|| 0!=strcmp((char const *)".shstrtab",
&shstrtab[get_te32(&sec_strndx->sh_name)]) ) {
throwCantPack("bad e_shstrndx");
}
phdr= phdri;
for (int j= e_phnum; --j>=0; ++phdr)
if (Elf64_Phdr::PT_DYNAMIC==get_te32(&phdr->p_type)) {
dynseg= (Elf64_Dyn const *)(check_pt_dynamic(phdr) + file_image);
invert_pt_dynamic(dynseg);
break;
}
// elf_find_dynamic() returns 0 if 0==dynseg.
dynstr= (char const *)elf_find_dynamic(Elf64_Dyn::DT_STRTAB);
dynsym= (Elf64_Sym const *)elf_find_dynamic(Elf64_Dyn::DT_SYMTAB);
if (opt->o_unix.force_pie
|| Elf64_Dyn::DF_1_PIE & elf_unsigned_dynamic(Elf64_Dyn::DT_FLAGS_1)
|| calls_crt1((Elf64_Rela const *)elf_find_dynamic(Elf64_Dyn::DT_RELA),
(int)elf_unsigned_dynamic(Elf64_Dyn::DT_RELASZ))
|| calls_crt1((Elf64_Rela const *)elf_find_dynamic(Elf64_Dyn::DT_JMPREL),
(int)elf_unsigned_dynamic(Elf64_Dyn::DT_PLTRELSZ))) {
is_pie = true;
goto proceed; // calls C library init for main program
}
// Heuristic HACK for shared libraries (compare Darwin (MacOS) Dylib.)
// If there is an existing DT_INIT, and if everything that the dynamic
// linker ld-linux needs to perform relocations before calling DT_INIT
// resides below the first SHT_EXECINSTR Section in one PT_LOAD, then
// compress from the first executable Section to the end of that PT_LOAD.
// We must not alter anything that ld-linux might touch before it calls
// the DT_INIT function.
//
// Obviously this hack requires that the linker script put pieces
// into good positions when building the original shared library,
// and also requires ld-linux to behave.
if (elf_find_dynamic(upx_dt_init)) {
if (elf_has_dynamic(Elf64_Dyn::DT_TEXTREL)) {
throwCantPack("DT_TEXTREL found; re-compile with -fPIC");
goto abandon;
}
Elf64_Shdr const *shdr = shdri;
xct_va = ~0ull;
if (e_shnum) {
for (int j= e_shnum; --j>=0; ++shdr) {
unsigned const sh_type = get_te64(&shdr->sh_type);
if (Elf64_Shdr::SHF_EXECINSTR & get_te64(&shdr->sh_flags)) {
xct_va = umin(xct_va, get_te64(&shdr->sh_addr));
}
// Hook the first slot of DT_PREINIT_ARRAY or DT_INIT_ARRAY.
if (( Elf64_Dyn::DT_PREINIT_ARRAY==upx_dt_init
&& Elf64_Shdr::SHT_PREINIT_ARRAY==sh_type)
|| ( Elf64_Dyn::DT_INIT_ARRAY ==upx_dt_init
&& Elf64_Shdr::SHT_INIT_ARRAY ==sh_type) ) {
user_init_off = get_te64(&shdr->sh_offset);
user_init_va = get_te64(&file_image[user_init_off]);
}
// By default /usr/bin/ld leaves 4 extra DT_NULL to support pre-linking.
// Take one as a last resort.
if ((Elf64_Dyn::DT_INIT==upx_dt_init || !upx_dt_init)
&& Elf64_Shdr::SHT_DYNAMIC == sh_type) {
unsigned const n = get_te64(&shdr->sh_size) / sizeof(Elf64_Dyn);
Elf64_Dyn *dynp = (Elf64_Dyn *)&file_image[get_te64(&shdr->sh_offset)];
for (; Elf64_Dyn::DT_NULL != dynp->d_tag; ++dynp) {
if (upx_dt_init == get_te64(&dynp->d_tag)) {
break; // re-found DT_INIT
}
}
if ((1+ dynp) < (n+ dynseg)) { // not the terminator, so take it
user_init_va = get_te64(&dynp->d_val); // 0 if (0==upx_dt_init)
set_te64(&dynp->d_tag, upx_dt_init = Elf64_Dyn::DT_INIT);
user_init_off = (char const *)&dynp->d_val - (char const *)&file_image[0];
}
}
}
}
else { // no Sections; use heuristics
upx_uint64_t const strsz = elf_unsigned_dynamic(Elf64_Dyn::DT_STRSZ);
upx_uint64_t const strtab = elf_unsigned_dynamic(Elf64_Dyn::DT_STRTAB);
upx_uint64_t const relsz = elf_unsigned_dynamic(Elf64_Dyn::DT_RELSZ);
upx_uint64_t const rel = elf_unsigned_dynamic(Elf64_Dyn::DT_REL);
upx_uint64_t const init = elf_unsigned_dynamic(upx_dt_init);
if ((init == (relsz + rel ) && rel == (strsz + strtab))
|| (init == (strsz + strtab) && strtab == (relsz + rel ))
) {
xct_va = init;
user_init_va = init;
user_init_off = elf_get_offset_from_address(init);
}
}
// Rely on 0==elf_unsigned_dynamic(tag) if no such tag.
upx_uint64_t const va_gash = elf_unsigned_dynamic(Elf64_Dyn::DT_GNU_HASH);
upx_uint64_t const va_hash = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH);
if (xct_va < va_gash || (0==va_gash && xct_va < va_hash)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_STRTAB)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_SYMTAB)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_REL)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_RELA)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_JMPREL)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_VERDEF)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_VERSYM)
|| xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_VERNEEDED) ) {
throwCantPack("DT_ tag above stub");
goto abandon;
}
if (!opt->o_unix.android_shlib) {
phdr = phdri;
for (unsigned j= 0; j < e_phnum; ++phdr, ++j) {
upx_uint64_t const vaddr = get_te64(&phdr->p_vaddr);
if (PT_NOTE64 == get_te32(&phdr->p_type)
&& xct_va < vaddr) {
char buf[40]; snprintf(buf, sizeof(buf),
"PT_NOTE %#lx above stub", (unsigned long)vaddr);
throwCantPack(buf);
goto abandon;
}
}
}
xct_off = elf_get_offset_from_address(xct_va);
if (opt->debug.debug_level) {
fprintf(stderr, "shlib canPack: xct_va=%#lx xct_off=%lx\n",
(long)xct_va, (long)xct_off);
}
goto proceed; // But proper packing depends on checking xct_va.
}
else
throwCantPack("need DT_INIT; try \"void _init(void){}\"");
abandon:
return false;
proceed: ;
}
// XXX Theoretically the following test should be first,
// but PackUnix::canPack() wants 0!=exetype ?
if (!super::canPack())
return false;
assert(exetype == 1);
exetype = 0;
// set options
opt->o_unix.blocksize = blocksize = file_size;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents.
https://github.com/upx/upx/issues/206
modified: p_lx_elf.cpp'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PackLinuxElf64::check_pt_dynamic(Elf64_Phdr const *const phdr)
{
upx_uint64_t t = get_te64(&phdr->p_offset), s = sizeof(Elf64_Dyn) + t;
upx_uint64_t filesz = get_te64(&phdr->p_filesz), memsz = get_te64(&phdr->p_memsz);
if (s < t || (upx_uint64_t)file_size < s
|| (7 & t) || (0xf & (filesz | memsz)) // .balign 8; 16==sizeof(Elf64_Dyn)
|| filesz < sizeof(Elf64_Dyn)
|| memsz < sizeof(Elf64_Dyn)
|| filesz < memsz) {
char msg[50]; snprintf(msg, sizeof(msg), "bad PT_DYNAMIC phdr[%u]",
(unsigned)(phdr - phdri));
throwCantPack(msg);
}
sz_dynseg = memsz;
return t;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents.
https://github.com/upx/upx/issues/206
modified: p_lx_elf.cpp'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool PackLinuxElf32::canPack()
{
union {
unsigned char buf[sizeof(Elf32_Ehdr) + 14*sizeof(Elf32_Phdr)];
//struct { Elf32_Ehdr ehdr; Elf32_Phdr phdr; } e;
} u;
COMPILE_TIME_ASSERT(sizeof(u.buf) <= 512)
fi->seek(0, SEEK_SET);
fi->readx(u.buf, sizeof(u.buf));
fi->seek(0, SEEK_SET);
Elf32_Ehdr const *const ehdr = (Elf32_Ehdr *) u.buf;
// now check the ELF header
if (checkEhdr(ehdr) != 0)
return false;
// additional requirements for linux/elf386
if (get_te16(&ehdr->e_ehsize) != sizeof(*ehdr)) {
throwCantPack("invalid Ehdr e_ehsize; try '--force-execve'");
return false;
}
if (e_phoff != sizeof(*ehdr)) {// Phdrs not contiguous with Ehdr
throwCantPack("non-contiguous Ehdr/Phdr; try '--force-execve'");
return false;
}
unsigned char osabi0 = u.buf[Elf32_Ehdr::EI_OSABI];
// The first PT_LOAD32 must cover the beginning of the file (0==p_offset).
Elf32_Phdr const *phdr = phdri;
note_size = 0;
for (unsigned j=0; j < e_phnum; ++phdr, ++j) {
if (j >= 14) {
throwCantPack("too many ElfXX_Phdr; try '--force-execve'");
return false;
}
unsigned const p_type = get_te32(&phdr->p_type);
unsigned const p_offset = get_te32(&phdr->p_offset);
if (1!=exetype && PT_LOAD32 == p_type) { // 1st PT_LOAD
exetype = 1;
load_va = get_te32(&phdr->p_vaddr); // class data member
// Cast on next line is to avoid a compiler bug (incorrect complaint) in
// Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x64
// error C4319: '~': zero extending 'unsigned int' to 'upx_uint64_t' of greater size
unsigned const off = ~page_mask & (unsigned)load_va;
if (off && off == p_offset) { // specific hint
throwCantPack("Go-language PT_LOAD: try hemfix.c, or try '--force-execve'");
// Fixing it inside upx fails because packExtent() reads original file.
return false;
}
if (0 != p_offset) { // 1st PT_LOAD must cover Ehdr and Phdr
throwCantPack("first PT_LOAD.p_offset != 0; try '--force-execve'");
return false;
}
hatch_off = ~3u & (3+ get_te32(&phdr->p_memsz));
}
if (PT_NOTE32 == p_type) {
unsigned const x = get_te32(&phdr->p_memsz);
if ( sizeof(elfout.notes) < x // beware overflow of note_size
|| (sizeof(elfout.notes) < (note_size += x)) ) {
throwCantPack("PT_NOTEs too big; try '--force-execve'");
return false;
}
if (osabi_note && Elf32_Ehdr::ELFOSABI_NONE==osabi0) { // Still seems to be generic.
struct {
struct Elf32_Nhdr nhdr;
char name[8];
unsigned body;
} note;
memset(¬e, 0, sizeof(note));
fi->seek(p_offset, SEEK_SET);
fi->readx(¬e, sizeof(note));
fi->seek(0, SEEK_SET);
if (4==get_te32(¬e.nhdr.descsz)
&& 1==get_te32(¬e.nhdr.type)
// && 0==note.end
&& (1+ strlen(osabi_note))==get_te32(¬e.nhdr.namesz)
&& 0==strcmp(osabi_note, (char const *)¬e.name[0])
) {
osabi0 = ei_osabi; // Specified by PT_NOTE.
}
}
}
}
if (Elf32_Ehdr::ELFOSABI_NONE ==osabi0
|| Elf32_Ehdr::ELFOSABI_LINUX==osabi0) { // No EI_OSBAI, no PT_NOTE.
unsigned const arm_eabi = 0xff000000u & get_te32(&ehdr->e_flags);
if (Elf32_Ehdr::EM_ARM==e_machine
&& (EF_ARM_EABI_VER5==arm_eabi
|| EF_ARM_EABI_VER4==arm_eabi ) ) {
// armel-eabi armeb-eabi ARM Linux EABI version 4 is a mess.
ei_osabi = osabi0 = Elf32_Ehdr::ELFOSABI_LINUX;
}
else {
osabi0 = opt->o_unix.osabi0; // Possibly specified by command-line.
}
}
if (osabi0!=ei_osabi) {
return false;
}
// We want to compress position-independent executable (gcc -pie)
// main programs, but compressing a shared library must be avoided
// because the result is no longer usable. In theory, there is no way
// to tell them apart: both are just ET_DYN. Also in theory,
// neither the presence nor the absence of any particular symbol name
// can be used to tell them apart; there are counterexamples.
// However, we will use the following heuristic suggested by
// Peter S. Mazinger <[email protected]> September 2005:
// If a ET_DYN has __libc_start_main as a global undefined symbol,
// then the file is a position-independent executable main program
// (that depends on libc.so.6) and is eligible to be compressed.
// Otherwise (no __libc_start_main as global undefined): skip it.
// Also allow __uClibc_main and __uClibc_start_main .
if (Elf32_Ehdr::ET_DYN==get_te16(&ehdr->e_type)) {
// The DT_SYMTAB has no designated length. Read the whole file.
alloc_file_image(file_image, file_size);
fi->seek(0, SEEK_SET);
fi->readx(file_image, file_size);
memcpy(&ehdri, ehdr, sizeof(Elf32_Ehdr));
phdri= (Elf32_Phdr *)((size_t)e_phoff + file_image); // do not free() !!
shdri= (Elf32_Shdr *)((size_t)e_shoff + file_image); // do not free() !!
sec_strndx = &shdri[get_te16(&ehdr->e_shstrndx)];
shstrtab = (char const *)(get_te32(&sec_strndx->sh_offset) + file_image);
sec_dynsym = elf_find_section_type(Elf32_Shdr::SHT_DYNSYM);
if (sec_dynsym)
sec_dynstr = get_te32(&sec_dynsym->sh_link) + shdri;
if (Elf32_Shdr::SHT_STRTAB != get_te32(&sec_strndx->sh_type)
|| 0!=strcmp((char const *)".shstrtab",
&shstrtab[get_te32(&sec_strndx->sh_name)]) ) {
throwCantPack("bad e_shstrndx");
}
phdr= phdri;
for (int j= e_phnum; --j>=0; ++phdr)
if (Elf32_Phdr::PT_DYNAMIC==get_te32(&phdr->p_type)) {
dynseg= (Elf32_Dyn const *)(check_pt_dynamic(phdr) + file_image);
invert_pt_dynamic(dynseg);
break;
}
// elf_find_dynamic() returns 0 if 0==dynseg.
dynstr= (char const *)elf_find_dynamic(Elf32_Dyn::DT_STRTAB);
dynsym= (Elf32_Sym const *)elf_find_dynamic(Elf32_Dyn::DT_SYMTAB);
if (opt->o_unix.force_pie
|| Elf32_Dyn::DF_1_PIE & elf_unsigned_dynamic(Elf32_Dyn::DT_FLAGS_1)
|| calls_crt1((Elf32_Rel const *)elf_find_dynamic(Elf32_Dyn::DT_REL),
(int)elf_unsigned_dynamic(Elf32_Dyn::DT_RELSZ))
|| calls_crt1((Elf32_Rel const *)elf_find_dynamic(Elf32_Dyn::DT_JMPREL),
(int)elf_unsigned_dynamic(Elf32_Dyn::DT_PLTRELSZ))) {
is_pie = true;
goto proceed; // calls C library init for main program
}
// Heuristic HACK for shared libraries (compare Darwin (MacOS) Dylib.)
// If there is an existing DT_INIT, and if everything that the dynamic
// linker ld-linux needs to perform relocations before calling DT_INIT
// resides below the first SHT_EXECINSTR Section in one PT_LOAD, then
// compress from the first executable Section to the end of that PT_LOAD.
// We must not alter anything that ld-linux might touch before it calls
// the DT_INIT function.
//
// Obviously this hack requires that the linker script put pieces
// into good positions when building the original shared library,
// and also requires ld-linux to behave.
// Apparently glibc-2.13.90 insists on 0==e_ident[EI_PAD..15],
// so compressing shared libraries may be doomed anyway.
// 2011-06-01: stub.shlib-init.S works around by installing hatch
// at end of .text.
if (/*jni_onload_sym ||*/ elf_find_dynamic(upx_dt_init)) {
if (this->e_machine!=Elf32_Ehdr::EM_386
&& this->e_machine!=Elf32_Ehdr::EM_MIPS
&& this->e_machine!=Elf32_Ehdr::EM_ARM)
goto abandon; // need stub: EM_PPC
if (elf_has_dynamic(Elf32_Dyn::DT_TEXTREL)) {
throwCantPack("DT_TEXTREL found; re-compile with -fPIC");
goto abandon;
}
Elf32_Shdr const *shdr = shdri;
xct_va = ~0u;
if (e_shnum) {
for (int j= e_shnum; --j>=0; ++shdr) {
unsigned const sh_type = get_te32(&shdr->sh_type);
if (Elf32_Shdr::SHF_EXECINSTR & get_te32(&shdr->sh_flags)) {
xct_va = umin(xct_va, get_te32(&shdr->sh_addr));
}
// Hook the first slot of DT_PREINIT_ARRAY or DT_INIT_ARRAY.
if (( Elf32_Dyn::DT_PREINIT_ARRAY==upx_dt_init
&& Elf32_Shdr::SHT_PREINIT_ARRAY==sh_type)
|| ( Elf32_Dyn::DT_INIT_ARRAY ==upx_dt_init
&& Elf32_Shdr::SHT_INIT_ARRAY ==sh_type) ) {
user_init_off = get_te32(&shdr->sh_offset);
user_init_va = get_te32(&file_image[user_init_off]);
}
// By default /usr/bin/ld leaves 4 extra DT_NULL to support pre-linking.
// Take one as a last resort.
if ((Elf32_Dyn::DT_INIT==upx_dt_init || !upx_dt_init)
&& Elf32_Shdr::SHT_DYNAMIC == sh_type) {
unsigned const n = get_te32(&shdr->sh_size) / sizeof(Elf32_Dyn);
Elf32_Dyn *dynp = (Elf32_Dyn *)&file_image[get_te32(&shdr->sh_offset)];
for (; Elf32_Dyn::DT_NULL != dynp->d_tag; ++dynp) {
if (upx_dt_init == get_te32(&dynp->d_tag)) {
break; // re-found DT_INIT
}
}
if ((1+ dynp) < (n+ dynseg)) { // not the terminator, so take it
user_init_va = get_te32(&dynp->d_val); // 0 if (0==upx_dt_init)
set_te32(&dynp->d_tag, upx_dt_init = Elf32_Dyn::DT_INIT);
user_init_off = (char const *)&dynp->d_val - (char const *)&file_image[0];
}
}
}
}
else { // no Sections; use heuristics
unsigned const strsz = elf_unsigned_dynamic(Elf32_Dyn::DT_STRSZ);
unsigned const strtab = elf_unsigned_dynamic(Elf32_Dyn::DT_STRTAB);
unsigned const relsz = elf_unsigned_dynamic(Elf32_Dyn::DT_RELSZ);
unsigned const rel = elf_unsigned_dynamic(Elf32_Dyn::DT_REL);
unsigned const init = elf_unsigned_dynamic(upx_dt_init);
if ((init == (relsz + rel ) && rel == (strsz + strtab))
|| (init == (strsz + strtab) && strtab == (relsz + rel ))
) {
xct_va = init;
user_init_va = init;
user_init_off = elf_get_offset_from_address(init);
}
}
// Rely on 0==elf_unsigned_dynamic(tag) if no such tag.
unsigned const va_gash = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH);
unsigned const va_hash = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);
if (xct_va < va_gash || (0==va_gash && xct_va < va_hash)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_STRTAB)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_SYMTAB)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_REL)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_RELA)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_JMPREL)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERDEF)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERSYM)
|| xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERNEEDED) ) {
throwCantPack("DT_ tag above stub");
goto abandon;
}
if (!opt->o_unix.android_shlib) {
phdr = phdri;
for (unsigned j= 0; j < e_phnum; ++phdr, ++j) {
unsigned const vaddr = get_te32(&phdr->p_vaddr);
if (PT_NOTE32 == get_te32(&phdr->p_type)
&& xct_va < vaddr) {
char buf[40]; snprintf(buf, sizeof(buf),
"PT_NOTE %#x above stub", vaddr);
throwCantPack(buf);
goto abandon;
}
}
}
xct_off = elf_get_offset_from_address(xct_va);
if (opt->debug.debug_level) {
fprintf(stderr, "shlib canPack: xct_va=%#lx xct_off=%lx\n",
(long)xct_va, (long)xct_off);
}
goto proceed; // But proper packing depends on checking xct_va.
}
else
throwCantPack("need DT_INIT; try \"void _init(void){}\"");
abandon:
return false;
proceed: ;
}
// XXX Theoretically the following test should be first,
// but PackUnix::canPack() wants 0!=exetype ?
if (!super::canPack())
return false;
assert(exetype == 1);
exetype = 0;
// set options
opt->o_unix.blocksize = blocksize = file_size;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents.
https://github.com/upx/upx/issues/206
modified: p_lx_elf.cpp'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
height,
pixels_length,
quantum;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
if (sun_info.maplength > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth != 1) && (sun_info.depth != 8) &&
(sun_info.depth != 24) && (sun_info.depth != 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_NONE:
break;
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
{
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
{
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
{
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (sun_info.length == 0)
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
number_pixels=(MagickSizeType) (image->columns*image->rows);
if ((sun_info.type != RT_ENCODED) &&
((number_pixels*sun_info.depth) > (8UL*sun_info.length)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (HeapOverflowSanityCheck(sun_info.width,sun_info.depth) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
if (sun_info.length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
sun_data=(unsigned char *) AcquireQuantumMemory(sun_info.length,
sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
quantum=sun_info.depth == 1 ? 15 : 7;
bytes_per_line+=quantum;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+quantum))
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
bytes_per_line>>=4;
if (HeapOverflowSanityCheck(height,bytes_per_line) != MagickFalse)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
pixels_length=height*bytes_per_line;
sun_pixels=(unsigned char *) AcquireQuantumMemory(pixels_length+image->rows,
sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
ResetMagickMemory(sun_pixels,0,pixels_length*sizeof(*sun_pixels));
if (sun_info.type == RT_ENCODED)
{
status=DecodeImage(sun_data,sun_info.length,sun_pixels,pixels_length);
if (status == MagickFalse)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
else
{
if (sun_info.length > pixels_length)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
(void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);
}
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,ConstrainColormapIndex(image,*p,exception),q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/956'</s> |
<s>[INST] Given the following code containing errors, provide 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 ext4_xattr_set_entry(struct ext4_xattr_info *i,
struct ext4_xattr_search *s,
handle_t *handle, struct inode *inode,
bool is_block)
{
struct ext4_xattr_entry *last;
struct ext4_xattr_entry *here = s->here;
size_t min_offs = s->end - s->base, name_len = strlen(i->name);
int in_inode = i->in_inode;
struct inode *old_ea_inode = NULL;
struct inode *new_ea_inode = NULL;
size_t old_size, new_size;
int ret;
/* Space used by old and new values. */
old_size = (!s->not_found && !here->e_value_inum) ?
EXT4_XATTR_SIZE(le32_to_cpu(here->e_value_size)) : 0;
new_size = (i->value && !in_inode) ? EXT4_XATTR_SIZE(i->value_len) : 0;
/*
* Optimization for the simple case when old and new values have the
* same padded sizes. Not applicable if external inodes are involved.
*/
if (new_size && new_size == old_size) {
size_t offs = le16_to_cpu(here->e_value_offs);
void *val = s->base + offs;
here->e_value_size = cpu_to_le32(i->value_len);
if (i->value == EXT4_ZERO_XATTR_VALUE) {
memset(val, 0, new_size);
} else {
memcpy(val, i->value, i->value_len);
/* Clear padding bytes. */
memset(val + i->value_len, 0, new_size - i->value_len);
}
goto update_hash;
}
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_inum && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
/* Check whether we have enough space. */
if (i->value) {
size_t free;
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found)
free += EXT4_XATTR_LEN(name_len) + old_size;
if (free < EXT4_XATTR_LEN(name_len) + new_size) {
ret = -ENOSPC;
goto out;
}
/*
* If storing the value in an external inode is an option,
* reserve space for xattr entries/names in the external
* attribute block so that a long value does not occupy the
* whole space and prevent futher entries being added.
*/
if (ext4_has_feature_ea_inode(inode->i_sb) &&
new_size && is_block &&
(min_offs + old_size - new_size) <
EXT4_XATTR_BLOCK_RESERVE(inode)) {
ret = -ENOSPC;
goto out;
}
}
/*
* Getting access to old and new ea inodes is subject to failures.
* Finish that work before doing any modifications to the xattr data.
*/
if (!s->not_found && here->e_value_inum) {
ret = ext4_xattr_inode_iget(inode,
le32_to_cpu(here->e_value_inum),
le32_to_cpu(here->e_hash),
&old_ea_inode);
if (ret) {
old_ea_inode = NULL;
goto out;
}
}
if (i->value && in_inode) {
WARN_ON_ONCE(!i->value_len);
ret = ext4_xattr_inode_alloc_quota(inode, i->value_len);
if (ret)
goto out;
ret = ext4_xattr_inode_lookup_create(handle, inode, i->value,
i->value_len,
&new_ea_inode);
if (ret) {
new_ea_inode = NULL;
ext4_xattr_inode_free_quota(inode, NULL, i->value_len);
goto out;
}
}
if (old_ea_inode) {
/* We are ready to release ref count on the old_ea_inode. */
ret = ext4_xattr_inode_dec_ref(handle, old_ea_inode);
if (ret) {
/* Release newly required ref count on new_ea_inode. */
if (new_ea_inode) {
int err;
err = ext4_xattr_inode_dec_ref(handle,
new_ea_inode);
if (err)
ext4_warning_inode(new_ea_inode,
"dec ref new_ea_inode err=%d",
err);
ext4_xattr_inode_free_quota(inode, new_ea_inode,
i->value_len);
}
goto out;
}
ext4_xattr_inode_free_quota(inode, old_ea_inode,
le32_to_cpu(here->e_value_size));
}
/* No failures allowed past this point. */
if (!s->not_found && here->e_value_offs) {
/* Remove the old value. */
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(here->e_value_offs);
void *val = s->base + offs;
memmove(first_val + old_size, first_val, val - first_val);
memset(first_val, 0, old_size);
min_offs += old_size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_inum &&
last->e_value_size && o < offs)
last->e_value_offs = cpu_to_le16(o + old_size);
last = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove old name. */
size_t size = EXT4_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(here, (void *)here + size,
(void *)last - (void *)here + sizeof(__u32));
memset(last, 0, size);
} else if (s->not_found) {
/* Insert new name. */
size_t size = EXT4_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)here + sizeof(__u32);
memmove((void *)here + size, here, rest);
memset(here, 0, size);
here->e_name_index = i->name_index;
here->e_name_len = name_len;
memcpy(here->e_name, i->name, name_len);
} else {
/* This is an update, reset value info. */
here->e_value_inum = 0;
here->e_value_offs = 0;
here->e_value_size = 0;
}
if (i->value) {
/* Insert new value. */
if (in_inode) {
here->e_value_inum = cpu_to_le32(new_ea_inode->i_ino);
} else if (i->value_len) {
void *val = s->base + min_offs - new_size;
here->e_value_offs = cpu_to_le16(min_offs - new_size);
if (i->value == EXT4_ZERO_XATTR_VALUE) {
memset(val, 0, new_size);
} else {
memcpy(val, i->value, i->value_len);
/* Clear padding bytes. */
memset(val + i->value_len, 0,
new_size - i->value_len);
}
}
here->e_value_size = cpu_to_le32(i->value_len);
}
update_hash:
if (i->value) {
__le32 hash = 0;
/* Entry hash calculation. */
if (in_inode) {
__le32 crc32c_hash;
/*
* Feed crc32c hash instead of the raw value for entry
* hash calculation. This is to avoid walking
* potentially long value buffer again.
*/
crc32c_hash = cpu_to_le32(
ext4_xattr_inode_get_hash(new_ea_inode));
hash = ext4_xattr_hash_entry(here->e_name,
here->e_name_len,
&crc32c_hash, 1);
} else if (is_block) {
__le32 *value = s->base + le16_to_cpu(
here->e_value_offs);
hash = ext4_xattr_hash_entry(here->e_name,
here->e_name_len, value,
new_size >> 2);
}
here->e_hash = hash;
}
if (is_block)
ext4_xattr_rehash((struct ext4_xattr_header *)s->base);
ret = 0;
out:
iput(old_ea_inode);
iput(new_ea_inode);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'ext4: correctly handle a zero-length xattr with a non-zero e_value_offs
Ext4 will always create ext4 extended attributes which do not have a
value (where e_value_size is zero) with e_value_offs set to zero. In
most places e_value_offs will not be used in a substantive way if
e_value_size is zero.
There was one exception to this, which is in ext4_xattr_set_entry(),
where if there is a maliciously crafted file system where there is an
extended attribute with e_value_offs is non-zero and e_value_size is
0, the attempt to remove this xattr will result in a negative value
getting passed to memmove, leading to the following sadness:
[ 41.225365] EXT4-fs (loop0): mounted filesystem with ordered data mode. Opts: (null)
[ 44.538641] BUG: unable to handle kernel paging request at ffff9ec9a3000000
[ 44.538733] IP: __memmove+0x81/0x1a0
[ 44.538755] PGD 1249bd067 P4D 1249bd067 PUD 1249c1067 PMD 80000001230000e1
[ 44.538793] Oops: 0003 [#1] SMP PTI
[ 44.539074] CPU: 0 PID: 1470 Comm: poc Not tainted 4.16.0-rc1+ #1
...
[ 44.539475] Call Trace:
[ 44.539832] ext4_xattr_set_entry+0x9e7/0xf80
...
[ 44.539972] ext4_xattr_block_set+0x212/0xea0
...
[ 44.540041] ext4_xattr_set_handle+0x514/0x610
[ 44.540065] ext4_xattr_set+0x7f/0x120
[ 44.540090] __vfs_removexattr+0x4d/0x60
[ 44.540112] vfs_removexattr+0x75/0xe0
[ 44.540132] removexattr+0x4d/0x80
...
[ 44.540279] path_removexattr+0x91/0xb0
[ 44.540300] SyS_removexattr+0xf/0x20
[ 44.540322] do_syscall_64+0x71/0x120
[ 44.540344] entry_SYSCALL_64_after_hwframe+0x21/0x86
https://bugzilla.kernel.org/show_bug.cgi?id=199347
This addresses CVE-2018-10840.
Reported-by: "Xu, Wen" <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
Reviewed-by: Andreas Dilger <[email protected]>
Cc: [email protected]
Fixes: dec214d00e0d7 ("ext4: xattr inode deduplication")'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
{
struct ext4_iloc iloc;
struct ext4_inode *raw_inode;
struct ext4_inode_info *ei;
struct inode *inode;
journal_t *journal = EXT4_SB(sb)->s_journal;
long ret;
loff_t size;
int block;
uid_t i_uid;
gid_t i_gid;
projid_t i_projid;
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
ei = EXT4_I(inode);
iloc.bh = NULL;
ret = __ext4_get_inode_loc(inode, &iloc, 0);
if (ret < 0)
goto bad_inode;
raw_inode = ext4_raw_inode(&iloc);
if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
EXT4_ERROR_INODE(inode, "root inode unallocated");
ret = -EFSCORRUPTED;
goto bad_inode;
}
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
EXT4_INODE_SIZE(inode->i_sb) ||
(ei->i_extra_isize & 3)) {
EXT4_ERROR_INODE(inode,
"bad extra_isize %u (inode size %u)",
ei->i_extra_isize,
EXT4_INODE_SIZE(inode->i_sb));
ret = -EFSCORRUPTED;
goto bad_inode;
}
} else
ei->i_extra_isize = 0;
/* Precompute checksum seed for inode metadata */
if (ext4_has_metadata_csum(sb)) {
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
__le32 inum = cpu_to_le32(inode->i_ino);
__le32 gen = raw_inode->i_generation;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
sizeof(inum));
ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
sizeof(gen));
}
if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
EXT4_ERROR_INODE(inode, "checksum invalid");
ret = -EFSBADCRC;
goto bad_inode;
}
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
if (ext4_has_feature_project(sb) &&
EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
else
i_projid = EXT4_DEF_PROJID;
if (!(test_opt(inode->i_sb, NO_UID32))) {
i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
}
i_uid_write(inode, i_uid);
i_gid_write(inode, i_gid);
ei->i_projid = make_kprojid(&init_user_ns, i_projid);
set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
ei->i_inline_off = 0;
ei->i_dir_start_lookup = 0;
ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
/* We now have enough fields to check if the inode was active or not.
* This is needed because nfsd might try to access dead inodes
* the test is that same one that e2fsck uses
* NeilBrown 1999oct15
*/
if (inode->i_nlink == 0) {
if ((inode->i_mode == 0 ||
!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
ino != EXT4_BOOT_LOADER_INO) {
/* this inode is deleted */
ret = -ESTALE;
goto bad_inode;
}
/* The only unlinked inodes we let through here have
* valid i_mode and are being read by the orphan
* recovery code: that's fine, we're about to complete
* the process of deleting those.
* OR it is the EXT4_BOOT_LOADER_INO which is
* not initialized on a new filesystem. */
}
ei->i_flags = le32_to_cpu(raw_inode->i_flags);
inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
if (ext4_has_feature_64bit(sb))
ei->i_file_acl |=
((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
inode->i_size = ext4_isize(sb, raw_inode);
if ((size = i_size_read(inode)) < 0) {
EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
ret = -EFSCORRUPTED;
goto bad_inode;
}
ei->i_disksize = inode->i_size;
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
ei->i_block_group = iloc.block_group;
ei->i_last_alloc_group = ~0;
/*
* NOTE! The in-memory inode i_data array is in little-endian order
* even on big-endian machines: we do NOT byteswap the block numbers!
*/
for (block = 0; block < EXT4_N_BLOCKS; block++)
ei->i_data[block] = raw_inode->i_block[block];
INIT_LIST_HEAD(&ei->i_orphan);
/*
* Set transaction id's of transactions that have to be committed
* to finish f[data]sync. We set them to currently running transaction
* as we cannot be sure that the inode or some of its metadata isn't
* part of the transaction - the inode could have been reclaimed and
* now it is reread from disk.
*/
if (journal) {
transaction_t *transaction;
tid_t tid;
read_lock(&journal->j_state_lock);
if (journal->j_running_transaction)
transaction = journal->j_running_transaction;
else
transaction = journal->j_committing_transaction;
if (transaction)
tid = transaction->t_tid;
else
tid = journal->j_commit_sequence;
read_unlock(&journal->j_state_lock);
ei->i_sync_tid = tid;
ei->i_datasync_tid = tid;
}
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
if (ei->i_extra_isize == 0) {
/* The extra space is currently unused. Use it. */
BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
ei->i_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
} else {
ext4_iget_extra_inode(inode, raw_inode, ei);
}
}
EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
ivers |=
(__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
}
ext4_inode_set_iversion_queried(inode, ivers);
}
ret = 0;
if (ei->i_file_acl &&
!ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
ei->i_file_acl);
ret = -EFSCORRUPTED;
goto bad_inode;
} else if (!ext4_has_inline_data(inode)) {
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
(S_ISLNK(inode->i_mode) &&
!ext4_inode_is_fast_symlink(inode))))
/* Validate extent which is part of inode */
ret = ext4_ext_check_inode(inode);
} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
(S_ISLNK(inode->i_mode) &&
!ext4_inode_is_fast_symlink(inode))) {
/* Validate block references which are part of inode */
ret = ext4_ind_check_inode(inode);
}
}
if (ret)
goto bad_inode;
if (S_ISREG(inode->i_mode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ext4_dir_inode_operations;
inode->i_fop = &ext4_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
/* VFS does not allow setting these so must be corruption */
if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
EXT4_ERROR_INODE(inode,
"immutable or append flags not allowed on symlinks");
ret = -EFSCORRUPTED;
goto bad_inode;
}
if (ext4_encrypted_inode(inode)) {
inode->i_op = &ext4_encrypted_symlink_inode_operations;
ext4_set_aops(inode);
} else if (ext4_inode_is_fast_symlink(inode)) {
inode->i_link = (char *)ei->i_data;
inode->i_op = &ext4_fast_symlink_inode_operations;
nd_terminate_link(ei->i_data, inode->i_size,
sizeof(ei->i_data) - 1);
} else {
inode->i_op = &ext4_symlink_inode_operations;
ext4_set_aops(inode);
}
inode_nohighmem(inode);
} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
inode->i_op = &ext4_special_inode_operations;
if (raw_inode->i_block[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
} else if (ino == EXT4_BOOT_LOADER_INO) {
make_bad_inode(inode);
} else {
ret = -EFSCORRUPTED;
EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
goto bad_inode;
}
brelse(iloc.bh);
ext4_set_inode_flags(inode);
unlock_new_inode(inode);
return inode;
bad_inode:
brelse(iloc.bh);
iget_failed(inode);
return ERR_PTR(ret);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'ext4: bubble errors from ext4_find_inline_data_nolock() up to ext4_iget()
If ext4_find_inline_data_nolock() returns an error it needs to get
reflected up to ext4_iget(). In order to fix this,
ext4_iget_extra_inode() needs to return an error (and not return
void).
This is related to "ext4: do not allow external inodes for inline
data" (which fixes CVE-2018-11412) in that in the errors=continue
case, it would be useful to for userspace to receive an error
indicating that file system is corrupted.
Signed-off-by: Theodore Ts'o <[email protected]>
Reviewed-by: Andreas Dilger <[email protected]>
Cc: [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 compat_get_timex(struct timex *txc, const struct compat_timex __user *utp)
{
struct compat_timex tx32;
if (copy_from_user(&tx32, utp, sizeof(struct compat_timex)))
return -EFAULT;
txc->modes = tx32.modes;
txc->offset = tx32.offset;
txc->freq = tx32.freq;
txc->maxerror = tx32.maxerror;
txc->esterror = tx32.esterror;
txc->status = tx32.status;
txc->constant = tx32.constant;
txc->precision = tx32.precision;
txc->tolerance = tx32.tolerance;
txc->time.tv_sec = tx32.time.tv_sec;
txc->time.tv_usec = tx32.time.tv_usec;
txc->tick = tx32.tick;
txc->ppsfreq = tx32.ppsfreq;
txc->jitter = tx32.jitter;
txc->shift = tx32.shift;
txc->stabil = tx32.stabil;
txc->jitcnt = tx32.jitcnt;
txc->calcnt = tx32.calcnt;
txc->errcnt = tx32.errcnt;
txc->stbcnt = tx32.stbcnt;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'compat: fix 4-byte infoleak via uninitialized struct field
Commit 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to
native counterparts") removed the memset() in compat_get_timex(). Since
then, the compat adjtimex syscall can invoke do_adjtimex() with an
uninitialized ->tai.
If do_adjtimex() doesn't write to ->tai (e.g. because the arguments are
invalid), compat_put_timex() then copies the uninitialized ->tai field
to userspace.
Fix it by adding the memset() back.
Fixes: 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts")
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Kees Cook <[email protected]>
Acked-by: Al Viro <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *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(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 += 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)
{
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 * (ssize_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);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
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 long)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);
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);
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);
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
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/1149'</s> |
<s>[INST] Given the following code containing errors, provide 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 _slurm_rpc_submit_batch_pack_job(slurm_msg_t *msg)
{
static int select_serial = -1;
static int active_rpc_cnt = 0;
ListIterator iter;
int error_code = SLURM_SUCCESS, alloc_only = 0;
DEF_TIMERS;
uint32_t pack_job_id = 0, pack_job_offset = 0;
struct job_record *job_ptr = NULL, *first_job_ptr = NULL;
slurm_msg_t response_msg;
submit_response_msg_t submit_msg;
job_desc_msg_t *job_desc_msg;
char *script = NULL;
/* Locks: Read config, read job, read node, read partition */
slurmctld_lock_t job_read_lock = {
READ_LOCK, READ_LOCK, READ_LOCK, READ_LOCK, NO_LOCK };
/* Locks: Read config, write job, write node, read partition */
slurmctld_lock_t job_write_lock = {
READ_LOCK, WRITE_LOCK, WRITE_LOCK, READ_LOCK, NO_LOCK };
List job_req_list = (List) msg->data;
uid_t uid = g_slurm_auth_get_uid(msg->auth_cred,
slurmctld_config.auth_info);
uint32_t job_uid = NO_VAL;
char *err_msg = NULL, *job_submit_user_msg = NULL;
bool reject_job = false;
bool is_super_user;
List submit_job_list = NULL;
hostset_t jobid_hostset = NULL;
char tmp_str[32];
START_TIMER;
debug2("Processing RPC: REQUEST_SUBMIT_BATCH_PACK_JOB from uid=%d",
uid);
if (!job_req_list || (list_count(job_req_list) == 0)) {
info("REQUEST_SUBMIT_BATCH_PACK_JOB from uid=%d with empty job list",
uid);
error_code = SLURM_ERROR;
reject_job = true;
goto send_msg;
}
if (!_sched_backfill()) {
error_code = ESLURM_NOT_SUPPORTED;
reject_job = true;
goto send_msg;
}
if (select_serial == -1) {
if (xstrcmp(slurmctld_conf.select_type, "select/serial"))
select_serial = 0;
else
select_serial = 1;
}
if (slurmctld_config.submissions_disabled || (select_serial == 1)) {
info("Submissions disabled on system");
error_code = ESLURM_SUBMISSIONS_DISABLED;
reject_job = true;
goto send_msg;
}
if (!job_req_list || (list_count(job_req_list) == 0)) {
info("REQUEST_SUBMIT_BATCH_PACK_JOB from uid=%d with empty job list",
uid);
error_code = SLURM_ERROR;
reject_job = true;
goto send_msg;
}
/* Validate the individual request */
is_super_user = validate_super_user(uid);
lock_slurmctld(job_read_lock); /* Locks for job_submit plugin use */
iter = list_iterator_create(job_req_list);
while ((job_desc_msg = (job_desc_msg_t *) list_next(iter))) {
if (job_uid == NO_VAL)
job_uid = job_desc_msg->user_id;
if ((uid != job_desc_msg->user_id) && !is_super_user) {
/* NOTE: Super root can submit a job for any user */
error("Security violation, REQUEST_SUBMIT_BATCH_PACK_JOB from uid=%d",
uid);
error_code = ESLURM_USER_ID_MISSING;
break;
}
if ((job_desc_msg->alloc_node == NULL) ||
(job_desc_msg->alloc_node[0] == '\0')) {
error("REQUEST_SUBMIT_BATCH_PACK_JOB lacks alloc_node from uid=%d",
uid);
error_code = ESLURM_INVALID_NODE_NAME;
break;
}
dump_job_desc(job_desc_msg);
job_desc_msg->pack_job_offset = pack_job_offset;
error_code = validate_job_create_req(job_desc_msg, uid,
&err_msg);
if (error_code != SLURM_SUCCESS) {
reject_job = true;
break;
}
if (err_msg) {
char *save_ptr = NULL, *tok;
tok = strtok_r(err_msg, "\n", &save_ptr);
while (tok) {
char *sep = "";
if (job_submit_user_msg)
sep = "\n";
xstrfmtcat(job_submit_user_msg, "%s%d: %s",
sep, pack_job_offset, tok);
tok = strtok_r(NULL, "\n", &save_ptr);
}
xfree(err_msg);
}
pack_job_offset++;
}
list_iterator_destroy(iter);
unlock_slurmctld(job_read_lock);
if (error_code != SLURM_SUCCESS)
goto send_msg;
/*
* In validate_job_create_req, err_msg is currently only modified in
* the call to job_submit_plugin_submit. We save the err_msg in a temp
* char *job_submit_user_msg because err_msg can be overwritten later
* in the calls to job_allocate, and we need the job submit plugin value
* to build the resource allocation response in the call to
* _build_alloc_msg.
*/
if (err_msg)
job_submit_user_msg = xstrdup(err_msg);
/* Create new job allocations */
submit_job_list = list_create(NULL);
pack_job_offset = 0;
_throttle_start(&active_rpc_cnt);
lock_slurmctld(job_write_lock);
START_TIMER; /* Restart after we have locks */
iter = list_iterator_create(job_req_list);
while ((job_desc_msg = (job_desc_msg_t *) list_next(iter))) {
if (!script)
script = xstrdup(job_desc_msg->script);
if (pack_job_offset && job_desc_msg->script) {
info("%s: Pack job %u offset %u has script, being ignored",
__func__, pack_job_id, pack_job_offset);
xfree(job_desc_msg->script);
}
if (pack_job_offset) {
/* Email notifications disable except for pack leader */
job_desc_msg->mail_type = 0;
xfree(job_desc_msg->mail_user);
}
if (!job_desc_msg->burst_buffer) {
xfree(job_desc_msg->script);
job_desc_msg->script =
bb_g_build_pack_script(script, pack_job_offset);
}
job_desc_msg->pack_job_offset = pack_job_offset;
error_code = job_allocate(job_desc_msg,
job_desc_msg->immediate, false,
NULL, alloc_only, uid, &job_ptr,
&err_msg, msg->protocol_version);
if (!job_ptr ||
(error_code && job_ptr->job_state == JOB_FAILED)) {
reject_job = true;
} else {
if (pack_job_id == 0) {
pack_job_id = job_ptr->job_id;
first_job_ptr = job_ptr;
alloc_only = 1;
}
snprintf(tmp_str, sizeof(tmp_str), "%u",
job_ptr->job_id);
if (jobid_hostset)
hostset_insert(jobid_hostset, tmp_str);
else
jobid_hostset = hostset_create(tmp_str);
job_ptr->pack_job_id = pack_job_id;
job_ptr->pack_job_offset = pack_job_offset++;
job_ptr->batch_flag = 1;
list_append(submit_job_list, job_ptr);
}
if (job_desc_msg->immediate &&
(error_code != SLURM_SUCCESS)) {
error_code = ESLURM_CAN_NOT_START_IMMEDIATELY;
reject_job = true;
}
if (reject_job)
break;
}
list_iterator_destroy(iter);
xfree(script);
if ((pack_job_id == 0) && !reject_job) {
info("%s: No error, but no pack_job_id", __func__);
error_code = SLURM_ERROR;
reject_job = true;
}
/* Validate limits on pack-job as a whole */
if (!reject_job &&
(accounting_enforce & ACCOUNTING_ENFORCE_LIMITS) &&
!acct_policy_validate_pack(submit_job_list)) {
info("Pack job %u exceeded association/QOS limit for user %u",
pack_job_id, job_uid);
error_code = ESLURM_ACCOUNTING_POLICY;
reject_job = true;
}
if (!reject_job) {
int buf_size = pack_job_offset * 16;
char *tmp_str = xmalloc(buf_size);
char *tmp_offset = tmp_str;
first_job_ptr->pack_job_list = submit_job_list;
hostset_ranged_string(jobid_hostset, buf_size, tmp_str);
if (tmp_str[0] == '[') {
tmp_offset = strchr(tmp_str, ']');
if (tmp_offset)
tmp_offset[0] = '\0';
tmp_offset = tmp_str + 1;
}
iter = list_iterator_create(submit_job_list);
while ((job_ptr = (struct job_record *) list_next(iter))) {
job_ptr->pack_job_id_set = xstrdup(tmp_offset);
if (slurmctld_conf.debug_flags &
DEBUG_FLAG_HETERO_JOBS) {
char buf[JBUFSIZ];
info("Submit %s",
jobid2fmt(job_ptr, buf, sizeof(buf)));
}
}
list_iterator_destroy(iter);
xfree(tmp_str);
}
unlock_slurmctld(job_write_lock);
_throttle_fini(&active_rpc_cnt);
send_msg:
END_TIMER2("_slurm_rpc_submit_batch_pack_job");
if (reject_job) {
info("%s: %s", __func__, slurm_strerror(error_code));
if (err_msg)
slurm_send_rc_err_msg(msg, error_code, err_msg);
else
slurm_send_rc_msg(msg, error_code);
if (submit_job_list) {
(void) list_for_each(submit_job_list, _pack_job_cancel,
NULL);
if (first_job_ptr)
first_job_ptr->pack_job_list = submit_job_list;
else
FREE_NULL_LIST(submit_job_list);
}
} else {
info("%s: JobId=%u %s", __func__, pack_job_id, TIME_STR);
/* send job_ID */
submit_msg.job_id = pack_job_id;
submit_msg.step_id = SLURM_BATCH_SCRIPT;
submit_msg.error_code = error_code;
submit_msg.job_submit_user_msg = job_submit_user_msg;
slurm_msg_t_init(&response_msg);
response_msg.flags = msg->flags;
response_msg.protocol_version = msg->protocol_version;
response_msg.conn = msg->conn;
response_msg.msg_type = RESPONSE_SUBMIT_BATCH_JOB;
response_msg.data = &submit_msg;
slurm_send_node_msg(msg->conn_fd, &response_msg);
schedule_job_save(); /* Has own locks */
}
if (jobid_hostset)
hostset_destroy(jobid_hostset);
xfree(err_msg);
xfree(job_submit_user_msg);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid.
Only trust MUNGE signed values, unless the RPC was signed by
SlurmUser or root.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide 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 _slurm_rpc_submit_batch_job(slurm_msg_t *msg)
{
static int active_rpc_cnt = 0;
int error_code = SLURM_SUCCESS;
DEF_TIMERS;
uint32_t job_id = 0, priority = 0;
struct job_record *job_ptr = NULL;
slurm_msg_t response_msg;
submit_response_msg_t submit_msg;
job_desc_msg_t *job_desc_msg = (job_desc_msg_t *) msg->data;
/* Locks: Read config, read job, read node, read partition */
slurmctld_lock_t job_read_lock = {
READ_LOCK, READ_LOCK, READ_LOCK, READ_LOCK, READ_LOCK };
/* Locks: Read config, write job, write node, read partition, read
* federation */
slurmctld_lock_t job_write_lock = {
READ_LOCK, WRITE_LOCK, WRITE_LOCK, READ_LOCK, READ_LOCK };
uid_t uid = g_slurm_auth_get_uid(msg->auth_cred,
slurmctld_config.auth_info);
char *err_msg = NULL, *job_submit_user_msg = NULL;
bool reject_job = false;
START_TIMER;
debug2("Processing RPC: REQUEST_SUBMIT_BATCH_JOB from uid=%d", uid);
if (slurmctld_config.submissions_disabled) {
info("Submissions disabled on system");
error_code = ESLURM_SUBMISSIONS_DISABLED;
reject_job = true;
goto send_msg;
}
/* do RPC call */
if ( (uid != job_desc_msg->user_id) && (!validate_super_user(uid)) ) {
/* NOTE: Super root can submit a batch job for any user */
error_code = ESLURM_USER_ID_MISSING;
error("Security violation, REQUEST_SUBMIT_BATCH_JOB from uid=%d",
uid);
}
if ((job_desc_msg->alloc_node == NULL) ||
(job_desc_msg->alloc_node[0] == '\0')) {
error_code = ESLURM_INVALID_NODE_NAME;
error("REQUEST_SUBMIT_BATCH_JOB lacks alloc_node from uid=%d",
uid);
}
dump_job_desc(job_desc_msg);
if (error_code == SLURM_SUCCESS) {
/* Locks are for job_submit plugin use */
lock_slurmctld(job_read_lock);
job_desc_msg->pack_job_offset = NO_VAL;
error_code = validate_job_create_req(job_desc_msg,uid,&err_msg);
unlock_slurmctld(job_read_lock);
}
/*
* In validate_job_create_req(), err_msg is currently only modified in
* the call to job_submit_plugin_submit. We save the err_msg in a temp
* char *job_submit_user_msg because err_msg can be overwritten later
* in the calls to fed_mgr_job_allocate and/or job_allocate, and we
* need the job submit plugin value to build the resource allocation
* response in the call to _build_alloc_msg.
*/
if (err_msg)
job_submit_user_msg = xstrdup(err_msg);
if (error_code) {
reject_job = true;
goto send_msg;
}
_throttle_start(&active_rpc_cnt);
lock_slurmctld(job_write_lock);
START_TIMER; /* Restart after we have locks */
if (fed_mgr_fed_rec) {
if (fed_mgr_job_allocate(msg, job_desc_msg, false, uid,
msg->protocol_version, &job_id,
&error_code, &err_msg))
reject_job = true;
} else {
/* Create new job allocation */
job_desc_msg->pack_job_offset = NO_VAL;
error_code = job_allocate(job_desc_msg,
job_desc_msg->immediate,
false, NULL, 0, uid, &job_ptr,
&err_msg,
msg->protocol_version);
if (!job_ptr ||
(error_code && job_ptr->job_state == JOB_FAILED))
reject_job = true;
else {
job_id = job_ptr->job_id;
priority = job_ptr->priority;
}
if (job_desc_msg->immediate &&
(error_code != SLURM_SUCCESS)) {
error_code = ESLURM_CAN_NOT_START_IMMEDIATELY;
reject_job = true;
}
}
unlock_slurmctld(job_write_lock);
_throttle_fini(&active_rpc_cnt);
send_msg:
END_TIMER2("_slurm_rpc_submit_batch_job");
if (reject_job) {
info("%s: %s", __func__, slurm_strerror(error_code));
if (err_msg)
slurm_send_rc_err_msg(msg, error_code, err_msg);
else
slurm_send_rc_msg(msg, error_code);
} else {
info("%s: JobId=%u InitPrio=%u %s",
__func__, job_id, priority, TIME_STR);
/* send job_ID */
submit_msg.job_id = job_id;
submit_msg.step_id = SLURM_BATCH_SCRIPT;
submit_msg.error_code = error_code;
submit_msg.job_submit_user_msg = job_submit_user_msg;
slurm_msg_t_init(&response_msg);
response_msg.flags = msg->flags;
response_msg.protocol_version = msg->protocol_version;
response_msg.conn = msg->conn;
response_msg.msg_type = RESPONSE_SUBMIT_BATCH_JOB;
response_msg.data = &submit_msg;
slurm_send_node_msg(msg->conn_fd, &response_msg);
schedule_job_save(); /* Has own locks */
schedule_node_save(); /* Has own locks */
queue_job_scheduler();
}
xfree(err_msg);
xfree(job_submit_user_msg);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid.
Only trust MUNGE signed values, unless the RPC was signed by
SlurmUser or root.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static bool _is_valid_will_run_user(job_desc_msg_t *job_desc_msg, uid_t uid)
{
char *account = NULL;
if ((uid == job_desc_msg->user_id) || validate_operator(uid))
return true;
if (job_desc_msg->job_id != NO_VAL) {
struct job_record *job_ptr;
job_ptr = find_job_record(job_desc_msg->job_id);
if (job_ptr)
account = job_ptr->account;
} else if (job_desc_msg->account)
account = job_desc_msg->account;
if (account && assoc_mgr_is_user_acct_coord(acct_db_conn, uid, account))
return true;
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid.
Only trust MUNGE signed values, unless the RPC was signed by
SlurmUser or root.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _rpc_batch_job(slurm_msg_t *msg, bool new_msg)
{
batch_job_launch_msg_t *req = (batch_job_launch_msg_t *)msg->data;
bool first_job_run;
int rc = SLURM_SUCCESS;
bool replied = false, revoked;
slurm_addr_t *cli = &msg->orig_addr;
if (new_msg) {
uid_t req_uid = g_slurm_auth_get_uid(msg->auth_cred,
conf->auth_info);
if (!_slurm_authorized_user(req_uid)) {
error("Security violation, batch launch RPC from uid %d",
req_uid);
rc = ESLURM_USER_ID_MISSING; /* or bad in this case */
goto done;
}
}
if (_launch_job_test(req->job_id)) {
error("Job %u already running, do not launch second copy",
req->job_id);
rc = ESLURM_DUPLICATE_JOB_ID; /* job already running */
_launch_job_fail(req->job_id, rc);
goto done;
}
slurm_cred_handle_reissue(conf->vctx, req->cred);
if (slurm_cred_revoked(conf->vctx, req->cred)) {
error("Job %u already killed, do not launch batch job",
req->job_id);
rc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */
goto done;
}
task_g_slurmd_batch_request(req->job_id, req); /* determine task affinity */
slurm_mutex_lock(&prolog_mutex);
first_job_run = !slurm_cred_jobid_cached(conf->vctx, req->job_id);
/* BlueGene prolog waits for partition boot and is very slow.
* On any system we might need to load environment variables
* for Moab (see --get-user-env), which could also be slow.
* Just reply now and send a separate kill job request if the
* prolog or launch fail. */
replied = true;
if (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) {
/* The slurmctld is no longer waiting for a reply.
* This typically indicates that the slurmd was
* blocked from memory and/or CPUs and the slurmctld
* has requeued the batch job request. */
error("Could not confirm batch launch for job %u, "
"aborting request", req->job_id);
rc = SLURM_COMMUNICATIONS_SEND_ERROR;
slurm_mutex_unlock(&prolog_mutex);
goto done;
}
/*
* Insert jobid into credential context to denote that
* we've now "seen" an instance of the job
*/
if (first_job_run) {
job_env_t job_env;
slurm_cred_insert_jobid(conf->vctx, req->job_id);
_add_job_running_prolog(req->job_id);
slurm_mutex_unlock(&prolog_mutex);
memset(&job_env, 0, sizeof(job_env_t));
job_env.jobid = req->job_id;
job_env.step_id = req->step_id;
job_env.node_list = req->nodes;
job_env.partition = req->partition;
job_env.spank_job_env = req->spank_job_env;
job_env.spank_job_env_size = req->spank_job_env_size;
job_env.uid = req->uid;
job_env.user_name = req->user_name;
/*
* Run job prolog on this node
*/
#if defined(HAVE_BG)
select_g_select_jobinfo_get(req->select_jobinfo,
SELECT_JOBDATA_BLOCK_ID,
&job_env.resv_id);
#elif defined(HAVE_ALPS_CRAY)
job_env.resv_id = select_g_select_jobinfo_xstrdup(
req->select_jobinfo, SELECT_PRINT_RESV_ID);
#endif
if (container_g_create(req->job_id))
error("container_g_create(%u): %m", req->job_id);
rc = _run_prolog(&job_env, req->cred);
xfree(job_env.resv_id);
if (rc) {
int term_sig, exit_status;
if (WIFSIGNALED(rc)) {
exit_status = 0;
term_sig = WTERMSIG(rc);
} else {
exit_status = WEXITSTATUS(rc);
term_sig = 0;
}
error("[job %u] prolog failed status=%d:%d",
req->job_id, exit_status, term_sig);
_prolog_error(req, rc);
rc = ESLURMD_PROLOG_FAILED;
goto done;
}
} else {
slurm_mutex_unlock(&prolog_mutex);
_wait_for_job_running_prolog(req->job_id);
}
if (_get_user_env(req) < 0) {
bool requeue = _requeue_setup_env_fail();
if (requeue) {
rc = ESLURMD_SETUP_ENVIRONMENT_ERROR;
goto done;
}
}
_set_batch_job_limits(msg);
/* Since job could have been killed while the prolog was
* running (especially on BlueGene, which can take minutes
* for partition booting). Test if the credential has since
* been revoked and exit as needed. */
if (slurm_cred_revoked(conf->vctx, req->cred)) {
info("Job %u already killed, do not launch batch job",
req->job_id);
rc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */
goto done;
}
slurm_mutex_lock(&launch_mutex);
if (req->step_id == SLURM_BATCH_SCRIPT)
info("Launching batch job %u for UID %d",
req->job_id, req->uid);
else
info("Launching batch job %u.%u for UID %d",
req->job_id, req->step_id, req->uid);
debug3("_rpc_batch_job: call to _forkexec_slurmstepd");
rc = _forkexec_slurmstepd(LAUNCH_BATCH_JOB, (void *)req, cli, NULL,
(hostset_t)NULL, SLURM_PROTOCOL_VERSION);
debug3("_rpc_batch_job: return from _forkexec_slurmstepd: %d", rc);
slurm_mutex_unlock(&launch_mutex);
_launch_complete_add(req->job_id);
/* On a busy system, slurmstepd may take a while to respond,
* if the job was cancelled in the interim, run through the
* abort logic below. */
revoked = slurm_cred_revoked(conf->vctx, req->cred);
if (revoked)
_launch_complete_rm(req->job_id);
if (revoked && _is_batch_job_finished(req->job_id)) {
/* If configured with select/serial and the batch job already
* completed, consider the job sucessfully launched and do
* not repeat termination logic below, which in the worst case
* just slows things down with another message. */
revoked = false;
}
if (revoked) {
info("Job %u killed while launch was in progress",
req->job_id);
sleep(1); /* give slurmstepd time to create
* the communication socket */
_terminate_all_steps(req->job_id, true);
rc = ESLURMD_CREDENTIAL_REVOKED;
goto done;
}
done:
if (!replied) {
if (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) {
/* The slurmctld is no longer waiting for a reply.
* This typically indicates that the slurmd was
* blocked from memory and/or CPUs and the slurmctld
* has requeued the batch job request. */
error("Could not confirm batch launch for job %u, "
"aborting request", req->job_id);
rc = SLURM_COMMUNICATIONS_SEND_ERROR;
} else {
/* No need to initiate separate reply below */
rc = SLURM_SUCCESS;
}
}
if (rc != SLURM_SUCCESS) {
/* prolog or job launch failure,
* tell slurmctld that the job failed */
if (req->step_id == SLURM_BATCH_SCRIPT)
_launch_job_fail(req->job_id, rc);
else
_abort_step(req->job_id, req->step_id);
}
/*
* If job prolog failed or we could not reply,
* initiate message to slurmctld with current state
*/
if ((rc == ESLURMD_PROLOG_FAILED)
|| (rc == SLURM_COMMUNICATIONS_SEND_ERROR)
|| (rc == ESLURMD_SETUP_ENVIRONMENT_ERROR)) {
send_registration_msg(rc, false);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Validate gid and user_name values provided to slurmd up front.
Do not defer until later, and do not potentially miss out on proper
validation of the user_name field which can lead to improper authentication
handling.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _rpc_launch_tasks(slurm_msg_t *msg)
{
int errnum = SLURM_SUCCESS;
uint16_t port;
char host[MAXHOSTNAMELEN];
uid_t req_uid;
launch_tasks_request_msg_t *req = msg->data;
bool super_user = false;
bool mem_sort = false;
#ifndef HAVE_FRONT_END
bool first_job_run;
#endif
slurm_addr_t self;
slurm_addr_t *cli = &msg->orig_addr;
hostset_t step_hset = NULL;
job_mem_limits_t *job_limits_ptr;
int nodeid = 0;
bitstr_t *numa_bitmap = NULL;
#ifndef HAVE_FRONT_END
/* It is always 0 for front end systems */
nodeid = nodelist_find(req->complete_nodelist, conf->node_name);
#endif
req_uid = g_slurm_auth_get_uid(msg->auth_cred, conf->auth_info);
memcpy(&req->orig_addr, &msg->orig_addr, sizeof(slurm_addr_t));
super_user = _slurm_authorized_user(req_uid);
if ((super_user == false) && (req_uid != req->uid)) {
error("launch task request from uid %u",
(unsigned int) req_uid);
errnum = ESLURM_USER_ID_MISSING; /* or invalid user */
goto done;
}
slurm_get_ip_str(cli, &port, host, sizeof(host));
info("launch task %u.%u request from %u.%u@%s (port %hu)", req->job_id,
req->job_step_id, req->uid, req->gid, host, port);
/* this could be set previously and needs to be overwritten by
* this call for messages to work correctly for the new call */
env_array_overwrite(&req->env, "SLURM_SRUN_COMM_HOST", host);
req->envc = envcount(req->env);
#ifndef HAVE_FRONT_END
slurm_mutex_lock(&prolog_mutex);
first_job_run = !slurm_cred_jobid_cached(conf->vctx, req->job_id);
#endif
if (_check_job_credential(req, req_uid, nodeid, &step_hset,
msg->protocol_version) < 0) {
errnum = errno;
error("Invalid job credential from %ld@%s: %m",
(long) req_uid, host);
#ifndef HAVE_FRONT_END
slurm_mutex_unlock(&prolog_mutex);
#endif
goto done;
}
/* Must follow _check_job_credential(), which sets some req fields */
task_g_slurmd_launch_request(req->job_id, req, nodeid);
#ifndef HAVE_FRONT_END
if (first_job_run) {
int rc;
job_env_t job_env;
slurm_cred_insert_jobid(conf->vctx, req->job_id);
_add_job_running_prolog(req->job_id);
slurm_mutex_unlock(&prolog_mutex);
if (container_g_create(req->job_id))
error("container_g_create(%u): %m", req->job_id);
memset(&job_env, 0, sizeof(job_env_t));
job_env.jobid = req->job_id;
job_env.step_id = req->job_step_id;
job_env.node_list = req->complete_nodelist;
job_env.partition = req->partition;
job_env.spank_job_env = req->spank_job_env;
job_env.spank_job_env_size = req->spank_job_env_size;
job_env.uid = req->uid;
job_env.user_name = req->user_name;
rc = _run_prolog(&job_env, req->cred);
if (rc) {
int term_sig, exit_status;
if (WIFSIGNALED(rc)) {
exit_status = 0;
term_sig = WTERMSIG(rc);
} else {
exit_status = WEXITSTATUS(rc);
term_sig = 0;
}
error("[job %u] prolog failed status=%d:%d",
req->job_id, exit_status, term_sig);
errnum = ESLURMD_PROLOG_FAILED;
goto done;
}
/* Since the job could have been killed while the prolog was
* running, test if the credential has since been revoked
* and exit as needed. */
if (slurm_cred_revoked(conf->vctx, req->cred)) {
info("Job %u already killed, do not launch step %u.%u",
req->job_id, req->job_id, req->job_step_id);
errnum = ESLURMD_CREDENTIAL_REVOKED;
goto done;
}
} else {
slurm_mutex_unlock(&prolog_mutex);
_wait_for_job_running_prolog(req->job_id);
}
#endif
if (req->mem_bind_type & MEM_BIND_SORT) {
int task_cnt = -1;
if (req->tasks_to_launch)
task_cnt = (int) req->tasks_to_launch[nodeid];
mem_sort = true;
numa_bitmap = _build_numa_bitmap(req->mem_bind_type,
req->mem_bind,
req->cpu_bind_type,
req->cpu_bind, task_cnt);
}
node_features_g_step_config(mem_sort, numa_bitmap);
FREE_NULL_BITMAP(numa_bitmap);
if (req->job_mem_lim || req->step_mem_lim) {
step_loc_t step_info;
slurm_mutex_lock(&job_limits_mutex);
if (!job_limits_list)
job_limits_list = list_create(_job_limits_free);
step_info.jobid = req->job_id;
step_info.stepid = req->job_step_id;
job_limits_ptr = list_find_first (job_limits_list,
_step_limits_match,
&step_info);
if (!job_limits_ptr) {
job_limits_ptr = xmalloc(sizeof(job_mem_limits_t));
job_limits_ptr->job_id = req->job_id;
job_limits_ptr->job_mem = req->job_mem_lim;
job_limits_ptr->step_id = req->job_step_id;
job_limits_ptr->step_mem = req->step_mem_lim;
#if _LIMIT_INFO
info("AddLim step:%u.%u job_mem:%"PRIu64" "
"step_mem:%"PRIu64"",
job_limits_ptr->job_id, job_limits_ptr->step_id,
job_limits_ptr->job_mem,
job_limits_ptr->step_mem);
#endif
list_append(job_limits_list, job_limits_ptr);
}
slurm_mutex_unlock(&job_limits_mutex);
}
slurm_get_stream_addr(msg->conn_fd, &self);
debug3("_rpc_launch_tasks: call to _forkexec_slurmstepd");
errnum = _forkexec_slurmstepd(LAUNCH_TASKS, (void *)req, cli, &self,
step_hset, msg->protocol_version);
debug3("_rpc_launch_tasks: return from _forkexec_slurmstepd");
_launch_complete_add(req->job_id);
done:
if (step_hset)
hostset_destroy(step_hset);
if (slurm_send_rc_msg(msg, errnum) < 0) {
char addr_str[32];
slurm_print_slurm_addr(&msg->address, addr_str,
sizeof(addr_str));
error("_rpc_launch_tasks: unable to send return code to "
"address:port=%s msg_type=%u: %m",
addr_str, msg->msg_type);
/*
* Rewind credential so that srun may perform retry
*/
slurm_cred_rewind(conf->vctx, req->cred); /* ignore errors */
} else if (errnum == SLURM_SUCCESS) {
save_cred_state(conf->vctx);
task_g_slurmd_reserve_resources(req->job_id, req, nodeid);
}
/*
* If job prolog failed, indicate failure to slurmctld
*/
if (errnum == ESLURMD_PROLOG_FAILED)
send_registration_msg(errnum, false);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Validate gid and user_name values provided to slurmd up front.
Do not defer until later, and do not potentially miss out on proper
validation of the user_name field which can lead to improper authentication
handling.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _send_slurmstepd_init(int fd, int type, void *req,
slurm_addr_t *cli, slurm_addr_t *self,
hostset_t step_hset, uint16_t protocol_version)
{
int len = 0;
Buf buffer = NULL;
slurm_msg_t msg;
uid_t uid = (uid_t)-1;
gid_t gid = (uid_t)-1;
gids_t *gids = NULL;
int rank, proto;
int parent_rank, children, depth, max_depth;
char *parent_alias = NULL;
char *user_name = NULL;
slurm_addr_t parent_addr = {0};
char pwd_buffer[PW_BUF_SIZE];
struct passwd pwd, *pwd_result;
slurm_msg_t_init(&msg);
/* send type over to slurmstepd */
safe_write(fd, &type, sizeof(int));
/* step_hset can be NULL for batch scripts OR if the job was submitted
* by SlurmUser or root using the --no-allocate/-Z option and the job
* job credential validation by _check_job_credential() failed. If the
* job credential did not validate, then it did not come from slurmctld
* and there is no reason to send step completion messages to slurmctld.
*/
if (step_hset == NULL) {
bool send_error = false;
if (type == LAUNCH_TASKS) {
launch_tasks_request_msg_t *launch_req;
launch_req = (launch_tasks_request_msg_t *) req;
if (launch_req->job_step_id != SLURM_EXTERN_CONT)
send_error = true;
}
if (send_error) {
info("task rank unavailable due to invalid job "
"credential, step completion RPC impossible");
}
rank = -1;
parent_rank = -1;
children = 0;
depth = 0;
max_depth = 0;
} else if ((type == LAUNCH_TASKS) &&
(((launch_tasks_request_msg_t *)req)->alias_list)) {
/* In the cloud, each task talks directly to the slurmctld
* since node addressing is abnormal */
rank = 0;
parent_rank = -1;
children = 0;
depth = 0;
max_depth = 0;
} else {
#ifndef HAVE_FRONT_END
int count;
count = hostset_count(step_hset);
rank = hostset_find(step_hset, conf->node_name);
reverse_tree_info(rank, count, REVERSE_TREE_WIDTH,
&parent_rank, &children,
&depth, &max_depth);
if (rank > 0) { /* rank 0 talks directly to the slurmctld */
int rc;
/* Find the slurm_addr_t of this node's parent slurmd
* in the step host list */
parent_alias = hostset_nth(step_hset, parent_rank);
rc = slurm_conf_get_addr(parent_alias, &parent_addr);
if (rc != SLURM_SUCCESS) {
error("Failed looking up address for "
"NodeName %s", parent_alias);
/* parent_rank = -1; */
}
}
#else
/* In FRONT_END mode, one slurmd pretends to be all
* NodeNames, so we can't compare conf->node_name
* to the NodeNames in step_hset. Just send step complete
* RPC directly to the controller.
*/
rank = 0;
parent_rank = -1;
children = 0;
depth = 0;
max_depth = 0;
#endif
}
debug3("slurmstepd rank %d (%s), parent rank %d (%s), "
"children %d, depth %d, max_depth %d",
rank, conf->node_name,
parent_rank, parent_alias ? parent_alias : "NONE",
children, depth, max_depth);
if (parent_alias)
free(parent_alias);
/* send reverse-tree info to the slurmstepd */
safe_write(fd, &rank, sizeof(int));
safe_write(fd, &parent_rank, sizeof(int));
safe_write(fd, &children, sizeof(int));
safe_write(fd, &depth, sizeof(int));
safe_write(fd, &max_depth, sizeof(int));
safe_write(fd, &parent_addr, sizeof(slurm_addr_t));
/* send conf over to slurmstepd */
if (_send_slurmd_conf_lite(fd, conf) < 0)
goto rwfail;
/* send cli address over to slurmstepd */
buffer = init_buf(0);
slurm_pack_slurm_addr(cli, buffer);
len = get_buf_offset(buffer);
safe_write(fd, &len, sizeof(int));
safe_write(fd, get_buf_data(buffer), len);
free_buf(buffer);
buffer = NULL;
/* send self address over to slurmstepd */
if (self) {
buffer = init_buf(0);
slurm_pack_slurm_addr(self, buffer);
len = get_buf_offset(buffer);
safe_write(fd, &len, sizeof(int));
safe_write(fd, get_buf_data(buffer), len);
free_buf(buffer);
buffer = NULL;
} else {
len = 0;
safe_write(fd, &len, sizeof(int));
}
/* Send GRES information to slurmstepd */
gres_plugin_send_stepd(fd);
/* send cpu_frequency info to slurmstepd */
cpu_freq_send_info(fd);
/* send req over to slurmstepd */
switch(type) {
case LAUNCH_BATCH_JOB:
gid = (uid_t)((batch_job_launch_msg_t *)req)->gid;
uid = (uid_t)((batch_job_launch_msg_t *)req)->uid;
user_name = ((batch_job_launch_msg_t *)req)->user_name;
msg.msg_type = REQUEST_BATCH_JOB_LAUNCH;
break;
case LAUNCH_TASKS:
/*
* The validity of req->uid was verified against the
* auth credential in _rpc_launch_tasks(). req->gid
* has NOT yet been checked!
*/
gid = (uid_t)((launch_tasks_request_msg_t *)req)->gid;
uid = (uid_t)((launch_tasks_request_msg_t *)req)->uid;
user_name = ((launch_tasks_request_msg_t *)req)->user_name;
msg.msg_type = REQUEST_LAUNCH_TASKS;
break;
default:
error("Was sent a task I didn't understand");
break;
}
buffer = init_buf(0);
msg.data = req;
if (protocol_version == (uint16_t)NO_VAL)
proto = SLURM_PROTOCOL_VERSION;
else
proto = protocol_version;
msg.protocol_version = (uint16_t)proto;
pack_msg(&msg, buffer);
len = get_buf_offset(buffer);
safe_write(fd, &proto, sizeof(int));
safe_write(fd, &len, sizeof(int));
safe_write(fd, get_buf_data(buffer), len);
free_buf(buffer);
buffer = NULL;
#ifdef HAVE_NATIVE_CRAY
/* Try to avoid calling this on a system which is a native
* cray. getpwuid_r is slow on the compute nodes and this has
* in theory been verified earlier.
*/
if (!user_name) {
#endif
/* send cached group ids array for the relevant uid */
debug3("_send_slurmstepd_init: call to getpwuid_r");
if (slurm_getpwuid_r(uid, &pwd, pwd_buffer, PW_BUF_SIZE,
&pwd_result) || (pwd_result == NULL)) {
error("%s: getpwuid_r: %m", __func__);
len = 0;
safe_write(fd, &len, sizeof(int));
errno = ESLURMD_UID_NOT_FOUND;
return errno;
}
debug3("%s: return from getpwuid_r", __func__);
if (gid != pwd_result->pw_gid) {
debug("%s: Changing gid from %d to %d",
__func__, gid, pwd_result->pw_gid);
}
gid = pwd_result->pw_gid;
if (!user_name)
user_name = pwd_result->pw_name;
#ifdef HAVE_NATIVE_CRAY
}
#endif
if (!user_name) {
/* Sanity check since gids_cache_lookup will fail
* with a NULL. */
error("%s: No user name for %d: %m", __func__, uid);
len = 0;
safe_write(fd, &len, sizeof(int));
errno = ESLURMD_UID_NOT_FOUND;
return errno;
}
if ((gids = _gids_cache_lookup(user_name, gid))) {
int i;
uint32_t tmp32;
safe_write(fd, &gids->ngids, sizeof(int));
for (i = 0; i < gids->ngids; i++) {
tmp32 = (uint32_t)gids->gids[i];
safe_write(fd, &tmp32, sizeof(uint32_t));
}
_dealloc_gids(gids);
} else {
len = 0;
safe_write(fd, &len, sizeof(int));
}
return 0;
rwfail:
if (buffer)
free_buf(buffer);
error("_send_slurmstepd_init failed");
return errno;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Validate gid and user_name values provided to slurmd up front.
Do not defer until later, and do not potentially miss out on proper
validation of the user_name field which can lead to improper authentication
handling.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide 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 _spawn_prolog_stepd(slurm_msg_t *msg)
{
prolog_launch_msg_t *req = (prolog_launch_msg_t *)msg->data;
launch_tasks_request_msg_t *launch_req;
slurm_addr_t self;
slurm_addr_t *cli = &msg->orig_addr;
int i;
launch_req = xmalloc(sizeof(launch_tasks_request_msg_t));
launch_req->alias_list = req->alias_list;
launch_req->complete_nodelist = req->nodes;
launch_req->cpus_per_task = 1;
launch_req->cred = req->cred;
launch_req->cwd = req->work_dir;
launch_req->efname = "/dev/null";
launch_req->gid = req->gid;
launch_req->global_task_ids = xmalloc(sizeof(uint32_t *)
* req->nnodes);
launch_req->ifname = "/dev/null";
launch_req->job_id = req->job_id;
launch_req->job_mem_lim = req->job_mem_limit;
launch_req->job_step_id = SLURM_EXTERN_CONT;
launch_req->nnodes = req->nnodes;
launch_req->ntasks = req->nnodes;
launch_req->ofname = "/dev/null";
launch_req->partition = req->partition;
launch_req->spank_job_env_size = req->spank_job_env_size;
launch_req->spank_job_env = req->spank_job_env;
launch_req->step_mem_lim = req->job_mem_limit;
launch_req->tasks_to_launch = xmalloc(sizeof(uint16_t)
* req->nnodes);
launch_req->uid = req->uid;
for (i = 0; i < req->nnodes; i++) {
uint32_t *tmp32 = xmalloc(sizeof(uint32_t));
*tmp32 = i;
launch_req->global_task_ids[i] = tmp32;
launch_req->tasks_to_launch[i] = 1;
}
slurm_get_stream_addr(msg->conn_fd, &self);
/* Since job could have been killed while the prolog was
* running (especially on BlueGene, which can take minutes
* for partition booting). Test if the credential has since
* been revoked and exit as needed. */
if (slurm_cred_revoked(conf->vctx, req->cred)) {
info("Job %u already killed, do not launch extern step",
req->job_id);
} else {
hostset_t step_hset = hostset_create(req->nodes);
int rc;
debug3("%s: call to _forkexec_slurmstepd", __func__);
rc = _forkexec_slurmstepd(
LAUNCH_TASKS, (void *)launch_req, cli,
&self, step_hset, msg->protocol_version);
debug3("%s: return from _forkexec_slurmstepd %d", __func__, rc);
if (rc != SLURM_SUCCESS)
_launch_job_fail(req->job_id, rc);
if (step_hset)
hostset_destroy(step_hset);
}
for (i = 0; i < req->nnodes; i++)
xfree(launch_req->global_task_ids[i]);
xfree(launch_req->global_task_ids);
xfree(launch_req->tasks_to_launch);
xfree(launch_req);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Validate gid and user_name values provided to slurmd up front.
Do not defer until later, and do not potentially miss out on proper
validation of the user_name field which can lead to improper authentication
handling.
CVE-2018-10995.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zstatus(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
switch (r_type(op)) {
case t_file:
{
stream *s;
make_bool(op, (file_is_valid(s, op) ? 1 : 0));
}
return 0;
case t_string:
{
gs_parsed_file_name_t pname;
struct stat fstat;
int code = parse_file_name(op, &pname,
i_ctx_p->LockFilePermissions, imemory);
if (code < 0) {
if (code == gs_error_undefinedfilename) {
make_bool(op, 0);
code = 0;
}
return code;
}
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = (*pname.iodev->procs.file_status)(pname.iodev,
pname.fname, &fstat);
switch (code) {
case 0:
check_ostack(4);
/*
* Check to make sure that the file size fits into
* a PostScript integer. (On some systems, long is
* 32 bits, but file sizes are 64 bits.)
*/
push(4);
make_int(op - 4, stat_blocks(&fstat));
make_int(op - 3, fstat.st_size);
/*
* We can't check the value simply by using ==,
* because signed/unsigned == does the wrong thing.
* Instead, since integer assignment only keeps the
* bottom bits, we convert the values to double
* and then test for equality. This handles all
* cases of signed/unsigned or width mismatch.
*/
if ((double)op[-4].value.intval !=
(double)stat_blocks(&fstat) ||
(double)op[-3].value.intval !=
(double)fstat.st_size
)
return_error(gs_error_limitcheck);
make_int(op - 2, fstat.st_mtime);
make_int(op - 1, fstat.st_ctime);
make_bool(op, 1);
break;
case gs_error_undefinedfilename:
make_bool(op, 0);
code = 0;
}
gs_free_file_name(&pname, "status");
return code;
}
default:
return_op_typecheck(op);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Bug 697193: status operator honour SAFER option'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t match_busid_show(struct device_driver *drv, char *buf)
{
int i;
char *out = buf;
spin_lock(&busid_table_lock);
for (i = 0; i < MAX_BUSID; i++)
if (busid_table[i].name[0])
out += sprintf(out, "%s ", busid_table[i].name);
spin_unlock(&busid_table_lock);
out += sprintf(out, "\n");
return out - buf;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors
usbip_host updates device status without holding lock from stub probe,
disconnect and rebind code paths. When multiple requests to import a
device are received, these unprotected code paths step all over each
other and drive fails with NULL-ptr deref and use-after-free errors.
The driver uses a table lock to protect the busid array for adding and
deleting busids to the table. However, the probe, disconnect and rebind
paths get the busid table entry and update the status without holding
the busid table lock. Add a new finer grain lock to protect the busid
entry. This new lock will be held to search and update the busid entry
fields from get_busid_idx(), add_match_busid() and del_match_busid().
match_busid_show() does the same to access the busid entry fields.
get_busid_priv() changed to return the pointer to the busid entry holding
the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()
call put_busid_priv() to release the busid lock before returning. This
changes fixes the unprotected code paths eliminating the race conditions
in updating the busid entries.
Reported-by: Jakub Jirasek
Signed-off-by: Shuah Khan (Samsung OSG) <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 init_busid_table(void)
{
/*
* This also sets the bus_table[i].status to
* STUB_BUSID_OTHER, which is 0.
*/
memset(busid_table, 0, sizeof(busid_table));
spin_lock_init(&busid_table_lock);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors
usbip_host updates device status without holding lock from stub probe,
disconnect and rebind code paths. When multiple requests to import a
device are received, these unprotected code paths step all over each
other and drive fails with NULL-ptr deref and use-after-free errors.
The driver uses a table lock to protect the busid array for adding and
deleting busids to the table. However, the probe, disconnect and rebind
paths get the busid table entry and update the status without holding
the busid table lock. Add a new finer grain lock to protect the busid
entry. This new lock will be held to search and update the busid entry
fields from get_busid_idx(), add_match_busid() and del_match_busid().
match_busid_show() does the same to access the busid entry fields.
get_busid_priv() changed to return the pointer to the busid entry holding
the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()
call put_busid_priv() to release the busid lock before returning. This
changes fixes the unprotected code paths eliminating the race conditions
in updating the busid entries.
Reported-by: Jakub Jirasek
Signed-off-by: Shuah Khan (Samsung OSG) <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 stub_probe(struct usb_device *udev)
{
struct stub_device *sdev = NULL;
const char *udev_busid = dev_name(&udev->dev);
struct bus_id_priv *busid_priv;
int rc;
dev_dbg(&udev->dev, "Enter probe\n");
/* check we should claim or not by busid_table */
busid_priv = get_busid_priv(udev_busid);
if (!busid_priv || (busid_priv->status == STUB_BUSID_REMOV) ||
(busid_priv->status == STUB_BUSID_OTHER)) {
dev_info(&udev->dev,
"%s is not in match_busid table... skip!\n",
udev_busid);
/*
* Return value should be ENODEV or ENOXIO to continue trying
* other matched drivers by the driver core.
* See driver_probe_device() in driver/base/dd.c
*/
return -ENODEV;
}
if (udev->descriptor.bDeviceClass == USB_CLASS_HUB) {
dev_dbg(&udev->dev, "%s is a usb hub device... skip!\n",
udev_busid);
return -ENODEV;
}
if (!strcmp(udev->bus->bus_name, "vhci_hcd")) {
dev_dbg(&udev->dev,
"%s is attached on vhci_hcd... skip!\n",
udev_busid);
return -ENODEV;
}
/* ok, this is my device */
sdev = stub_device_alloc(udev);
if (!sdev)
return -ENOMEM;
dev_info(&udev->dev,
"usbip-host: register new device (bus %u dev %u)\n",
udev->bus->busnum, udev->devnum);
busid_priv->shutdown_busid = 0;
/* set private data to usb_device */
dev_set_drvdata(&udev->dev, sdev);
busid_priv->sdev = sdev;
busid_priv->udev = udev;
/*
* Claim this hub port.
* It doesn't matter what value we pass as owner
* (struct dev_state) as long as it is unique.
*/
rc = usb_hub_claim_port(udev->parent, udev->portnum,
(struct usb_dev_state *) udev);
if (rc) {
dev_dbg(&udev->dev, "unable to claim port\n");
goto err_port;
}
rc = stub_add_files(&udev->dev);
if (rc) {
dev_err(&udev->dev, "stub_add_files for %s\n", udev_busid);
goto err_files;
}
busid_priv->status = STUB_BUSID_ALLOC;
return 0;
err_files:
usb_hub_release_port(udev->parent, udev->portnum,
(struct usb_dev_state *) udev);
err_port:
dev_set_drvdata(&udev->dev, NULL);
usb_put_dev(udev);
busid_priv->sdev = NULL;
stub_device_free(sdev);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors
usbip_host updates device status without holding lock from stub probe,
disconnect and rebind code paths. When multiple requests to import a
device are received, these unprotected code paths step all over each
other and drive fails with NULL-ptr deref and use-after-free errors.
The driver uses a table lock to protect the busid array for adding and
deleting busids to the table. However, the probe, disconnect and rebind
paths get the busid table entry and update the status without holding
the busid table lock. Add a new finer grain lock to protect the busid
entry. This new lock will be held to search and update the busid entry
fields from get_busid_idx(), add_match_busid() and del_match_busid().
match_busid_show() does the same to access the busid entry fields.
get_busid_priv() changed to return the pointer to the busid entry holding
the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()
call put_busid_priv() to release the busid lock before returning. This
changes fixes the unprotected code paths eliminating the race conditions
in updating the busid entries.
Reported-by: Jakub Jirasek
Signed-off-by: Shuah Khan (Samsung OSG) <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 ssize_t rebind_store(struct device_driver *dev, const char *buf,
size_t count)
{
int ret;
int len;
struct bus_id_priv *bid;
/* buf length should be less that BUSID_SIZE */
len = strnlen(buf, BUSID_SIZE);
if (!(len < BUSID_SIZE))
return -EINVAL;
bid = get_busid_priv(buf);
if (!bid)
return -ENODEV;
/* mark the device for deletion so probe ignores it during rescan */
bid->status = STUB_BUSID_OTHER;
ret = do_rebind((char *) buf, bid);
if (ret < 0)
return ret;
/* delete device from busid_table */
del_match_busid((char *) buf);
return count;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors
usbip_host updates device status without holding lock from stub probe,
disconnect and rebind code paths. When multiple requests to import a
device are received, these unprotected code paths step all over each
other and drive fails with NULL-ptr deref and use-after-free errors.
The driver uses a table lock to protect the busid array for adding and
deleting busids to the table. However, the probe, disconnect and rebind
paths get the busid table entry and update the status without holding
the busid table lock. Add a new finer grain lock to protect the busid
entry. This new lock will be held to search and update the busid entry
fields from get_busid_idx(), add_match_busid() and del_match_busid().
match_busid_show() does the same to access the busid entry fields.
get_busid_priv() changed to return the pointer to the busid entry holding
the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()
call put_busid_priv() to release the busid lock before returning. This
changes fixes the unprotected code paths eliminating the race conditions
in updating the busid entries.
Reported-by: Jakub Jirasek
Signed-off-by: Shuah Khan (Samsung OSG) <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 stub_device_rebind(void)
{
#if IS_MODULE(CONFIG_USBIP_HOST)
struct bus_id_priv *busid_priv;
int i;
/* update status to STUB_BUSID_OTHER so probe ignores the device */
spin_lock(&busid_table_lock);
for (i = 0; i < MAX_BUSID; i++) {
if (busid_table[i].name[0] &&
busid_table[i].shutdown_busid) {
busid_priv = &(busid_table[i]);
busid_priv->status = STUB_BUSID_OTHER;
}
}
spin_unlock(&busid_table_lock);
/* now run rebind */
for (i = 0; i < MAX_BUSID; i++) {
if (busid_table[i].name[0] &&
busid_table[i].shutdown_busid) {
busid_priv = &(busid_table[i]);
do_rebind(busid_table[i].name, busid_priv);
}
}
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors
usbip_host updates device status without holding lock from stub probe,
disconnect and rebind code paths. When multiple requests to import a
device are received, these unprotected code paths step all over each
other and drive fails with NULL-ptr deref and use-after-free errors.
The driver uses a table lock to protect the busid array for adding and
deleting busids to the table. However, the probe, disconnect and rebind
paths get the busid table entry and update the status without holding
the busid table lock. Add a new finer grain lock to protect the busid
entry. This new lock will be held to search and update the busid entry
fields from get_busid_idx(), add_match_busid() and del_match_busid().
match_busid_show() does the same to access the busid entry fields.
get_busid_priv() changed to return the pointer to the busid entry holding
the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()
call put_busid_priv() to release the busid lock before returning. This
changes fixes the unprotected code paths eliminating the race conditions
in updating the busid entries.
Reported-by: Jakub Jirasek
Signed-off-by: Shuah Khan (Samsung OSG) <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 put_busid_priv(struct bus_id_priv *bid)
{
spin_unlock(&bid->busid_lock);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix bad unlock balance during stub_probe()
stub_probe() calls put_busid_priv() in an error path when device isn't
found in the busid_table. Fix it by making put_busid_priv() safe to be
called with null struct bus_id_priv pointer.
This problem happens when "usbip bind" is run without loading usbip_host
driver and then running modprobe. The first failed bind attempt unbinds
the device from the original driver and when usbip_host is modprobed,
stub_probe() runs and doesn't find the device in its busid table and calls
put_busid_priv(0 with null bus_id_priv pointer.
usbip-host 3-10.2: 3-10.2 is not in match_busid table... skip!
[ 367.359679] =====================================
[ 367.359681] WARNING: bad unlock balance detected!
[ 367.359683] 4.17.0-rc4+ #5 Not tainted
[ 367.359685] -------------------------------------
[ 367.359688] modprobe/2768 is trying to release lock (
[ 367.359689]
==================================================================
[ 367.359696] BUG: KASAN: null-ptr-deref in print_unlock_imbalance_bug+0x99/0x110
[ 367.359699] Read of size 8 at addr 0000000000000058 by task modprobe/2768
[ 367.359705] CPU: 4 PID: 2768 Comm: modprobe Not tainted 4.17.0-rc4+ #5
Fixes: 22076557b07c ("usbip: usbip_host: fix NULL-ptr deref and use-after-free errors") in usb-linus
Signed-off-by: Shuah Khan (Samsung OSG) <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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: includeFile(FileInfo *nested, CharsString *includedFile,
CharacterClass **characterClasses,
TranslationTableCharacterAttributes *characterClassAttribute,
short opcodeLengths[], TranslationTableOffset *newRuleOffset,
TranslationTableRule **newRule, RuleName **ruleNames,
TranslationTableHeader **table) {
int k;
char includeThis[MAXSTRING];
char **tableFiles;
int rv;
for (k = 0; k < includedFile->length; k++)
includeThis[k] = (char)includedFile->chars[k];
includeThis[k] = 0;
tableFiles = _lou_resolveTable(includeThis, nested->fileName);
if (tableFiles == NULL) {
errorCount++;
return 0;
}
if (tableFiles[1] != NULL) {
errorCount++;
free_tablefiles(tableFiles);
_lou_logMessage(LOG_ERROR,
"Table list not supported in include statement: 'include %s'",
includeThis);
return 0;
}
rv = compileFile(*tableFiles, characterClasses, characterClassAttribute,
opcodeLengths, newRuleOffset, newRule, ruleNames, table);
free_tablefiles(tableFiles);
return rv;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Fix yet another buffer overflow in the braille table parser
Reported by Henri Salo
Fixes #592'</s> |
<s>[INST] Given the following code containing errors, provide 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 handle_error(Sass_Context* c_ctx) {
try {
throw;
}
catch (Exception::Base& e) {
std::stringstream msg_stream;
std::string cwd(Sass::File::get_cwd());
std::string msg_prefix(e.errtype());
bool got_newline = false;
msg_stream << msg_prefix << ": ";
const char* msg = e.what();
while (msg && *msg) {
if (*msg == '\r') {
got_newline = true;
}
else if (*msg == '\n') {
got_newline = true;
}
else if (got_newline) {
msg_stream << std::string(msg_prefix.size() + 2, ' ');
got_newline = false;
}
msg_stream << *msg;
++msg;
}
if (!got_newline) msg_stream << "\n";
if (e.traces.empty()) {
// we normally should have some traces, still here as a fallback
std::string rel_path(Sass::File::abs2rel(e.pstate.path, cwd, cwd));
msg_stream << std::string(msg_prefix.size() + 2, ' ');
msg_stream << " on line " << e.pstate.line + 1 << " of " << rel_path << "\n";
}
else {
std::string rel_path(Sass::File::abs2rel(e.pstate.path, cwd, cwd));
msg_stream << traces_to_string(e.traces, " ");
}
// now create the code trace (ToDo: maybe have util functions?)
if (e.pstate.line != std::string::npos && e.pstate.column != std::string::npos) {
size_t lines = e.pstate.line;
const char* line_beg = e.pstate.src;
// scan through src until target line
// move line_beg pointer to line start
while (line_beg && *line_beg && lines != 0) {
if (*line_beg == '\n') --lines;
utf8::unchecked::next(line_beg);
}
const char* line_end = line_beg;
// move line_end before next newline character
while (line_end && *line_end && *line_end != '\n') {
if (*line_end == '\n') break;
if (*line_end == '\r') break;
utf8::unchecked::next(line_end);
}
if (line_end && *line_end != 0) ++ line_end;
size_t line_len = line_end - line_beg;
size_t move_in = 0; size_t shorten = 0;
size_t left_chars = 42; size_t max_chars = 76;
// reported excerpt should not exceed `max_chars` chars
if (e.pstate.column > line_len) left_chars = e.pstate.column;
if (e.pstate.column > left_chars) move_in = e.pstate.column - left_chars;
if (line_len > max_chars + move_in) shorten = line_len - move_in - max_chars;
utf8::advance(line_beg, move_in, line_end);
utf8::retreat(line_end, shorten, line_beg);
std::string sanitized; std::string marker(e.pstate.column - move_in, '-');
utf8::replace_invalid(line_beg, line_end, std::back_inserter(sanitized));
msg_stream << ">> " << sanitized << "\n";
msg_stream << " " << marker << "^\n";
}
JsonNode* json_err = json_mkobject();
json_append_member(json_err, "status", json_mknumber(1));
json_append_member(json_err, "file", json_mkstring(e.pstate.path));
json_append_member(json_err, "line", json_mknumber((double)(e.pstate.line + 1)));
json_append_member(json_err, "column", json_mknumber((double)(e.pstate.column + 1)));
json_append_member(json_err, "message", json_mkstring(e.what()));
json_append_member(json_err, "formatted", json_mkstream(msg_stream));
try { c_ctx->error_json = json_stringify(json_err, " "); }
catch (...) {}
c_ctx->error_message = sass_copy_string(msg_stream.str());
c_ctx->error_text = sass_copy_c_string(e.what());
c_ctx->error_status = 1;
c_ctx->error_file = sass_copy_c_string(e.pstate.path);
c_ctx->error_line = e.pstate.line + 1;
c_ctx->error_column = e.pstate.column + 1;
c_ctx->error_src = e.pstate.src;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
json_delete(json_err);
}
catch (std::bad_alloc& ba) {
std::stringstream msg_stream;
JsonNode* json_err = json_mkobject();
msg_stream << "Unable to allocate memory: " << ba.what() << std::endl;
json_append_member(json_err, "status", json_mknumber(2));
json_append_member(json_err, "message", json_mkstring(ba.what()));
json_append_member(json_err, "formatted", json_mkstream(msg_stream));
try { c_ctx->error_json = json_stringify(json_err, " "); }
catch (...) {}
c_ctx->error_message = sass_copy_string(msg_stream.str());
c_ctx->error_text = sass_copy_c_string(ba.what());
c_ctx->error_status = 2;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
json_delete(json_err);
}
catch (std::exception& e) {
std::stringstream msg_stream;
JsonNode* json_err = json_mkobject();
msg_stream << "Internal Error: " << e.what() << std::endl;
json_append_member(json_err, "status", json_mknumber(3));
json_append_member(json_err, "message", json_mkstring(e.what()));
json_append_member(json_err, "formatted", json_mkstream(msg_stream));
try { c_ctx->error_json = json_stringify(json_err, " "); }
catch (...) {}
c_ctx->error_message = sass_copy_string(msg_stream.str());
c_ctx->error_text = sass_copy_c_string(e.what());
c_ctx->error_status = 3;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
json_delete(json_err);
}
catch (std::string& e) {
std::stringstream msg_stream;
JsonNode* json_err = json_mkobject();
msg_stream << "Internal Error: " << e << std::endl;
json_append_member(json_err, "status", json_mknumber(4));
json_append_member(json_err, "message", json_mkstring(e.c_str()));
json_append_member(json_err, "formatted", json_mkstream(msg_stream));
try { c_ctx->error_json = json_stringify(json_err, " "); }
catch (...) {}
c_ctx->error_message = sass_copy_string(msg_stream.str());
c_ctx->error_text = sass_copy_c_string(e.c_str());
c_ctx->error_status = 4;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
json_delete(json_err);
}
catch (const char* e) {
std::stringstream msg_stream;
JsonNode* json_err = json_mkobject();
msg_stream << "Internal Error: " << e << std::endl;
json_append_member(json_err, "status", json_mknumber(4));
json_append_member(json_err, "message", json_mkstring(e));
json_append_member(json_err, "formatted", json_mkstream(msg_stream));
try { c_ctx->error_json = json_stringify(json_err, " "); }
catch (...) {}
c_ctx->error_message = sass_copy_string(msg_stream.str());
c_ctx->error_text = sass_copy_c_string(e);
c_ctx->error_status = 4;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
json_delete(json_err);
}
catch (...) {
std::stringstream msg_stream;
JsonNode* json_err = json_mkobject();
msg_stream << "Unknown error occurred" << std::endl;
json_append_member(json_err, "status", json_mknumber(5));
json_append_member(json_err, "message", json_mkstring("unknown"));
try { c_ctx->error_json = json_stringify(json_err, " "); }
catch (...) {}
c_ctx->error_message = sass_copy_string(msg_stream.str());
c_ctx->error_text = sass_copy_c_string("unknown");
c_ctx->error_status = 5;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
json_delete(json_err);
}
return c_ctx->error_status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Optimize line_begin/end search in `handle_error`
There is no need to advance by UTF-8 code points when searching for an
ASCII character, because UTF-8 is a prefix-free encoding.'</s> |
<s>[INST] Given the following code containing errors, provide 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 Inspect::operator()(Color_Ptr c)
{
// output the final token
std::stringstream ss;
// original color name
// maybe an unknown token
std::string name = c->disp();
// resolved color
std::string res_name = name;
double r = Sass::round(cap_channel<0xff>(c->r()), opt.precision);
double g = Sass::round(cap_channel<0xff>(c->g()), opt.precision);
double b = Sass::round(cap_channel<0xff>(c->b()), opt.precision);
double a = cap_channel<1> (c->a());
// get color from given name (if one was given at all)
if (name != "" && name_to_color(name)) {
Color_Ptr_Const n = name_to_color(name);
r = Sass::round(cap_channel<0xff>(n->r()), opt.precision);
g = Sass::round(cap_channel<0xff>(n->g()), opt.precision);
b = Sass::round(cap_channel<0xff>(n->b()), opt.precision);
a = cap_channel<1> (n->a());
}
// otherwise get the possible resolved color name
else {
double numval = r * 0x10000 + g * 0x100 + b;
if (color_to_name(numval))
res_name = color_to_name(numval);
}
std::stringstream hexlet;
// dart sass compressed all colors in regular css always
// ruby sass and libsass does it only when not delayed
// since color math is going to be removed, this can go too
bool compressed = opt.output_style == COMPRESSED;
hexlet << '#' << std::setw(1) << std::setfill('0');
// create a short color hexlet if there is any need for it
if (compressed && is_color_doublet(r, g, b) && a == 1) {
hexlet << std::hex << std::setw(1) << (static_cast<unsigned long>(r) >> 4);
hexlet << std::hex << std::setw(1) << (static_cast<unsigned long>(g) >> 4);
hexlet << std::hex << std::setw(1) << (static_cast<unsigned long>(b) >> 4);
} else {
hexlet << std::hex << std::setw(2) << static_cast<unsigned long>(r);
hexlet << std::hex << std::setw(2) << static_cast<unsigned long>(g);
hexlet << std::hex << std::setw(2) << static_cast<unsigned long>(b);
}
if (compressed && !c->is_delayed()) name = "";
if (opt.output_style == INSPECT && a >= 1) {
append_token(hexlet.str(), c);
return;
}
// retain the originally specified color definition if unchanged
if (name != "") {
ss << name;
}
else if (a >= 1) {
if (res_name != "") {
if (compressed && hexlet.str().size() < res_name.size()) {
ss << hexlet.str();
} else {
ss << res_name;
}
}
else {
ss << hexlet.str();
}
}
else {
ss << "rgba(";
ss << static_cast<unsigned long>(r) << ",";
if (!compressed) ss << " ";
ss << static_cast<unsigned long>(g) << ",";
if (!compressed) ss << " ";
ss << static_cast<unsigned long>(b) << ",";
if (!compressed) ss << " ";
ss << a << ')';
}
append_token(ss.str(), c);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix possible bug with handling empty reference combinators
Fixes #2665'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Statement_Ptr Expand::operator()(Debug_Ptr d)
{
// eval handles this too, because warnings may occur in functions
d->perform(&eval);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault on empty custom properties
Originally reported in sass/sassc#225
Fixes sass/sassc#225
Spec sass/sass-spec#1249'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Statement_Ptr Expand::operator()(Definition_Ptr d)
{
Env* env = environment();
Definition_Obj dd = SASS_MEMORY_COPY(d);
env->local_frame()[d->name() +
(d->type() == Definition::MIXIN ? "[m]" : "[f]")] = dd;
if (d->type() == Definition::FUNCTION && (
Prelexer::calc_fn_call(d->name().c_str()) ||
d->name() == "element" ||
d->name() == "expression" ||
d->name() == "url"
)) {
deprecated(
"Naming a function \"" + d->name() + "\" is disallowed and will be an error in future versions of Sass.",
"This name conflicts with an existing CSS function with special parse rules.",
false, d->pstate()
);
}
// set the static link so we can have lexical scoping
dd->environment(env);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault on empty custom properties
Originally reported in sass/sassc#225
Fixes sass/sassc#225
Spec sass/sass-spec#1249'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: read_non_rle_pixel(tga_source_ptr sinfo)
/* Read one Targa pixel from the input file; no RLE expansion */
{
register FILE *infile = sinfo->pub.input_file;
register int i;
for (i = 0; i < sinfo->pixel_size; i++) {
sinfo->tga_pixel[i] = (U_CHAR)getc(infile);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-834'], 'message': 'Fix CVE-2018-11813
Refer to change log for details.
Fixes #242'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _rsvg_io_get_file_path (const gchar * filename,
const gchar * base_uri)
{
gchar *absolute_filename;
if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {
absolute_filename = g_strdup (filename);
} else {
gchar *tmpcdir;
gchar *base_filename;
if (base_uri) {
base_filename = g_filename_from_uri (base_uri, NULL, NULL);
if (base_filename != NULL) {
tmpcdir = g_path_get_dirname (base_filename);
g_free (base_filename);
} else
return NULL;
} else
tmpcdir = g_get_current_dir ();
absolute_filename = g_build_filename (tmpcdir, filename, NULL);
g_free (tmpcdir);
}
return absolute_filename;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-522'], 'message': 'Fixed possible credentials leaking reported by Alex Birsan.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: parseChars(FileInfo *nested, CharsString *result, CharsString *token) {
int in = 0;
int out = 0;
int lastOutSize = 0;
int lastIn;
unsigned int ch = 0;
int numBytes = 0;
unsigned int utf32 = 0;
int k;
while (in < token->length) {
ch = token->chars[in++] & 0xff;
if (ch < 128) {
if (ch == '\\') { /* escape sequence */
switch (ch = token->chars[in]) {
case '\\':
break;
case 'e':
ch = 0x1b;
break;
case 'f':
ch = 12;
break;
case 'n':
ch = 10;
break;
case 'r':
ch = 13;
break;
case 's':
ch = ' ';
break;
case 't':
ch = 9;
break;
case 'v':
ch = 11;
break;
case 'w':
ch = ENDSEGMENT;
break;
case 34:
ch = QUOTESUB;
break;
case 'X':
case 'x':
if (token->length - in > 4) {
ch = hexValue(nested, &token->chars[in + 1], 4);
in += 4;
}
break;
case 'y':
case 'Y':
if (CHARSIZE == 2) {
not32:
compileError(nested,
"liblouis has not been compiled for 32-bit Unicode");
break;
}
if (token->length - in > 5) {
ch = hexValue(nested, &token->chars[in + 1], 5);
in += 5;
}
break;
case 'z':
case 'Z':
if (CHARSIZE == 2) goto not32;
if (token->length - in > 8) {
ch = hexValue(nested, &token->chars[in + 1], 8);
in += 8;
}
break;
default:
compileError(nested, "invalid escape sequence '\\%c'", ch);
break;
}
in++;
}
result->chars[out++] = (widechar)ch;
if (out >= MAXSTRING) {
result->length = out;
return 1;
}
continue;
}
lastOutSize = out;
lastIn = in;
for (numBytes = MAXBYTES - 1; numBytes > 0; numBytes--)
if (ch >= first0Bit[numBytes]) break;
utf32 = ch & (0XFF - first0Bit[numBytes]);
for (k = 0; k < numBytes; k++) {
if (in >= MAXSTRING) break;
if (out >= MAXSTRING) {
result->length = lastOutSize;
return 1;
}
if (token->chars[in] < 128 || (token->chars[in] & 0x0040)) {
compileWarning(nested, "invalid UTF-8. Assuming Latin-1.");
result->chars[out++] = token->chars[lastIn];
in = lastIn + 1;
continue;
}
utf32 = (utf32 << 6) + (token->chars[in++] & 0x3f);
}
if (out >= MAXSTRING) {
result->length = lastOutSize;
return 1;
}
if (CHARSIZE == 2 && utf32 > 0xffff) utf32 = 0xffff;
result->chars[out++] = (widechar)utf32;
}
result->length = out;
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Check index before writing to result->chars
Fixes #595'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.