text
stringlengths 486
228k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: glue(cirrus_bitblt_rop_fwd_, ROP_NAME)(CirrusVGAState *s,
uint8_t *dst,const uint8_t *src,
int dstpitch,int srcpitch,
int bltwidth,int bltheight)
{
int x,y;
dstpitch -= bltwidth;
srcpitch -= bltwidth;
for (y = 0; y < bltheight; y++) {
for (x = 0; x < bltwidth; x++) {
ROP_OP(*dst, *src);
dst++;
src++;
}
dst += dstpitch;
src += srcpitch;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow
I have just noticed that patch for CVE-2007-1320 has never been applied
to the QEMU CVS. Please find it below.
| Multiple heap-based buffer overflows in the cirrus_invalidate_region
| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and
| possibly other products, might allow local users to execute arbitrary
| code via unspecified vectors related to "attempting to mark
| non-existent regions as dirty," aka the "bitblt" heap overflow.
git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s> |
<s>[INST] Given the following code containing errors, provide 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 pwc_video_close(struct inode *inode, struct file *file)
{
struct video_device *vdev = file->private_data;
struct pwc_device *pdev;
int i;
PWC_DEBUG_OPEN(">> video_close called(vdev = 0x%p).\n", vdev);
pdev = (struct pwc_device *)vdev->priv;
if (pdev->vopen == 0)
PWC_DEBUG_MODULE("video_close() called on closed device?\n");
/* Dump statistics, but only if a reasonable amount of frames were
processed (to prevent endless log-entries in case of snap-shot
programs)
*/
if (pdev->vframe_count > 20)
PWC_DEBUG_MODULE("Closing video device: %d frames received, dumped %d frames, %d frames with errors.\n", pdev->vframe_count, pdev->vframes_dumped, pdev->vframes_error);
if (DEVICE_USE_CODEC1(pdev->type))
pwc_dec1_exit();
else
pwc_dec23_exit();
pwc_isoc_cleanup(pdev);
pwc_free_buffers(pdev);
/* Turn off LEDS and power down camera, but only when not unplugged */
if (pdev->error_status != EPIPE) {
/* Turn LEDs off */
if (pwc_set_leds(pdev, 0, 0) < 0)
PWC_DEBUG_MODULE("Failed to set LED on/off time.\n");
if (power_save) {
i = pwc_camera_power(pdev, 0);
if (i < 0)
PWC_ERROR("Failed to power down camera (%d)\n", i);
}
}
pdev->vopen--;
PWC_DEBUG_OPEN("<< video_close() vopen=%d\n", pdev->vopen);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver
the pwc driver has a disconnect method that waits for user space to
close the device. This opens up an opportunity for a DoS attack,
blocking the USB subsystem and making khubd's task busy wait in
kernel space. This patch shifts freeing resources to close if an opened
device is disconnected.
Signed-off-by: Oliver Neukum <oneukum@suse.de>
CC: stable <stable@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: isdn_net_setcfg(isdn_net_ioctl_cfg * cfg)
{
isdn_net_dev *p = isdn_net_findif(cfg->name);
ulong features;
int i;
int drvidx;
int chidx;
char drvid[25];
if (p) {
isdn_net_local *lp = p->local;
/* See if any registered driver supports the features we want */
features = ((1 << cfg->l2_proto) << ISDN_FEATURE_L2_SHIFT) |
((1 << cfg->l3_proto) << ISDN_FEATURE_L3_SHIFT);
for (i = 0; i < ISDN_MAX_DRIVERS; i++)
if (dev->drv[i])
if ((dev->drv[i]->interface->features & features) == features)
break;
if (i == ISDN_MAX_DRIVERS) {
printk(KERN_WARNING "isdn_net: No driver with selected features\n");
return -ENODEV;
}
if (lp->p_encap != cfg->p_encap){
#ifdef CONFIG_ISDN_X25
struct concap_proto * cprot = p -> cprot;
#endif
if (isdn_net_device_started(p)) {
printk(KERN_WARNING "%s: cannot change encap when if is up\n",
p->dev->name);
return -EBUSY;
}
#ifdef CONFIG_ISDN_X25
if( cprot && cprot -> pops )
cprot -> pops -> proto_del ( cprot );
p -> cprot = NULL;
lp -> dops = NULL;
/* ... , prepare for configuration of new one ... */
switch ( cfg -> p_encap ){
case ISDN_NET_ENCAP_X25IFACE:
lp -> dops = &isdn_concap_reliable_dl_dops;
}
/* ... and allocate new one ... */
p -> cprot = isdn_concap_new( cfg -> p_encap );
/* p -> cprot == NULL now if p_encap is not supported
by means of the concap_proto mechanism */
/* the protocol is not configured yet; this will
happen later when isdn_net_reset() is called */
#endif
}
switch ( cfg->p_encap ) {
case ISDN_NET_ENCAP_SYNCPPP:
#ifndef CONFIG_ISDN_PPP
printk(KERN_WARNING "%s: SyncPPP support not configured\n",
p->dev->name);
return -EINVAL;
#else
p->dev->type = ARPHRD_PPP; /* change ARP type */
p->dev->addr_len = 0;
p->dev->do_ioctl = isdn_ppp_dev_ioctl;
#endif
break;
case ISDN_NET_ENCAP_X25IFACE:
#ifndef CONFIG_ISDN_X25
printk(KERN_WARNING "%s: isdn-x25 support not configured\n",
p->dev->name);
return -EINVAL;
#else
p->dev->type = ARPHRD_X25; /* change ARP type */
p->dev->addr_len = 0;
#endif
break;
case ISDN_NET_ENCAP_CISCOHDLCK:
p->dev->do_ioctl = isdn_ciscohdlck_dev_ioctl;
break;
default:
if( cfg->p_encap >= 0 &&
cfg->p_encap <= ISDN_NET_ENCAP_MAX_ENCAP )
break;
printk(KERN_WARNING
"%s: encapsulation protocol %d not supported\n",
p->dev->name, cfg->p_encap);
return -EINVAL;
}
if (strlen(cfg->drvid)) {
/* A bind has been requested ... */
char *c,
*e;
drvidx = -1;
chidx = -1;
strcpy(drvid, cfg->drvid);
if ((c = strchr(drvid, ','))) {
/* The channel-number is appended to the driver-Id with a comma */
chidx = (int) simple_strtoul(c + 1, &e, 10);
if (e == c)
chidx = -1;
*c = '\0';
}
for (i = 0; i < ISDN_MAX_DRIVERS; i++)
/* Lookup driver-Id in array */
if (!(strcmp(dev->drvid[i], drvid))) {
drvidx = i;
break;
}
if ((drvidx == -1) || (chidx == -1))
/* Either driver-Id or channel-number invalid */
return -ENODEV;
} else {
/* Parameters are valid, so get them */
drvidx = lp->pre_device;
chidx = lp->pre_channel;
}
if (cfg->exclusive > 0) {
unsigned long flags;
/* If binding is exclusive, try to grab the channel */
spin_lock_irqsave(&dev->lock, flags);
if ((i = isdn_get_free_channel(ISDN_USAGE_NET,
lp->l2_proto, lp->l3_proto, drvidx,
chidx, lp->msn)) < 0) {
/* Grab failed, because desired channel is in use */
lp->exclusive = -1;
spin_unlock_irqrestore(&dev->lock, flags);
return -EBUSY;
}
/* All went ok, so update isdninfo */
dev->usage[i] = ISDN_USAGE_EXCLUSIVE;
isdn_info_update();
spin_unlock_irqrestore(&dev->lock, flags);
lp->exclusive = i;
} else {
/* Non-exclusive binding or unbind. */
lp->exclusive = -1;
if ((lp->pre_device != -1) && (cfg->exclusive == -1)) {
isdn_unexclusive_channel(lp->pre_device, lp->pre_channel);
isdn_free_channel(lp->pre_device, lp->pre_channel, ISDN_USAGE_NET);
drvidx = -1;
chidx = -1;
}
}
strcpy(lp->msn, cfg->eaz);
lp->pre_device = drvidx;
lp->pre_channel = chidx;
lp->onhtime = cfg->onhtime;
lp->charge = cfg->charge;
lp->l2_proto = cfg->l2_proto;
lp->l3_proto = cfg->l3_proto;
lp->cbdelay = cfg->cbdelay;
lp->dialmax = cfg->dialmax;
lp->triggercps = cfg->triggercps;
lp->slavedelay = cfg->slavedelay * HZ;
lp->pppbind = cfg->pppbind;
lp->dialtimeout = cfg->dialtimeout >= 0 ? cfg->dialtimeout * HZ : -1;
lp->dialwait = cfg->dialwait * HZ;
if (cfg->secure)
lp->flags |= ISDN_NET_SECURE;
else
lp->flags &= ~ISDN_NET_SECURE;
if (cfg->cbhup)
lp->flags |= ISDN_NET_CBHUP;
else
lp->flags &= ~ISDN_NET_CBHUP;
switch (cfg->callback) {
case 0:
lp->flags &= ~(ISDN_NET_CALLBACK | ISDN_NET_CBOUT);
break;
case 1:
lp->flags |= ISDN_NET_CALLBACK;
lp->flags &= ~ISDN_NET_CBOUT;
break;
case 2:
lp->flags |= ISDN_NET_CBOUT;
lp->flags &= ~ISDN_NET_CALLBACK;
break;
}
lp->flags &= ~ISDN_NET_DIALMODE_MASK; /* first all bits off */
if (cfg->dialmode && !(cfg->dialmode & ISDN_NET_DIALMODE_MASK)) {
/* old isdnctrl version, where only 0 or 1 is given */
printk(KERN_WARNING
"Old isdnctrl version detected! Please update.\n");
lp->flags |= ISDN_NET_DM_OFF; /* turn on `off' bit */
}
else {
lp->flags |= cfg->dialmode; /* turn on selected bits */
}
if (cfg->chargehup)
lp->hupflags |= ISDN_CHARGEHUP;
else
lp->hupflags &= ~ISDN_CHARGEHUP;
if (cfg->ihup)
lp->hupflags |= ISDN_INHUP;
else
lp->hupflags &= ~ISDN_INHUP;
if (cfg->chargeint > 10) {
lp->hupflags |= ISDN_CHARGEHUP | ISDN_HAVECHARGE | ISDN_MANCHARGE;
lp->chargeint = cfg->chargeint * HZ;
}
if (cfg->p_encap != lp->p_encap) {
if (cfg->p_encap == ISDN_NET_ENCAP_RAWIP) {
p->dev->header_ops = NULL;
p->dev->flags = IFF_NOARP|IFF_POINTOPOINT;
} else {
p->dev->header_ops = &isdn_header_ops;
if (cfg->p_encap == ISDN_NET_ENCAP_ETHER)
p->dev->flags = IFF_BROADCAST | IFF_MULTICAST;
else
p->dev->flags = IFF_NOARP|IFF_POINTOPOINT;
}
}
lp->p_encap = cfg->p_encap;
return 0;
}
return -ENODEV;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings
Addresses http://bugzilla.kernel.org/show_bug.cgi?id=9416
Signed-off-by: Karsten Keil <kkeil@suse.de>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ProcPanoramiXShmCreatePixmap(
register ClientPtr client)
{
ScreenPtr pScreen = NULL;
PixmapPtr pMap = NULL;
DrawablePtr pDraw;
DepthPtr pDepth;
int i, j, result, rc;
ShmDescPtr shmdesc;
REQUEST(xShmCreatePixmapReq);
unsigned int width, height, depth;
unsigned long size;
PanoramiXRes *newPix;
REQUEST_SIZE_MATCH(xShmCreatePixmapReq);
client->errorValue = stuff->pid;
if (!sharedPixmaps)
return BadImplementation;
LEGAL_NEW_RESOURCE(stuff->pid, client);
rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY,
DixUnknownAccess);
if (rc != Success)
return rc;
VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);
width = stuff->width;
height = stuff->height;
depth = stuff->depth;
if (!width || !height || !depth)
{
client->errorValue = 0;
return BadValue;
}
if (width > 32767 || height > 32767)
return BadAlloc;
if (stuff->depth != 1)
{
pDepth = pDraw->pScreen->allowedDepths;
for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++)
if (pDepth->depth == stuff->depth)
goto CreatePmap;
client->errorValue = stuff->depth;
return BadValue;
}
CreatePmap:
size = PixmapBytePad(width, depth) * height;
if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) {
if (size < width * height)
return BadAlloc;
/* thankfully, offset is unsigned */
if (stuff->offset + size < size)
return BadAlloc;
}
VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client);
if(!(newPix = (PanoramiXRes *) xalloc(sizeof(PanoramiXRes))))
return BadAlloc;
newPix->type = XRT_PIXMAP;
newPix->u.pix.shared = TRUE;
newPix->info[0].id = stuff->pid;
for(j = 1; j < PanoramiXNumScreens; j++)
newPix->info[j].id = FakeClientID(client->index);
result = (client->noClientException);
FOR_NSCREENS(j) {
pScreen = screenInfo.screens[j];
pMap = (*shmFuncs[j]->CreatePixmap)(pScreen,
stuff->width, stuff->height, stuff->depth,
shmdesc->addr + stuff->offset);
if (pMap) {
dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc);
shmdesc->refcnt++;
pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER;
pMap->drawable.id = newPix->info[j].id;
if (!AddResource(newPix->info[j].id, RT_PIXMAP, (pointer)pMap)) {
(*pScreen->DestroyPixmap)(pMap);
result = BadAlloc;
break;
}
} else {
result = BadAlloc;
break;
}
}
if(result == BadAlloc) {
while(j--) {
(*pScreen->DestroyPixmap)(pMap);
FreeResource(newPix->info[j].id, RT_NONE);
}
xfree(newPix);
} else
AddResource(stuff->pid, XRT_PIXMAP, newPix);
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static unsigned long __peek_user(struct task_struct *child, addr_t addr)
{
struct user *dummy = NULL;
addr_t offset, tmp;
if (addr < (addr_t) &dummy->regs.acrs) {
/*
* psw and gprs are stored on the stack
*/
tmp = *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr);
if (addr == (addr_t) &dummy->regs.psw.mask)
/* Remove per bit from user psw. */
tmp &= ~PSW_MASK_PER;
} else if (addr < (addr_t) &dummy->regs.orig_gpr2) {
/*
* access registers are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.acrs;
#ifdef CONFIG_64BIT
/*
* Very special case: old & broken 64 bit gdb reading
* from acrs[15]. Result is a 64 bit value. Read the
* 32 bit acrs[15] value and shift it by 32. Sick...
*/
if (addr == (addr_t) &dummy->regs.acrs[15])
tmp = ((unsigned long) child->thread.acrs[15]) << 32;
else
#endif
tmp = *(addr_t *)((addr_t) &child->thread.acrs + offset);
} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {
/*
* orig_gpr2 is stored on the kernel stack
*/
tmp = (addr_t) task_pt_regs(child)->orig_gpr2;
} else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) {
/*
* floating point regs. are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.fp_regs;
tmp = *(addr_t *)((addr_t) &child->thread.fp_regs + offset);
if (addr == (addr_t) &dummy->regs.fp_regs.fpc)
tmp &= (unsigned long) FPC_VALID_MASK
<< (BITS_PER_LONG - 32);
} else if (addr < (addr_t) (&dummy->regs.per_info + 1)) {
/*
* per_info is found in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.per_info;
tmp = *(addr_t *)((addr_t) &child->thread.per_info + offset);
} else
tmp = 0;
return tmp;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': '[S390] CVE-2008-1514: prevent ptrace padding area read/write in 31-bit mode
When running a 31-bit ptrace, on either an s390 or s390x kernel,
reads and writes into a padding area in struct user_regs_struct32
will result in a kernel panic.
This is also known as CVE-2008-1514.
Test case available here:
http://sources.redhat.com/cgi-bin/cvsweb.cgi/~checkout~/tests/ptrace-tests/tests/user-area-padding.c?cvsroot=systemtap
Steps to reproduce:
1) wget the above
2) gcc -o user-area-padding-31bit user-area-padding.c -Wall -ggdb2 -D_GNU_SOURCE -m31
3) ./user-area-padding-31bit
<panic>
Test status
-----------
Without patch, both s390 and s390x kernels panic. With patch, the test case,
as well as the gdb testsuite, pass without incident, padding area reads
returning zero, writes ignored.
Nb: original version returned -EINVAL on write attempts, which broke the
gdb test and made the test case slightly unhappy, Jan Kratochvil suggested
the change to return 0 on write attempts.
Signed-off-by: Jarod Wilson <jarod@redhat.com>
Tested-by: Jan Kratochvil <jan.kratochvil@redhat.com>
Signed-off-by: Martin Schwidefsky <schwidefsky@de.ibm.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _gnutls_recv_handshake_header (gnutls_session_t session,
gnutls_handshake_description_t type,
gnutls_handshake_description_t * recv_type)
{
int ret;
uint32_t length32 = 0;
uint8_t *dataptr = NULL; /* for realloc */
size_t handshake_header_size = HANDSHAKE_HEADER_SIZE;
/* if we have data into the buffer then return them, do not read the next packet.
* In order to return we need a full TLS handshake header, or in case of a version 2
* packet, then we return the first byte.
*/
if (session->internals.handshake_header_buffer.header_size ==
handshake_header_size || (session->internals.v2_hello != 0
&& type == GNUTLS_HANDSHAKE_CLIENT_HELLO
&& session->internals.
handshake_header_buffer.packet_length > 0))
{
*recv_type = session->internals.handshake_header_buffer.recv_type;
return session->internals.handshake_header_buffer.packet_length;
}
/* Note: SSL2_HEADERS == 1 */
dataptr = session->internals.handshake_header_buffer.header;
/* If we haven't already read the handshake headers.
*/
if (session->internals.handshake_header_buffer.header_size < SSL2_HEADERS)
{
ret =
_gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE,
type, dataptr, SSL2_HEADERS);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
/* The case ret==0 is caught here.
*/
if (ret != SSL2_HEADERS)
{
gnutls_assert ();
return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
}
session->internals.handshake_header_buffer.header_size = SSL2_HEADERS;
}
if (session->internals.v2_hello == 0
|| type != GNUTLS_HANDSHAKE_CLIENT_HELLO)
{
ret =
_gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE,
type,
&dataptr[session->
internals.
handshake_header_buffer.
header_size],
HANDSHAKE_HEADER_SIZE -
session->internals.
handshake_header_buffer.header_size);
if (ret <= 0)
{
gnutls_assert ();
return (ret < 0) ? ret : GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
}
if ((size_t) ret !=
HANDSHAKE_HEADER_SIZE -
session->internals.handshake_header_buffer.header_size)
{
gnutls_assert ();
return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
}
*recv_type = dataptr[0];
/* we do not use DECR_LEN because we know
* that the packet has enough data.
*/
length32 = _gnutls_read_uint24 (&dataptr[1]);
handshake_header_size = HANDSHAKE_HEADER_SIZE;
_gnutls_handshake_log ("HSK[%x]: %s was received [%ld bytes]\n",
session, _gnutls_handshake2str (dataptr[0]),
length32 + HANDSHAKE_HEADER_SIZE);
}
else
{ /* v2 hello */
length32 = session->internals.v2_hello - SSL2_HEADERS; /* we've read the first byte */
handshake_header_size = SSL2_HEADERS; /* we've already read one byte */
*recv_type = dataptr[0];
_gnutls_handshake_log ("HSK[%x]: %s(v2) was received [%ld bytes]\n",
session, _gnutls_handshake2str (*recv_type),
length32 + handshake_header_size);
if (*recv_type != GNUTLS_HANDSHAKE_CLIENT_HELLO)
{ /* it should be one or nothing */
gnutls_assert ();
return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
}
}
/* put the packet into the buffer */
session->internals.handshake_header_buffer.header_size =
handshake_header_size;
session->internals.handshake_header_buffer.packet_length = length32;
session->internals.handshake_header_buffer.recv_type = *recv_type;
if (*recv_type != type)
{
gnutls_assert ();
return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
}
return length32;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'Fix GNUTLS-SA-2008-1 security vulnerabilities.
See http://www.gnu.org/software/gnutls/security.html for updates.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: snd_seq_oss_synth_make_info(struct seq_oss_devinfo *dp, int dev, struct synth_info *inf)
{
struct seq_oss_synth *rec;
if (dp->synths[dev].is_midi) {
struct midi_info minf;
snd_seq_oss_midi_make_info(dp, dp->synths[dev].midi_mapped, &minf);
inf->synth_type = SYNTH_TYPE_MIDI;
inf->synth_subtype = 0;
inf->nr_voices = 16;
inf->device = dev;
strlcpy(inf->name, minf.name, sizeof(inf->name));
} else {
if ((rec = get_synthdev(dp, dev)) == NULL)
return -ENXIO;
inf->synth_type = rec->synth_type;
inf->synth_subtype = rec->synth_subtype;
inf->nr_voices = rec->nr_voices;
inf->device = dev;
strlcpy(inf->name, rec->name, sizeof(inf->name));
snd_use_lock_free(&rec->use_lock);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'sound: ensure device number is valid in snd_seq_oss_synth_make_info
snd_seq_oss_synth_make_info() incorrectly reports information
to userspace without first checking for the validity of the
device number, leading to possible information leak (CVE-2008-3272).
Reported-By: Tobias Klein <tk@trapkit.de>
Acked-and-tested-by: Takashi Iwai <tiwai@suse.de>
Cc: stable@kernel.org
Signed-off-by: Willy Tarreau <w@1wt.eu>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd )
{
struct net_local *nl = (struct net_local *) dev->priv;
struct sbni_flags flags;
int error = 0;
#ifdef CONFIG_SBNI_MULTILINE
struct net_device *slave_dev;
char slave_name[ 8 ];
#endif
switch( cmd ) {
case SIOCDEVGETINSTATS :
if (copy_to_user( ifr->ifr_data, &nl->in_stats,
sizeof(struct sbni_in_stats) ))
error = -EFAULT;
break;
case SIOCDEVRESINSTATS :
if( current->euid != 0 ) /* root only */
return -EPERM;
memset( &nl->in_stats, 0, sizeof(struct sbni_in_stats) );
break;
case SIOCDEVGHWSTATE :
flags.mac_addr = *(u32 *)(dev->dev_addr + 3);
flags.rate = nl->csr1.rate;
flags.slow_mode = (nl->state & FL_SLOW_MODE) != 0;
flags.rxl = nl->cur_rxl_index;
flags.fixed_rxl = nl->delta_rxl == 0;
if (copy_to_user( ifr->ifr_data, &flags, sizeof flags ))
error = -EFAULT;
break;
case SIOCDEVSHWSTATE :
if( current->euid != 0 ) /* root only */
return -EPERM;
spin_lock( &nl->lock );
flags = *(struct sbni_flags*) &ifr->ifr_ifru;
if( flags.fixed_rxl )
nl->delta_rxl = 0,
nl->cur_rxl_index = flags.rxl;
else
nl->delta_rxl = DEF_RXL_DELTA,
nl->cur_rxl_index = DEF_RXL;
nl->csr1.rxl = rxl_tab[ nl->cur_rxl_index ];
nl->csr1.rate = flags.rate;
outb( *(u8 *)&nl->csr1 | PR_RES, dev->base_addr + CSR1 );
spin_unlock( &nl->lock );
break;
#ifdef CONFIG_SBNI_MULTILINE
case SIOCDEVENSLAVE :
if( current->euid != 0 ) /* root only */
return -EPERM;
if (copy_from_user( slave_name, ifr->ifr_data, sizeof slave_name ))
return -EFAULT;
slave_dev = dev_get_by_name(&init_net, slave_name );
if( !slave_dev || !(slave_dev->flags & IFF_UP) ) {
printk( KERN_ERR "%s: trying to enslave non-active "
"device %s\n", dev->name, slave_name );
return -EPERM;
}
return enslave( dev, slave_dev );
case SIOCDEVEMANSIPATE :
if( current->euid != 0 ) /* root only */
return -EPERM;
return emancipate( dev );
#endif /* CONFIG_SBNI_MULTILINE */
default :
return -EOPNOTSUPP;
}
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'wan: Missing capability checks in sbni_ioctl()
There are missing capability checks in the following code:
1300 static int
1301 sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd)
1302 {
[...]
1319 case SIOCDEVRESINSTATS :
1320 if( current->euid != 0 ) /* root only */
1321 return -EPERM;
[...]
1336 case SIOCDEVSHWSTATE :
1337 if( current->euid != 0 ) /* root only */
1338 return -EPERM;
[...]
1357 case SIOCDEVENSLAVE :
1358 if( current->euid != 0 ) /* root only */
1359 return -EPERM;
[...]
1372 case SIOCDEVEMANSIPATE :
1373 if( current->euid != 0 ) /* root only */
1374 return -EPERM;
Here's my proposed fix:
Missing capability checks.
Signed-off-by: Eugene Teo <eugeneteo@kernel.sg>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 bmp_info_t *bmp_getinfo(jas_stream_t *in)
{
bmp_info_t *info;
int i;
bmp_palent_t *palent;
if (!(info = bmp_info_create())) {
return 0;
}
if (bmp_getint32(in, &info->len) || info->len != 40 ||
bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) ||
bmp_getint16(in, &info->numplanes) ||
bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) ||
bmp_getint32(in, &info->siz) ||
bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) ||
bmp_getint32(in, &info->numcolors) ||
bmp_getint32(in, &info->mincolors)) {
bmp_info_destroy(info);
return 0;
}
if (info->height < 0) {
info->topdown = 1;
info->height = -info->height;
} else {
info->topdown = 0;
}
if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 ||
info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) {
bmp_info_destroy(info);
return 0;
}
if (info->enctype != BMP_ENC_RGB) {
jas_eprintf("unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
if (info->numcolors > 0) {
if (!(info->palents = jas_malloc(info->numcolors *
sizeof(bmp_palent_t)))) {
bmp_info_destroy(info);
return 0;
}
} else {
info->palents = 0;
}
for (i = 0; i < info->numcolors; ++i) {
palent = &info->palents[i];
if ((palent->blu = jas_stream_getc(in)) == EOF ||
(palent->grn = jas_stream_getc(in)) == EOF ||
(palent->red = jas_stream_getc(in)) == EOF ||
(palent->res = jas_stream_getc(in)) == EOF) {
bmp_info_destroy(info);
return 0;
}
}
return info;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being
invoked with the size argument being computed in a manner that would not
allow integer overflow to be detected. Now, these places in the code
have been modified to use special-purpose memory allocation functions
(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.
This should fix many security problems.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos)
{
uint_fast16_t rlvlno;
uint_fast32_t tlprctlx;
uint_fast32_t tlprctly;
uint_fast32_t brprcbrx;
uint_fast32_t brprcbry;
uint_fast16_t bandno;
jpc_enc_band_t *band;
/* Deduce the resolution level. */
rlvlno = rlvl - tcmpt->rlvls;
/* Initialize members required for error recovery. */
rlvl->bands = 0;
rlvl->tcmpt = tcmpt;
/* Compute the coordinates of the top-left and bottom-right
corners of the tile-component at this resolution. */
rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls -
1 - rlvlno);
rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls -
1 - rlvlno);
rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls -
1 - rlvlno);
rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls -
1 - rlvlno);
if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) {
rlvl->numhprcs = 0;
rlvl->numvprcs = 0;
rlvl->numprcs = 0;
return rlvl;
}
rlvl->numbands = (!rlvlno) ? 1 : 3;
rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno];
rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno];
if (!rlvlno) {
rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
rlvl->cbgheightexpn = rlvl->prcheightexpn;
} else {
rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
}
rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn);
rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn);
/* Compute the number of precincts. */
tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn);
brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn);
rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn);
rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn);
rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_enc_band_t)))) {
goto error;
}
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
band->prcs = 0;
band->data = 0;
band->rlvl = rlvl;
}
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (!band_create(band, cp, rlvl, bandinfos)) {
goto error;
}
}
return rlvl;
error:
rlvl_destroy(rlvl);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being
invoked with the size argument being computed in a manner that would not
allow integer overflow to be detected. Now, these places in the code
have been modified to use special-purpose memory allocation functions
(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.
This should fix many security problems.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0,
int r1, int c1)
{
int i;
if (mat0->data_) {
if (!(mat0->flags_ & JAS_MATRIX_REF)) {
jas_free(mat0->data_);
}
mat0->data_ = 0;
mat0->datasize_ = 0;
}
if (mat0->rows_) {
jas_free(mat0->rows_);
mat0->rows_ = 0;
}
mat0->flags_ |= JAS_MATRIX_REF;
mat0->numrows_ = r1 - r0 + 1;
mat0->numcols_ = c1 - c0 + 1;
mat0->maxrows_ = mat0->numrows_;
mat0->rows_ = jas_malloc(mat0->maxrows_ * sizeof(jas_seqent_t *));
for (i = 0; i < mat0->numrows_; ++i) {
mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
}
mat0->xstart_ = mat1->xstart_ + c0;
mat0->ystart_ = mat1->ystart_ + r0;
mat0->xend_ = mat0->xstart_ + mat0->numcols_;
mat0->yend_ = mat0->ystart_ + mat0->numrows_;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being
invoked with the size argument being computed in a manner that would not
allow integer overflow to be detected. Now, these places in the code
have been modified to use special-purpose memory allocation functions
(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.
This should fix many security problems.'</s> |
<s>[INST] Given the following code containing errors, provide 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_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_crg_t *crg = &ms->parms.crg;
jpc_crgcomp_t *comp;
uint_fast16_t compno;
crg->numcomps = cstate->numcomps;
if (!(crg->comps = jas_malloc(cstate->numcomps * sizeof(uint_fast16_t)))) {
return -1;
}
for (compno = 0, comp = crg->comps; compno < cstate->numcomps;
++compno, ++comp) {
if (jpc_getuint16(in, &comp->hoff) ||
jpc_getuint16(in, &comp->voff)) {
jpc_crg_destroyparms(ms);
return -1;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being
invoked with the size argument being computed in a manner that would not
allow integer overflow to be detected. Now, these places in the code
have been modified to use special-purpose memory allocation functions
(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.
This should fix many security problems.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image)
{
jpc_enc_cp_t *cp;
jas_tvparser_t *tvp;
int ret;
int numilyrrates;
double *ilyrrates;
int i;
int tagid;
jpc_enc_tcp_t *tcp;
jpc_enc_tccp_t *tccp;
jpc_enc_ccp_t *ccp;
int cmptno;
uint_fast16_t rlvlno;
uint_fast16_t prcwidthexpn;
uint_fast16_t prcheightexpn;
bool enablemct;
uint_fast32_t jp2overhead;
uint_fast16_t lyrno;
uint_fast32_t hsteplcm;
uint_fast32_t vsteplcm;
bool mctvalid;
tvp = 0;
cp = 0;
ilyrrates = 0;
numilyrrates = 0;
if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {
goto error;
}
prcwidthexpn = 15;
prcheightexpn = 15;
enablemct = true;
jp2overhead = 0;
cp->ccps = 0;
cp->debug = 0;
cp->imgareatlx = UINT_FAST32_MAX;
cp->imgareatly = UINT_FAST32_MAX;
cp->refgrdwidth = 0;
cp->refgrdheight = 0;
cp->tilegrdoffx = UINT_FAST32_MAX;
cp->tilegrdoffy = UINT_FAST32_MAX;
cp->tilewidth = 0;
cp->tileheight = 0;
cp->numcmpts = jas_image_numcmpts(image);
hsteplcm = 1;
vsteplcm = 1;
for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=
jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +
jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {
jas_eprintf("unsupported image type\n");
goto error;
}
/* Note: We ought to be calculating the LCMs here. Fix some day. */
hsteplcm *= jas_image_cmpthstep(image, cmptno);
vsteplcm *= jas_image_cmptvstep(image, cmptno);
}
if (!(cp->ccps = jas_malloc(cp->numcmpts * sizeof(jpc_enc_ccp_t)))) {
goto error;
}
for (cmptno = 0, ccp = cp->ccps; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno,
++ccp) {
ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);
ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);
/* XXX - this isn't quite correct for more general image */
ccp->sampgrdsubstepx = 0;
ccp->sampgrdsubstepx = 0;
ccp->prec = jas_image_cmptprec(image, cmptno);
ccp->sgnd = jas_image_cmptsgnd(image, cmptno);
ccp->numstepsizes = 0;
memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));
}
cp->rawsize = jas_image_rawsize(image);
cp->totalsize = UINT_FAST32_MAX;
tcp = &cp->tcp;
tcp->csty = 0;
tcp->intmode = true;
tcp->prg = JPC_COD_LRCPPRG;
tcp->numlyrs = 1;
tcp->ilyrrates = 0;
tccp = &cp->tccp;
tccp->csty = 0;
tccp->maxrlvls = 6;
tccp->cblkwidthexpn = 6;
tccp->cblkheightexpn = 6;
tccp->cblksty = 0;
tccp->numgbits = 2;
if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
goto error;
}
while (!(ret = jas_tvparser_next(tvp))) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,
jas_tvparser_gettag(tvp)))->id) {
case OPT_DEBUG:
cp->debug = atoi(jas_tvparser_getval(tvp));
break;
case OPT_IMGAREAOFFX:
cp->imgareatlx = atoi(jas_tvparser_getval(tvp));
break;
case OPT_IMGAREAOFFY:
cp->imgareatly = atoi(jas_tvparser_getval(tvp));
break;
case OPT_TILEGRDOFFX:
cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));
break;
case OPT_TILEGRDOFFY:
cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));
break;
case OPT_TILEWIDTH:
cp->tilewidth = atoi(jas_tvparser_getval(tvp));
break;
case OPT_TILEHEIGHT:
cp->tileheight = atoi(jas_tvparser_getval(tvp));
break;
case OPT_PRCWIDTH:
prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
break;
case OPT_PRCHEIGHT:
prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
break;
case OPT_CBLKWIDTH:
tccp->cblkwidthexpn =
jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
break;
case OPT_CBLKHEIGHT:
tccp->cblkheightexpn =
jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
break;
case OPT_MODE:
if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,
jas_tvparser_getval(tvp)))->id) < 0) {
jas_eprintf("ignoring invalid mode %s\n",
jas_tvparser_getval(tvp));
} else {
tcp->intmode = (tagid == MODE_INT);
}
break;
case OPT_PRG:
if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,
jas_tvparser_getval(tvp)))->id) < 0) {
jas_eprintf("ignoring invalid progression order %s\n",
jas_tvparser_getval(tvp));
} else {
tcp->prg = tagid;
}
break;
case OPT_NOMCT:
enablemct = false;
break;
case OPT_MAXRLVLS:
tccp->maxrlvls = atoi(jas_tvparser_getval(tvp));
break;
case OPT_SOP:
cp->tcp.csty |= JPC_COD_SOP;
break;
case OPT_EPH:
cp->tcp.csty |= JPC_COD_EPH;
break;
case OPT_LAZY:
tccp->cblksty |= JPC_COX_LAZY;
break;
case OPT_TERMALL:
tccp->cblksty |= JPC_COX_TERMALL;
break;
case OPT_SEGSYM:
tccp->cblksty |= JPC_COX_SEGSYM;
break;
case OPT_VCAUSAL:
tccp->cblksty |= JPC_COX_VSC;
break;
case OPT_RESET:
tccp->cblksty |= JPC_COX_RESET;
break;
case OPT_PTERM:
tccp->cblksty |= JPC_COX_PTERM;
break;
case OPT_NUMGBITS:
cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
break;
case OPT_RATE:
if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
&cp->totalsize)) {
jas_eprintf("ignoring bad rate specifier %s\n",
jas_tvparser_getval(tvp));
}
break;
case OPT_ILYRRATES:
if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
&ilyrrates)) {
jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n",
jas_tvparser_getval(tvp));
}
break;
case OPT_JP2OVERHEAD:
jp2overhead = atoi(jas_tvparser_getval(tvp));
break;
default:
jas_eprintf("warning: ignoring invalid option %s\n",
jas_tvparser_gettag(tvp));
break;
}
}
jas_tvparser_destroy(tvp);
tvp = 0;
if (cp->totalsize != UINT_FAST32_MAX) {
cp->totalsize = (cp->totalsize > jp2overhead) ?
(cp->totalsize - jp2overhead) : 0;
}
if (cp->imgareatlx == UINT_FAST32_MAX) {
cp->imgareatlx = 0;
} else {
if (hsteplcm != 1) {
jas_eprintf("warning: overriding imgareatlx value\n");
}
cp->imgareatlx *= hsteplcm;
}
if (cp->imgareatly == UINT_FAST32_MAX) {
cp->imgareatly = 0;
} else {
if (vsteplcm != 1) {
jas_eprintf("warning: overriding imgareatly value\n");
}
cp->imgareatly *= vsteplcm;
}
cp->refgrdwidth = cp->imgareatlx + jas_image_width(image);
cp->refgrdheight = cp->imgareatly + jas_image_height(image);
if (cp->tilegrdoffx == UINT_FAST32_MAX) {
cp->tilegrdoffx = cp->imgareatlx;
}
if (cp->tilegrdoffy == UINT_FAST32_MAX) {
cp->tilegrdoffy = cp->imgareatly;
}
if (!cp->tilewidth) {
cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;
}
if (!cp->tileheight) {
cp->tileheight = cp->refgrdheight - cp->tilegrdoffy;
}
if (cp->numcmpts == 3) {
mctvalid = true;
for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||
jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||
jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||
jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {
mctvalid = false;
}
}
} else {
mctvalid = false;
}
if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {
jas_eprintf("warning: color space apparently not RGB\n");
}
if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {
tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);
} else {
tcp->mctid = JPC_MCT_NONE;
}
tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);
for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
tccp->prcwidthexpns[rlvlno] = prcwidthexpn;
tccp->prcheightexpns[rlvlno] = prcheightexpn;
}
if (prcwidthexpn != 15 || prcheightexpn != 15) {
tccp->csty |= JPC_COX_PRT;
}
/* Ensure that the tile width and height is valid. */
if (!cp->tilewidth) {
jas_eprintf("invalid tile width %lu\n", (unsigned long)
cp->tilewidth);
goto error;
}
if (!cp->tileheight) {
jas_eprintf("invalid tile height %lu\n", (unsigned long)
cp->tileheight);
goto error;
}
/* Ensure that the tile grid offset is valid. */
if (cp->tilegrdoffx > cp->imgareatlx ||
cp->tilegrdoffy > cp->imgareatly ||
cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||
cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {
jas_eprintf("invalid tile grid offset (%lu, %lu)\n",
(unsigned long) cp->tilegrdoffx, (unsigned long)
cp->tilegrdoffy);
goto error;
}
cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,
cp->tilewidth);
cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,
cp->tileheight);
cp->numtiles = cp->numhtiles * cp->numvtiles;
if (ilyrrates && numilyrrates > 0) {
tcp->numlyrs = numilyrrates + 1;
if (!(tcp->ilyrrates = jas_malloc((tcp->numlyrs - 1) *
sizeof(jpc_fix_t)))) {
goto error;
}
for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {
tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);
}
}
/* Ensure that the integer mode is used in the case of lossless
coding. */
if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {
jas_eprintf("cannot use real mode for lossless coding\n");
goto error;
}
/* Ensure that the precinct width is valid. */
if (prcwidthexpn > 15) {
jas_eprintf("invalid precinct width\n");
goto error;
}
/* Ensure that the precinct height is valid. */
if (prcheightexpn > 15) {
jas_eprintf("invalid precinct height\n");
goto error;
}
/* Ensure that the code block width is valid. */
if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {
jas_eprintf("invalid code block width %d\n",
JPC_POW2(cp->tccp.cblkwidthexpn));
goto error;
}
/* Ensure that the code block height is valid. */
if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {
jas_eprintf("invalid code block height %d\n",
JPC_POW2(cp->tccp.cblkheightexpn));
goto error;
}
/* Ensure that the code block size is not too large. */
if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {
jas_eprintf("code block size too large\n");
goto error;
}
/* Ensure that the number of layers is valid. */
if (cp->tcp.numlyrs > 16384) {
jas_eprintf("too many layers\n");
goto error;
}
/* There must be at least one resolution level. */
if (cp->tccp.maxrlvls < 1) {
jas_eprintf("must be at least one resolution level\n");
goto error;
}
/* Ensure that the number of guard bits is valid. */
if (cp->tccp.numgbits > 8) {
jas_eprintf("invalid number of guard bits\n");
goto error;
}
/* Ensure that the rate is within the legal range. */
if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {
jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);
}
/* Ensure that the intermediate layer rates are valid. */
if (tcp->numlyrs > 1) {
/* The intermediate layers rates must increase monotonically. */
for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
jas_eprintf("intermediate layer rates must increase monotonically\n");
goto error;
}
}
/* The intermediate layer rates must be less than the overall rate. */
if (cp->totalsize != UINT_FAST32_MAX) {
for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)
/ cp->rawsize) {
jas_eprintf("warning: intermediate layer rates must be less than overall rate\n");
goto error;
}
}
}
}
if (ilyrrates) {
jas_free(ilyrrates);
}
return cp;
error:
if (ilyrrates) {
jas_free(ilyrrates);
}
if (tvp) {
jas_tvparser_destroy(tvp);
}
if (cp) {
jpc_enc_cp_destroy(cp);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being
invoked with the size argument being computed in a manner that would not
allow integer overflow to be detected. Now, these places in the code
have been modified to use special-purpose memory allocation functions
(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.
This should fix many security problems.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
jpc_fix_t *buf = joinbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
*dstptr = *srcptr;
srcptr += stride;
++dstptr;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += 2 * stride;
++srcptr;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being
invoked with the size argument being computed in a manner that would not
allow integer overflow to be detected. Now, these places in the code
have been modified to use special-purpose memory allocation functions
(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.
This should fix many security problems.'</s> |
<s>[INST] Given the following code containing errors, provide 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 jas_stream_printf(jas_stream_t *stream, const char *fmt, ...)
{
va_list ap;
char buf[4096];
int ret;
va_start(ap, fmt);
ret = vsprintf(buf, fmt, ap);
jas_stream_puts(stream, buf);
va_end(ap);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'CVE-2008-3522'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: sctp_disposition_t sctp_sf_do_asconf_ack(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *asconf_ack = arg;
struct sctp_chunk *last_asconf = asoc->addip_last_asconf;
struct sctp_chunk *abort;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *addip_hdr;
__u32 sent_serial, rcvd_serial;
if (!sctp_vtag_verify(asconf_ack, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/* ADD-IP, Section 4.1.2:
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!sctp_addip_noauth && !asconf_ack->auth)
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
/* Make sure that the ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data;
rcvd_serial = ntohl(addip_hdr->serial);
/* Verify the ASCONF-ACK chunk before processing it. */
if (!sctp_verify_asconf(asoc,
(sctp_paramhdr_t *)addip_hdr->params,
(void *)asconf_ack->chunk_end,
&err_param))
return sctp_sf_violation_paramlen(ep, asoc, type,
(void *)&err_param, commands);
if (last_asconf) {
addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr;
sent_serial = ntohl(addip_hdr->serial);
} else {
sent_serial = asoc->addip_serial - 1;
}
/* D0) If an endpoint receives an ASCONF-ACK that is greater than or
* equal to the next serial number to be used but no ASCONF chunk is
* outstanding the endpoint MUST ABORT the association. Note that a
* sequence number is greater than if it is no more than 2^^31-1
* larger than the current sequence number (using serial arithmetic).
*/
if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&
!(asoc->addip_last_asconf)) {
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
if (!sctp_process_asconf_ack((struct sctp_association *)asoc,
asconf_ack))
return SCTP_DISPOSITION_CONSUME;
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
return SCTP_DISPOSITION_DISCARD;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'sctp: Fix kernel panic while process protocol violation parameter
Since call to function sctp_sf_abort_violation() need paramter 'arg' with
'struct sctp_chunk' type, it will read the chunk type and chunk length from
the chunk_hdr member of chunk. But call to sctp_sf_violation_paramlen()
always with 'struct sctp_paramhdr' type's parameter, it will be passed to
sctp_sf_abort_violation(). This may cause kernel panic.
sctp_sf_violation_paramlen()
|-- sctp_sf_abort_violation()
|-- sctp_make_abort_violation()
This patch fixed this problem. This patch also fix two place which called
sctp_sf_violation_paramlen() with wrong paramter type.
Signed-off-by: Wei Yongjun <yjwei@cn.fujitsu.com>
Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int hfsplus_block_allocate(struct super_block *sb, u32 size, u32 offset, u32 *max)
{
struct page *page;
struct address_space *mapping;
__be32 *pptr, *curr, *end;
u32 mask, start, len, n;
__be32 val;
int i;
len = *max;
if (!len)
return size;
dprint(DBG_BITMAP, "block_allocate: %u,%u,%u\n", size, offset, len);
mutex_lock(&HFSPLUS_SB(sb).alloc_file->i_mutex);
mapping = HFSPLUS_SB(sb).alloc_file->i_mapping;
page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL);
pptr = kmap(page);
curr = pptr + (offset & (PAGE_CACHE_BITS - 1)) / 32;
i = offset % 32;
offset &= ~(PAGE_CACHE_BITS - 1);
if ((size ^ offset) / PAGE_CACHE_BITS)
end = pptr + PAGE_CACHE_BITS / 32;
else
end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32;
/* scan the first partial u32 for zero bits */
val = *curr;
if (~val) {
n = be32_to_cpu(val);
mask = (1U << 31) >> i;
for (; i < 32; mask >>= 1, i++) {
if (!(n & mask))
goto found;
}
}
curr++;
/* scan complete u32s for the first zero bit */
while (1) {
while (curr < end) {
val = *curr;
if (~val) {
n = be32_to_cpu(val);
mask = 1 << 31;
for (i = 0; i < 32; mask >>= 1, i++) {
if (!(n & mask))
goto found;
}
}
curr++;
}
kunmap(page);
offset += PAGE_CACHE_BITS;
if (offset >= size)
break;
page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS,
NULL);
curr = pptr = kmap(page);
if ((size ^ offset) / PAGE_CACHE_BITS)
end = pptr + PAGE_CACHE_BITS / 32;
else
end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32;
}
dprint(DBG_BITMAP, "bitmap full\n");
start = size;
goto out;
found:
start = offset + (curr - pptr) * 32 + i;
if (start >= size) {
dprint(DBG_BITMAP, "bitmap full\n");
goto out;
}
/* do any partial u32 at the start */
len = min(size - start, len);
while (1) {
n |= mask;
if (++i >= 32)
break;
mask >>= 1;
if (!--len || n & mask)
goto done;
}
if (!--len)
goto done;
*curr++ = cpu_to_be32(n);
/* do full u32s */
while (1) {
while (curr < end) {
n = be32_to_cpu(*curr);
if (len < 32)
goto last;
if (n) {
len = 32;
goto last;
}
*curr++ = cpu_to_be32(0xffffffff);
len -= 32;
}
set_page_dirty(page);
kunmap(page);
offset += PAGE_CACHE_BITS;
page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS,
NULL);
pptr = kmap(page);
curr = pptr;
end = pptr + PAGE_CACHE_BITS / 32;
}
last:
/* do any partial u32 at end */
mask = 1U << 31;
for (i = 0; i < len; i++) {
if (n & mask)
break;
n |= mask;
mask >>= 1;
}
done:
*curr = cpu_to_be32(n);
set_page_dirty(page);
kunmap(page);
*max = offset + (curr - pptr) * 32 + i - start;
HFSPLUS_SB(sb).free_blocks -= *max;
sb->s_dirt = 1;
dprint(DBG_BITMAP, "-> %u,%u\n", start, *max);
out:
mutex_unlock(&HFSPLUS_SB(sb).alloc_file->i_mutex);
return start;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'hfsplus: check read_mapping_page() return value
While testing more corrupted images with hfsplus, i came across
one which triggered the following bug:
[15840.675016] BUG: unable to handle kernel paging request at fffffffb
[15840.675016] IP: [<c0116a4f>] kmap+0x15/0x56
[15840.675016] *pde = 00008067 *pte = 00000000
[15840.675016] Oops: 0000 [#1] PREEMPT DEBUG_PAGEALLOC
[15840.675016] Modules linked in:
[15840.675016]
[15840.675016] Pid: 11575, comm: ln Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #29)
[15840.675016] EIP: 0060:[<c0116a4f>] EFLAGS: 00010202 CPU: 0
[15840.675016] EIP is at kmap+0x15/0x56
[15840.675016] EAX: 00000246 EBX: fffffffb ECX: 00000000 EDX: cab919c0
[15840.675016] ESI: 000007dd EDI: cab0bcf4 EBP: cab0bc98 ESP: cab0bc94
[15840.675016] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068
[15840.675016] Process ln (pid: 11575, ti=cab0b000 task=cab919c0 task.ti=cab0b000)
[15840.675016] Stack: 00000000 cab0bcdc c0231cfb 00000000 cab0bce0 00000800 ca9290c0 fffffffb
[15840.675016] cab145d0 cab919c0 cab15998 22222222 22222222 22222222 00000001 cab15960
[15840.675016] 000007dd cab0bcf4 cab0bd04 c022cb3a cab0bcf4 cab15a6c ca9290c0 00000000
[15840.675016] Call Trace:
[15840.675016] [<c0231cfb>] ? hfsplus_block_allocate+0x6f/0x2d3
[15840.675016] [<c022cb3a>] ? hfsplus_file_extend+0xc4/0x1db
[15840.675016] [<c022ce41>] ? hfsplus_get_block+0x8c/0x19d
[15840.675016] [<c06adde4>] ? sub_preempt_count+0x9d/0xab
[15840.675016] [<c019ece6>] ? __block_prepare_write+0x147/0x311
[15840.675016] [<c0161934>] ? __grab_cache_page+0x52/0x73
[15840.675016] [<c019ef4f>] ? block_write_begin+0x79/0xd5
[15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d
[15840.675016] [<c019f22a>] ? cont_write_begin+0x27f/0x2af
[15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d
[15840.675016] [<c0139ebe>] ? tick_program_event+0x28/0x4c
[15840.675016] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd
[15840.675016] [<c022b723>] ? hfsplus_write_begin+0x2d/0x32
[15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d
[15840.675016] [<c0161988>] ? pagecache_write_begin+0x33/0x107
[15840.675016] [<c01879e5>] ? __page_symlink+0x3c/0xae
[15840.675016] [<c019ad34>] ? __mark_inode_dirty+0x12f/0x137
[15840.675016] [<c0187a70>] ? page_symlink+0x19/0x1e
[15840.675016] [<c022e6eb>] ? hfsplus_symlink+0x41/0xa6
[15840.675016] [<c01886a9>] ? vfs_symlink+0x99/0x101
[15840.675016] [<c018a2f6>] ? sys_symlinkat+0x6b/0xad
[15840.675016] [<c018a348>] ? sys_symlink+0x10/0x12
[15840.675016] [<c01038bd>] ? sysenter_do_call+0x12/0x31
[15840.675016] =======================
[15840.675016] Code: 00 00 75 10 83 3d 88 2f ec c0 02 75 07 89 d0 e8 12 56 05 00 5d c3 55 ba 06 00 00 00 89 e5 53 89 c3 b8 3d eb 7e c0 e8 16 74 00 00 <8b> 03 c1 e8 1e 69 c0 d8 02 00 00 05 b8 69 8e c0 2b 80 c4 02 00
[15840.675016] EIP: [<c0116a4f>] kmap+0x15/0x56 SS:ESP 0068:cab0bc94
[15840.675016] ---[ end trace 4fea40dad6b70e5f ]---
This happens because the return value of read_mapping_page() is passed on
to kmap unchecked. The bug is triggered after the first
read_mapping_page() in hfsplus_block_allocate(), this patch fixes all
three usages in this functions but leaves the ones further down in the
file unchanged.
Signed-off-by: Eric Sesterhenn <snakebyte@gmx.de>
Cc: Roman Zippel <zippel@linux-m68k.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 untag_chunk(struct audit_chunk *chunk, struct node *p)
{
struct audit_chunk *new;
struct audit_tree *owner;
int size = chunk->count - 1;
int i, j;
mutex_lock(&chunk->watch.inode->inotify_mutex);
if (chunk->dead) {
mutex_unlock(&chunk->watch.inode->inotify_mutex);
return;
}
owner = p->owner;
if (!size) {
chunk->dead = 1;
spin_lock(&hash_lock);
list_del_init(&chunk->trees);
if (owner->root == chunk)
owner->root = NULL;
list_del_init(&p->list);
list_del_rcu(&chunk->hash);
spin_unlock(&hash_lock);
inotify_evict_watch(&chunk->watch);
mutex_unlock(&chunk->watch.inode->inotify_mutex);
put_inotify_watch(&chunk->watch);
return;
}
new = alloc_chunk(size);
if (!new)
goto Fallback;
if (inotify_clone_watch(&chunk->watch, &new->watch) < 0) {
free_chunk(new);
goto Fallback;
}
chunk->dead = 1;
spin_lock(&hash_lock);
list_replace_init(&chunk->trees, &new->trees);
if (owner->root == chunk) {
list_del_init(&owner->same_root);
owner->root = NULL;
}
for (i = j = 0; i < size; i++, j++) {
struct audit_tree *s;
if (&chunk->owners[j] == p) {
list_del_init(&p->list);
i--;
continue;
}
s = chunk->owners[j].owner;
new->owners[i].owner = s;
new->owners[i].index = chunk->owners[j].index - j + i;
if (!s) /* result of earlier fallback */
continue;
get_tree(s);
list_replace_init(&chunk->owners[i].list, &new->owners[j].list);
}
list_replace_rcu(&chunk->hash, &new->hash);
list_for_each_entry(owner, &new->trees, same_root)
owner->root = new;
spin_unlock(&hash_lock);
inotify_evict_watch(&chunk->watch);
mutex_unlock(&chunk->watch.inode->inotify_mutex);
put_inotify_watch(&chunk->watch);
return;
Fallback:
// do the best we can
spin_lock(&hash_lock);
if (owner->root == chunk) {
list_del_init(&owner->same_root);
owner->root = NULL;
}
list_del_init(&p->list);
p->owner = NULL;
put_tree(owner);
spin_unlock(&hash_lock);
mutex_unlock(&chunk->watch.inode->inotify_mutex);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races
Inotify watch removals suck violently.
To kick the watch out we need (in this order) inode->inotify_mutex and
ih->mutex. That's fine if we have a hold on inode; however, for all
other cases we need to make damn sure we don't race with umount. We can
*NOT* just grab a reference to a watch - inotify_unmount_inodes() will
happily sail past it and we'll end with reference to inode potentially
outliving its superblock.
Ideally we just want to grab an active reference to superblock if we
can; that will make sure we won't go into inotify_umount_inodes() until
we are done. Cleanup is just deactivate_super().
However, that leaves a messy case - what if we *are* racing with
umount() and active references to superblock can't be acquired anymore?
We can bump ->s_count, grab ->s_umount, which will almost certainly wait
until the superblock is shut down and the watch in question is pining
for fjords. That's fine, but there is a problem - we might have hit the
window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e.
the moment when superblock is past the point of no return and is heading
for shutdown) and the moment when deactivate_super() acquires
->s_umount.
We could just do drop_super() yield() and retry, but that's rather
antisocial and this stuff is luser-triggerable. OTOH, having grabbed
->s_umount and having found that we'd got there first (i.e. that
->s_root is non-NULL) we know that we won't race with
inotify_umount_inodes().
So we could grab a reference to watch and do the rest as above, just
with drop_super() instead of deactivate_super(), right? Wrong. We had
to drop ih->mutex before we could grab ->s_umount. So the watch
could've been gone already.
That still can be dealt with - we need to save watch->wd, do idr_find()
and compare its result with our pointer. If they match, we either have
the damn thing still alive or we'd lost not one but two races at once,
the watch had been killed and a new one got created with the same ->wd
at the same address. That couldn't have happened in inotify_destroy(),
but inotify_rm_wd() could run into that. Still, "new one got created"
is not a problem - we have every right to kill it or leave it alone,
whatever's more convenient.
So we can use idr_find(...) == watch && watch->inode->i_sb == sb as
"grab it and kill it" check. If it's been our original watch, we are
fine, if it's a newcomer - nevermind, just pretend that we'd won the
race and kill the fscker anyway; we are safe since we know that its
superblock won't be going away.
And yes, this is far beyond mere "not very pretty"; so's the entire
concept of inotify to start with.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
Acked-by: Greg KH <greg@kroah.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static struct audit_chunk *find_chunk(struct node *p)
{
int index = p->index & ~(1U<<31);
p -= index;
return container_of(p, struct audit_chunk, owners[0]);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races
Inotify watch removals suck violently.
To kick the watch out we need (in this order) inode->inotify_mutex and
ih->mutex. That's fine if we have a hold on inode; however, for all
other cases we need to make damn sure we don't race with umount. We can
*NOT* just grab a reference to a watch - inotify_unmount_inodes() will
happily sail past it and we'll end with reference to inode potentially
outliving its superblock.
Ideally we just want to grab an active reference to superblock if we
can; that will make sure we won't go into inotify_umount_inodes() until
we are done. Cleanup is just deactivate_super().
However, that leaves a messy case - what if we *are* racing with
umount() and active references to superblock can't be acquired anymore?
We can bump ->s_count, grab ->s_umount, which will almost certainly wait
until the superblock is shut down and the watch in question is pining
for fjords. That's fine, but there is a problem - we might have hit the
window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e.
the moment when superblock is past the point of no return and is heading
for shutdown) and the moment when deactivate_super() acquires
->s_umount.
We could just do drop_super() yield() and retry, but that's rather
antisocial and this stuff is luser-triggerable. OTOH, having grabbed
->s_umount and having found that we'd got there first (i.e. that
->s_root is non-NULL) we know that we won't race with
inotify_umount_inodes().
So we could grab a reference to watch and do the rest as above, just
with drop_super() instead of deactivate_super(), right? Wrong. We had
to drop ih->mutex before we could grab ->s_umount. So the watch
could've been gone already.
That still can be dealt with - we need to save watch->wd, do idr_find()
and compare its result with our pointer. If they match, we either have
the damn thing still alive or we'd lost not one but two races at once,
the watch had been killed and a new one got created with the same ->wd
at the same address. That couldn't have happened in inotify_destroy(),
but inotify_rm_wd() could run into that. Still, "new one got created"
is not a problem - we have every right to kill it or leave it alone,
whatever's more convenient.
So we can use idr_find(...) == watch && watch->inode->i_sb == sb as
"grab it and kill it" check. If it's been our original watch, we are
fine, if it's a newcomer - nevermind, just pretend that we'd won the
race and kill the fscker anyway; we are safe since we know that its
superblock won't be going away.
And yes, this is far beyond mere "not very pretty"; so's the entire
concept of inotify to start with.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
Acked-by: Greg KH <greg@kroah.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 dispatch_packet(AvahiServer *s, AvahiDnsPacket *p, const AvahiAddress *src_address, uint16_t port, const AvahiAddress *dst_address, AvahiIfIndex iface, int ttl) {
AvahiInterface *i;
int from_local_iface = 0;
assert(s);
assert(p);
assert(src_address);
assert(dst_address);
assert(iface > 0);
assert(src_address->proto == dst_address->proto);
if (!(i = avahi_interface_monitor_get_interface(s->monitor, iface, src_address->proto)) ||
!i->announcing) {
avahi_log_warn("Received packet from invalid interface.");
return;
}
if (avahi_address_is_ipv4_in_ipv6(src_address))
/* This is an IPv4 address encapsulated in IPv6, so let's ignore it. */
return;
if (originates_from_local_legacy_unicast_socket(s, src_address, port))
/* This originates from our local reflector, so let's ignore it */
return;
/* We don't want to reflect local traffic, so we check if this packet is generated locally. */
if (s->config.enable_reflector)
from_local_iface = originates_from_local_iface(s, iface, src_address, port);
if (avahi_dns_packet_check_valid_multicast(p) < 0) {
avahi_log_warn("Received invalid packet.");
return;
}
if (avahi_dns_packet_is_query(p)) {
int legacy_unicast = 0;
if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ARCOUNT) != 0) {
avahi_log_warn("Invalid query packet.");
return;
}
if (port != AVAHI_MDNS_PORT) {
/* Legacy Unicast */
if ((avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) != 0 ||
avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0)) {
avahi_log_warn("Invalid legacy unicast query packet.");
return;
}
legacy_unicast = 1;
}
if (legacy_unicast)
reflect_legacy_unicast_query_packet(s, p, i, src_address, port);
handle_query_packet(s, p, i, src_address, port, legacy_unicast, from_local_iface);
} else {
char t[AVAHI_ADDRESS_STR_MAX];
if (port != AVAHI_MDNS_PORT) {
avahi_log_warn("Received response from host %s with invalid source port %u on interface '%s.%i'", avahi_address_snprint(t, sizeof(t), src_address), port, i->hardware->name, i->protocol);
return;
}
if (ttl != 255 && s->config.check_response_ttl) {
avahi_log_warn("Received response from host %s with invalid TTL %u on interface '%s.%i'.", avahi_address_snprint(t, sizeof(t), src_address), ttl, i->hardware->name, i->protocol);
return;
}
if (!is_mdns_mcast_address(dst_address) &&
!avahi_interface_address_on_link(i, src_address)) {
avahi_log_warn("Received non-local response from host %s on interface '%s.%i'.", avahi_address_snprint(t, sizeof(t), src_address), i->hardware->name, i->protocol);
return;
}
if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_QDCOUNT) != 0 ||
avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) == 0 ||
avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0) {
avahi_log_warn("Invalid response packet from host %s.", avahi_address_snprint(t, sizeof(t), src_address));
return;
}
handle_response_packet(s, p, i, src_address, from_local_iface);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Don't get confused by UDP packets with a source port that is zero
This is a fix for rhbz 475394.
Problem identified by Hugo Dias.'</s> |
<s>[INST] Given the following code containing errors, provide 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 _af_adpcm_decoder (uint8_t *indata, int16_t *outdata, int len,
struct adpcm_state *state)
{
uint8_t *inp; /* Input buffer pointer */
int16_t *outp; /* output buffer pointer */
int sign; /* Current adpcm sign bit */
int delta; /* Current adpcm output value */
int step; /* Stepsize */
int valpred; /* Predicted value */
int vpdiff; /* Current change to valpred */
int index; /* Current step change index */
int inputbuffer; /* place to keep next 4-bit value */
int bufferstep; /* toggle between inputbuffer/input */
outp = outdata;
inp = indata;
valpred = state->valprev;
index = state->index;
step = stepsizeTable[index];
bufferstep = 0;
for ( ; len > 0 ; len-- ) {
/* Step 1 - get the delta value */
if ( bufferstep ) {
delta = (inputbuffer >> 4) & 0xf;
} else {
inputbuffer = *inp++;
delta = inputbuffer & 0xf;
}
bufferstep = !bufferstep;
/* Step 2 - Find new index value (for later) */
index += indexTable[delta];
if ( index < 0 ) index = 0;
if ( index > 88 ) index = 88;
/* Step 3 - Separate sign and magnitude */
sign = delta & 8;
delta = delta & 7;
/* Step 4 - Compute difference and new predicted value */
/*
** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
** in adpcm_coder.
*/
vpdiff = step >> 3;
if ( delta & 4 ) vpdiff += step;
if ( delta & 2 ) vpdiff += step>>1;
if ( delta & 1 ) vpdiff += step>>2;
if ( sign )
valpred -= vpdiff;
else
valpred += vpdiff;
/* Step 5 - clamp output value */
if ( valpred > 32767 )
valpred = 32767;
else if ( valpred < -32768 )
valpred = -32768;
/* Step 6 - Update step value */
step = stepsizeTable[index];
/* Step 7 - Output value */
*outp++ = valpred;
}
state->valprev = valpred;
state->index = index;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
union {
int val;
struct linger ling;
struct timeval tm;
} v;
unsigned int lv = sizeof(int);
int len;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch(optname) {
case SO_DEBUG:
v.val = sock_flag(sk, SOCK_DBG);
break;
case SO_DONTROUTE:
v.val = sock_flag(sk, SOCK_LOCALROUTE);
break;
case SO_BROADCAST:
v.val = !!sock_flag(sk, SOCK_BROADCAST);
break;
case SO_SNDBUF:
v.val = sk->sk_sndbuf;
break;
case SO_RCVBUF:
v.val = sk->sk_rcvbuf;
break;
case SO_REUSEADDR:
v.val = sk->sk_reuse;
break;
case SO_KEEPALIVE:
v.val = !!sock_flag(sk, SOCK_KEEPOPEN);
break;
case SO_TYPE:
v.val = sk->sk_type;
break;
case SO_ERROR:
v.val = -sock_error(sk);
if (v.val==0)
v.val = xchg(&sk->sk_err_soft, 0);
break;
case SO_OOBINLINE:
v.val = !!sock_flag(sk, SOCK_URGINLINE);
break;
case SO_NO_CHECK:
v.val = sk->sk_no_check;
break;
case SO_PRIORITY:
v.val = sk->sk_priority;
break;
case SO_LINGER:
lv = sizeof(v.ling);
v.ling.l_onoff = !!sock_flag(sk, SOCK_LINGER);
v.ling.l_linger = sk->sk_lingertime / HZ;
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("getsockopt");
break;
case SO_TIMESTAMP:
v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
!sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPNS:
v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_RCVTIMEO:
lv=sizeof(struct timeval);
if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_SNDTIMEO:
lv=sizeof(struct timeval);
if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_sndtimeo / HZ;
v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_RCVLOWAT:
v.val = sk->sk_rcvlowat;
break;
case SO_SNDLOWAT:
v.val=1;
break;
case SO_PASSCRED:
v.val = test_bit(SOCK_PASSCRED, &sock->flags) ? 1 : 0;
break;
case SO_PEERCRED:
if (len > sizeof(sk->sk_peercred))
len = sizeof(sk->sk_peercred);
if (copy_to_user(optval, &sk->sk_peercred, len))
return -EFAULT;
goto lenout;
case SO_PEERNAME:
{
char address[128];
if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))
return -ENOTCONN;
if (lv < len)
return -EINVAL;
if (copy_to_user(optval, address, len))
return -EFAULT;
goto lenout;
}
/* Dubious BSD thing... Probably nobody even uses it, but
* the UNIX standard wants it for whatever reason... -DaveM
*/
case SO_ACCEPTCONN:
v.val = sk->sk_state == TCP_LISTEN;
break;
case SO_PASSSEC:
v.val = test_bit(SOCK_PASSSEC, &sock->flags) ? 1 : 0;
break;
case SO_PEERSEC:
return security_socket_getpeersec_stream(sock, optval, optlen, len);
case SO_MARK:
v.val = sk->sk_mark;
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (copy_to_user(optval, &v, len))
return -EFAULT;
lenout:
if (put_user(len, optlen))
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'net: 4 bytes kernel memory disclosure in SO_BSDCOMPAT gsopt try #2
In function sock_getsockopt() located in net/core/sock.c, optval v.val
is not correctly initialized and directly returned in userland in case
we have SO_BSDCOMPAT option set.
This dummy code should trigger the bug:
int main(void)
{
unsigned char buf[4] = { 0, 0, 0, 0 };
int len;
int sock;
sock = socket(33, 2, 2);
getsockopt(sock, 1, SO_BSDCOMPAT, &buf, &len);
printf("%x%x%x%x\n", buf[0], buf[1], buf[2], buf[3]);
close(sock);
}
Here is a patch that fix this bug by initalizing v.val just after its
declaration.
Signed-off-by: Clément Lecigne <clement.lecigne@netasq.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 inotify_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
size_t event_size = sizeof (struct inotify_event);
struct inotify_device *dev;
char __user *start;
int ret;
DEFINE_WAIT(wait);
start = buf;
dev = file->private_data;
while (1) {
prepare_to_wait(&dev->wq, &wait, TASK_INTERRUPTIBLE);
mutex_lock(&dev->ev_mutex);
if (!list_empty(&dev->events)) {
ret = 0;
break;
}
mutex_unlock(&dev->ev_mutex);
if (file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = -EINTR;
break;
}
schedule();
}
finish_wait(&dev->wq, &wait);
if (ret)
return ret;
while (1) {
struct inotify_kernel_event *kevent;
ret = buf - start;
if (list_empty(&dev->events))
break;
kevent = inotify_dev_get_event(dev);
if (event_size + kevent->event.len > count) {
if (ret == 0 && count > 0) {
/*
* could not get a single event because we
* didn't have enough buffer space.
*/
ret = -EINVAL;
}
break;
}
remove_kevent(dev, kevent);
/*
* Must perform the copy_to_user outside the mutex in order
* to avoid a lock order reversal with mmap_sem.
*/
mutex_unlock(&dev->ev_mutex);
if (copy_to_user(buf, &kevent->event, event_size)) {
ret = -EFAULT;
break;
}
buf += event_size;
count -= event_size;
if (kevent->name) {
if (copy_to_user(buf, kevent->name, kevent->event.len)){
ret = -EFAULT;
break;
}
buf += kevent->event.len;
count -= kevent->event.len;
}
free_kevent(kevent);
mutex_lock(&dev->ev_mutex);
}
mutex_unlock(&dev->ev_mutex);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'inotify: clean up inotify_read and fix locking problems
If userspace supplies an invalid pointer to a read() of an inotify
instance, the inotify device's event list mutex is unlocked twice.
This causes an unbalance which effectively leaves the data structure
unprotected, and we can trigger oopses by accessing the inotify
instance from different tasks concurrently.
The best fix (contributed largely by Linus) is a total rewrite
of the function in question:
On Thu, Jan 22, 2009 at 7:05 AM, Linus Torvalds wrote:
> The thing to notice is that:
>
> - locking is done in just one place, and there is no question about it
> not having an unlock.
>
> - that whole double-while(1)-loop thing is gone.
>
> - use multiple functions to make nesting and error handling sane
>
> - do error testing after doing the things you always need to do, ie do
> this:
>
> mutex_lock(..)
> ret = function_call();
> mutex_unlock(..)
>
> .. test ret here ..
>
> instead of doing conditional exits with unlocking or freeing.
>
> So if the code is written in this way, it may still be buggy, but at least
> it's not buggy because of subtle "forgot to unlock" or "forgot to free"
> issues.
>
> This _always_ unlocks if it locked, and it always frees if it got a
> non-error kevent.
Cc: John McCutchan <ttb@tentacle.dhs.org>
Cc: Robert Love <rlove@google.com>
Cc: <stable@kernel.org>
Signed-off-by: Vegard Nossum <vegard.nossum@gmail.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 nfs_server *nfs_create_server(const struct nfs_mount_data *data,
struct nfs_fh *mntfh)
{
struct nfs_server *server;
struct nfs_fattr fattr;
int error;
server = nfs_alloc_server();
if (!server)
return ERR_PTR(-ENOMEM);
/* Get a client representation */
error = nfs_init_server(server, data);
if (error < 0)
goto error;
BUG_ON(!server->nfs_client);
BUG_ON(!server->nfs_client->rpc_ops);
BUG_ON(!server->nfs_client->rpc_ops->file_inode_ops);
/* Probe the root fh to retrieve its FSID */
error = nfs_probe_fsinfo(server, mntfh, &fattr);
if (error < 0)
goto error;
if (!(fattr.valid & NFS_ATTR_FATTR)) {
error = server->nfs_client->rpc_ops->getattr(server, mntfh, &fattr);
if (error < 0) {
dprintk("nfs_create_server: getattr error = %d\n", -error);
goto error;
}
}
memcpy(&server->fsid, &fattr.fsid, sizeof(server->fsid));
dprintk("Server FSID: %llx:%llx\n",
(unsigned long long) server->fsid.major,
(unsigned long long) server->fsid.minor);
BUG_ON(!server->nfs_client);
BUG_ON(!server->nfs_client->rpc_ops);
BUG_ON(!server->nfs_client->rpc_ops->file_inode_ops);
spin_lock(&nfs_client_lock);
list_add_tail(&server->client_link, &server->nfs_client->cl_superblocks);
list_add_tail(&server->master_link, &nfs_volume_list);
spin_unlock(&nfs_client_lock);
server->mount_time = jiffies;
return server;
error:
nfs_free_server(server);
return ERR_PTR(error);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup()
It doesn't look as if the NFS file name limit is being initialised correctly
in the struct nfs_server. Make sure that we limit whatever is being set in
nfs_probe_fsinfo() and nfs_init_server().
Also ensure that readdirplus and nfs4_path_walk respect our file name
limits.
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_msr_entry *msr;
u64 host_tsc;
int ret = 0;
switch (msr_index) {
#ifdef CONFIG_X86_64
case MSR_EFER:
vmx_load_host_state(vmx);
ret = kvm_set_msr_common(vcpu, msr_index, data);
break;
case MSR_FS_BASE:
vmcs_writel(GUEST_FS_BASE, data);
break;
case MSR_GS_BASE:
vmcs_writel(GUEST_GS_BASE, data);
break;
#endif
case MSR_IA32_SYSENTER_CS:
vmcs_write32(GUEST_SYSENTER_CS, data);
break;
case MSR_IA32_SYSENTER_EIP:
vmcs_writel(GUEST_SYSENTER_EIP, data);
break;
case MSR_IA32_SYSENTER_ESP:
vmcs_writel(GUEST_SYSENTER_ESP, data);
break;
case MSR_IA32_TIME_STAMP_COUNTER:
rdtscll(host_tsc);
guest_write_tsc(data, host_tsc);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
/*
* Just discard all writes to the performance counters; this
* should keep both older linux and windows 64-bit guests
* happy
*/
pr_unimpl(vcpu, "unimplemented perfctr wrmsr: 0x%x data 0x%llx\n", msr_index, data);
break;
case MSR_IA32_CR_PAT:
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, data);
vcpu->arch.pat = data;
break;
}
/* Otherwise falls through to kvm_set_msr_common */
default:
vmx_load_host_state(vmx);
msr = find_msr_entry(vmx, msr_index);
if (msr) {
msr->data = data;
break;
}
ret = kvm_set_msr_common(vcpu, msr_index, data);
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'KVM: VMX: Don't allow uninhibited access to EFER on i386
vmx_set_msr() does not allow i386 guests to touch EFER, but they can still
do so through the default: label in the switch. If they set EFER_LME, they
can oops the host.
Fix by having EFER access through the normal channel (which will check for
EFER_LME) even on i386.
Reported-and-tested-by: Benjamin Gilbert <bgilbert@cs.cmu.edu>
Cc: stable@kernel.org
Signed-off-by: Avi Kivity <avi@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide 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 udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct udp_sock *up = udp_sk(sk);
int ulen = len;
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
int free = 0;
int connected = 0;
__be32 daddr, faddr, saddr;
__be16 dport;
u8 tos;
int err;
int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
if (len > 0xFFFF)
return -EMSGSIZE;
/*
* Check the flags.
*/
if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
return -EOPNOTSUPP;
ipc.opt = NULL;
if (up->pending) {
/*
* There are pending frames.
* The socket lock must be held while it's corked.
*/
lock_sock(sk);
if (likely(up->pending)) {
if (unlikely(up->pending != AF_INET)) {
release_sock(sk);
return -EINVAL;
}
goto do_append_data;
}
release_sock(sk);
}
ulen += sizeof(struct udphdr);
/*
* Get and verify the address.
*/
if (msg->msg_name) {
struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
if (msg->msg_namelen < sizeof(*usin))
return -EINVAL;
if (usin->sin_family != AF_INET) {
if (usin->sin_family != AF_UNSPEC)
return -EAFNOSUPPORT;
}
daddr = usin->sin_addr.s_addr;
dport = usin->sin_port;
if (dport == 0)
return -EINVAL;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = inet->daddr;
dport = inet->dport;
/* Open fast path for connected socket.
Route will not be used, if at least one option is set.
*/
connected = 1;
}
ipc.addr = inet->saddr;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(msg, &ipc);
if (err)
return err;
if (ipc.opt)
free = 1;
connected = 0;
}
if (!ipc.opt)
ipc.opt = inet->opt;
saddr = ipc.addr;
ipc.addr = faddr = daddr;
if (ipc.opt && ipc.opt->srr) {
if (!daddr)
return -EINVAL;
faddr = ipc.opt->faddr;
connected = 0;
}
tos = RT_TOS(inet->tos);
if (sock_flag(sk, SOCK_LOCALROUTE) ||
(msg->msg_flags & MSG_DONTROUTE) ||
(ipc.opt && ipc.opt->is_strictroute)) {
tos |= RTO_ONLINK;
connected = 0;
}
if (MULTICAST(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
connected = 0;
}
if (connected)
rt = (struct rtable*)sk_dst_check(sk, 0);
if (rt == NULL) {
struct flowi fl = { .oif = ipc.oif,
.nl_u = { .ip4_u =
{ .daddr = faddr,
.saddr = saddr,
.tos = tos } },
.proto = IPPROTO_UDP,
.uli_u = { .ports =
{ .sport = inet->sport,
.dport = dport } } };
security_sk_classify_flow(sk, &fl);
err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
if (err)
goto out;
err = -EACCES;
if ((rt->rt_flags & RTCF_BROADCAST) &&
!sock_flag(sk, SOCK_BROADCAST))
goto out;
if (connected)
sk_dst_set(sk, dst_clone(&rt->u.dst));
}
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
saddr = rt->rt_src;
if (!ipc.addr)
daddr = ipc.addr = rt->rt_dst;
lock_sock(sk);
if (unlikely(up->pending)) {
/* The socket is already corked while preparing it. */
/* ... which is an evident application bug. --ANK */
release_sock(sk);
LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
err = -EINVAL;
goto out;
}
/*
* Now cork the socket to pend data.
*/
inet->cork.fl.fl4_dst = daddr;
inet->cork.fl.fl_ip_dport = dport;
inet->cork.fl.fl4_src = saddr;
inet->cork.fl.fl_ip_sport = inet->sport;
up->pending = AF_INET;
do_append_data:
up->len += ulen;
err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
sizeof(struct udphdr), &ipc, rt,
corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
if (err)
udp_flush_pending_frames(sk);
else if (!corkreq)
err = udp_push_pending_frames(sk, up);
release_sock(sk);
out:
ip_rt_put(rt);
if (free)
kfree(ipc.opt);
if (!err) {
UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
return len;
}
/*
* ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
* ENOBUFS might not be good (it's not tunable per se), but otherwise
* we don't have a good statistic (IpOutDiscards but it can be too many
* things). We could add another new stat but at least for now that
* seems like overkill.
*/
if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS);
}
return err;
do_confirm:
dst_confirm(&rt->u.dst);
if (!(msg->msg_flags&MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto out;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': '[UDP]: Fix MSG_PROBE crash
UDP tracks corking status through the pending variable. The
IP layer also tracks it through the socket write queue. It
is possible for the two to get out of sync when MSG_PROBE is
used.
This patch changes UDP to check the write queue to ensure
that the two stay in sync.
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static __inline__ int cbq_dump_ovl(struct sk_buff *skb, struct cbq_class *cl)
{
unsigned char *b = skb->tail;
struct tc_cbq_ovl opt;
opt.strategy = cl->ovl_strategy;
opt.priority2 = cl->priority2+1;
opt.penalty = (cl->penalty*1000)/HZ;
RTA_PUT(skb, TCA_CBQ_OVL_STRATEGY, sizeof(opt), &opt);
return skb->len;
rtattr_failure:
skb_trim(skb, b - skb->data);
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing padding fields in dumped structures
Plug holes with padding fields and initialized them to zero.
Signed-off-by: Patrick McHardy <kaber@trash.net>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: tc_dump_action(struct sk_buff *skb, struct netlink_callback *cb)
{
struct nlmsghdr *nlh;
unsigned char *b = skb->tail;
struct rtattr *x;
struct tc_action_ops *a_o;
struct tc_action a;
int ret = 0;
struct tcamsg *t = (struct tcamsg *) NLMSG_DATA(cb->nlh);
char *kind = find_dump_kind(cb->nlh);
if (kind == NULL) {
printk("tc_dump_action: action bad kind\n");
return 0;
}
a_o = tc_lookup_action_n(kind);
if (a_o == NULL) {
printk("failed to find %s\n", kind);
return 0;
}
memset(&a, 0, sizeof(struct tc_action));
a.ops = a_o;
if (a_o->walk == NULL) {
printk("tc_dump_action: %s !capable of dumping table\n", kind);
goto rtattr_failure;
}
nlh = NLMSG_PUT(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq,
cb->nlh->nlmsg_type, sizeof(*t));
t = NLMSG_DATA(nlh);
t->tca_family = AF_UNSPEC;
x = (struct rtattr *) skb->tail;
RTA_PUT(skb, TCA_ACT_TAB, 0, NULL);
ret = a_o->walk(skb, cb, RTM_GETACTION, &a);
if (ret < 0)
goto rtattr_failure;
if (ret > 0) {
x->rta_len = skb->tail - (u8 *) x;
ret = skb->len;
} else
skb_trim(skb, (u8*)x - skb->data);
nlh->nlmsg_len = skb->tail - b;
if (NETLINK_CB(cb->skb).pid && ret)
nlh->nlmsg_flags |= NLM_F_MULTI;
module_put(a_o->owner);
return skb->len;
rtattr_failure:
nlmsg_failure:
module_put(a_o->owner);
skb_trim(skb, b - skb->data);
return skb->len;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data
Mostly missing initialization of padding fields of 1 or 2 bytes length,
two instances of uninitialized nlmsgerr->msg of 16 bytes length.
Signed-off-by: Patrick McHardy <kaber@trash.net>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: __nlmsg_put(struct sk_buff *skb, u32 pid, u32 seq, int type, int len, int flags)
{
struct nlmsghdr *nlh;
int size = NLMSG_LENGTH(len);
nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size));
nlh->nlmsg_type = type;
nlh->nlmsg_len = size;
nlh->nlmsg_flags = flags;
nlh->nlmsg_pid = pid;
nlh->nlmsg_seq = seq;
return nlh;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Clear padding in netlink messages
Signed-off-by: Patrick McHardy <kaber@trash.net>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ReadBMP (const gchar *name,
GError **error)
{
FILE *fd;
guchar buffer[64];
gint ColormapSize, rowbytes, Maps;
gboolean Grey = FALSE;
guchar ColorMap[256][3];
gint32 image_ID;
gchar magick[2];
Bitmap_Channel masks[4];
filename = name;
fd = g_fopen (filename, "rb");
if (!fd)
{
g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),
_("Could not open '%s' for reading: %s"),
gimp_filename_to_utf8 (filename), g_strerror (errno));
return -1;
}
gimp_progress_init_printf (_("Opening '%s'"),
gimp_filename_to_utf8 (name));
/* It is a File. Now is it a Bitmap? Read the shortest possible header */
if (!ReadOK (fd, magick, 2) || !(!strncmp (magick, "BA", 2) ||
!strncmp (magick, "BM", 2) || !strncmp (magick, "IC", 2) ||
!strncmp (magick, "PI", 2) || !strncmp (magick, "CI", 2) ||
!strncmp (magick, "CP", 2)))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
while (!strncmp (magick, "BA", 2))
{
if (!ReadOK (fd, buffer, 12))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
if (!ReadOK (fd, magick, 2))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
}
if (!ReadOK (fd, buffer, 12))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
/* bring them to the right byteorder. Not too nice, but it should work */
Bitmap_File_Head.bfSize = ToL (&buffer[0x00]);
Bitmap_File_Head.zzHotX = ToS (&buffer[0x04]);
Bitmap_File_Head.zzHotY = ToS (&buffer[0x06]);
Bitmap_File_Head.bfOffs = ToL (&buffer[0x08]);
if (!ReadOK (fd, buffer, 4))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
Bitmap_File_Head.biSize = ToL (&buffer[0x00]);
/* What kind of bitmap is it? */
if (Bitmap_File_Head.biSize == 12) /* OS/2 1.x ? */
{
if (!ReadOK (fd, buffer, 8))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error reading BMP file header from '%s'"),
gimp_filename_to_utf8 (filename));
return -1;
}
Bitmap_Head.biWidth = ToS (&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToS (&buffer[0x02]); /* 14 */
Bitmap_Head.biPlanes = ToS (&buffer[0x04]); /* 16 */
Bitmap_Head.biBitCnt = ToS (&buffer[0x06]); /* 18 */
Bitmap_Head.biCompr = 0;
Bitmap_Head.biSizeIm = 0;
Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;
Bitmap_Head.biClrUsed = 0;
Bitmap_Head.biClrImp = 0;
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
memset(masks, 0, sizeof(masks));
Maps = 3;
}
else if (Bitmap_File_Head.biSize == 40) /* Windows 3.x */
{
if (!ReadOK (fd, buffer, 36))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error reading BMP file header from '%s'"),
gimp_filename_to_utf8 (filename));
return -1;
}
Bitmap_Head.biWidth = ToL (&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL (&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS (&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS (&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL (&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL (&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL (&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL (&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL (&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL (&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
Maps = 4;
memset(masks, 0, sizeof(masks));
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
if (!ReadOK (fd, buffer, 3 * sizeof (guint32)))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error reading BMP file header from '%s'"),
gimp_filename_to_utf8 (filename));
return -1;
}
Bitmap_Head.masks[0] = ToL(&buffer[0x00]);
Bitmap_Head.masks[1] = ToL(&buffer[0x04]);
Bitmap_Head.masks[2] = ToL(&buffer[0x08]);
ReadChannelMasks (&Bitmap_Head.masks[0], masks, 3);
}
else
switch (Bitmap_Head.biBitCnt)
{
case 32:
masks[0].mask = 0x00ff0000;
masks[0].shiftin = 16;
masks[0].max_value= (gfloat)255.0;
masks[1].mask = 0x0000ff00;
masks[1].shiftin = 8;
masks[1].max_value= (gfloat)255.0;
masks[2].mask = 0x000000ff;
masks[2].shiftin = 0;
masks[2].max_value= (gfloat)255.0;
masks[3].mask = 0xff000000;
masks[3].shiftin = 24;
masks[3].max_value= (gfloat)255.0;
break;
case 24:
masks[0].mask = 0xff0000;
masks[0].shiftin = 16;
masks[0].max_value= (gfloat)255.0;
masks[1].mask = 0x00ff00;
masks[1].shiftin = 8;
masks[1].max_value= (gfloat)255.0;
masks[2].mask = 0x0000ff;
masks[2].shiftin = 0;
masks[2].max_value= (gfloat)255.0;
masks[3].mask = 0x0;
masks[3].shiftin = 0;
masks[3].max_value= (gfloat)0.0;
break;
case 16:
masks[0].mask = 0x7c00;
masks[0].shiftin = 10;
masks[0].max_value= (gfloat)31.0;
masks[1].mask = 0x03e0;
masks[1].shiftin = 5;
masks[1].max_value= (gfloat)31.0;
masks[2].mask = 0x001f;
masks[2].shiftin = 0;
masks[2].max_value= (gfloat)31.0;
masks[3].mask = 0x0;
masks[3].shiftin = 0;
masks[3].max_value= (gfloat)0.0;
break;
default:
break;
}
}
else if (Bitmap_File_Head.biSize >= 56 && Bitmap_File_Head.biSize <= 64)
/* enhanced Windows format with bit masks */
{
if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error reading BMP file header from '%s'"),
gimp_filename_to_utf8 (filename));
return -1;
}
Bitmap_Head.biWidth =ToL (&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight =ToL (&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes =ToS (&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt =ToS (&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr =ToL (&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm =ToL (&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels =ToL (&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels =ToL (&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed =ToL (&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp =ToL (&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] =ToL (&buffer[0x24]); /* 36 */
Bitmap_Head.masks[1] =ToL (&buffer[0x28]); /* 3A */
Bitmap_Head.masks[2] =ToL (&buffer[0x2C]); /* 3E */
Bitmap_Head.masks[3] =ToL (&buffer[0x30]); /* 42 */
Maps = 4;
ReadChannelMasks (&Bitmap_Head.masks[0], masks, 4);
}
else
{
GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(filename, NULL);
if (pixbuf)
{
gint32 layer_ID;
image_ID = gimp_image_new (gdk_pixbuf_get_width (pixbuf),
gdk_pixbuf_get_height (pixbuf),
GIMP_RGB);
layer_ID = gimp_layer_new_from_pixbuf (image_ID, _("Background"),
pixbuf,
100.,
GIMP_NORMAL_MODE, 0, 0);
g_object_unref (pixbuf);
gimp_image_set_filename (image_ID, filename);
gimp_image_add_layer (image_ID, layer_ID, -1);
return image_ID;
}
else
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error reading BMP file header from '%s'"),
gimp_filename_to_utf8 (filename));
return -1;
}
}
/* Valid bitpdepthis 1, 4, 8, 16, 24, 32 */
/* 16 is awful, we should probably shoot whoever invented it */
/* There should be some colors used! */
ColormapSize =
(Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;
if ((Bitmap_Head.biClrUsed == 0) && (Bitmap_Head.biBitCnt <= 8))
ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;
if (ColormapSize > 256)
ColormapSize = 256;
/* Sanity checks */
if (Bitmap_Head.biHeight == 0 || Bitmap_Head.biWidth == 0)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
if (Bitmap_Head.biWidth < 0)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
if (Bitmap_Head.biPlanes != 1)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
if (Bitmap_Head.biClrUsed > 256)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("'%s' is not a valid BMP file"),
gimp_filename_to_utf8 (filename));
return -1;
}
/* Windows and OS/2 declare filler so that rows are a multiple of
* word length (32 bits == 4 bytes)
*/
rowbytes= ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;
#ifdef DEBUG
printf ("\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, "
"Comp: %u, Zeile: %u\n",
Bitmap_File_Head.bfSize,
Bitmap_Head.biClrUsed,
Bitmap_Head.biBitCnt,
Bitmap_Head.biWidth,
Bitmap_Head.biHeight,
Bitmap_Head.biCompr,
rowbytes);
#endif
if (Bitmap_Head.biBitCnt <= 8)
{
#ifdef DEBUG
printf ("Colormap read\n");
#endif
/* Get the Colormap */
if (!ReadColorMap (fd, ColorMap, ColormapSize, Maps, &Grey))
return -1;
}
fseek (fd, Bitmap_File_Head.bfOffs, SEEK_SET);
/* Get the Image and return the ID or -1 on error*/
image_ID = ReadImage (fd,
Bitmap_Head.biWidth,
ABS (Bitmap_Head.biHeight),
ColorMap,
Bitmap_Head.biClrUsed,
Bitmap_Head.biBitCnt,
Bitmap_Head.biCompr,
rowbytes,
Grey,
masks,
error);
if (image_ID < 0)
return -1;
if (Bitmap_Head.biXPels > 0 && Bitmap_Head.biYPels > 0)
{
/* Fixed up from scott@asofyet's changes last year, njl195 */
gdouble xresolution;
gdouble yresolution;
/* I don't agree with scott's feeling that Gimp should be
* trying to "fix" metric resolution translations, in the
* long term Gimp should be SI (metric) anyway, but we
* haven't told the Americans that yet */
xresolution = Bitmap_Head.biXPels * 0.0254;
yresolution = Bitmap_Head.biYPels * 0.0254;
gimp_image_set_resolution (image_ID, xresolution, yresolution);
}
if (Bitmap_Head.biHeight < 0)
gimp_image_flip (image_ID, GIMP_ORIENTATION_VERTICAL);
return image_ID;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Harden the BMP plugin against integer overflows.
Issues discovered by Stefan Cornelius, Secunia Research, advisory SA37232
and CVE identifier CVE-2009-1570. Fixes bug #600484.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: nma_gconf_settings_new (void)
{
return (NMAGConfSettings *) g_object_new (NMA_TYPE_GCONF_SETTINGS, NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'editor: prevent any registration of objects on the system bus
D-Bus access-control is name-based; so requests for a specific name
are allowed/denied based on the rules in /etc/dbus-1/system.d. But
apparently apps still get a non-named service on the bus, and if we
register *any* object even though we don't have a named service,
dbus and dbus-glib will happily proxy signals. Since the connection
editor shouldn't ever expose anything having to do with connections
on any bus, make sure that's the 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: nma_gconf_connection_changed (NMAGConfConnection *self)
{
NMAGConfConnectionPrivate *priv;
GHashTable *settings;
NMConnection *wrapped_connection;
NMConnection *gconf_connection;
GHashTable *new_settings;
GError *error = NULL;
g_return_val_if_fail (NMA_IS_GCONF_CONNECTION (self), FALSE);
priv = NMA_GCONF_CONNECTION_GET_PRIVATE (self);
wrapped_connection = nm_exported_connection_get_connection (NM_EXPORTED_CONNECTION (self));
gconf_connection = nm_gconf_read_connection (priv->client, priv->dir);
if (!gconf_connection) {
g_warning ("No connection read from GConf at %s.", priv->dir);
goto invalid;
}
utils_fill_connection_certs (gconf_connection);
if (!nm_connection_verify (gconf_connection, &error)) {
utils_clear_filled_connection_certs (gconf_connection);
g_warning ("%s: Invalid connection %s: '%s' / '%s' invalid: %d",
__func__, priv->dir,
g_type_name (nm_connection_lookup_setting_type_by_quark (error->domain)),
error->message, error->code);
goto invalid;
}
utils_clear_filled_connection_certs (gconf_connection);
/* Ignore the GConf update if nothing changed */
if ( nm_connection_compare (wrapped_connection, gconf_connection, NM_SETTING_COMPARE_FLAG_EXACT)
&& nm_gconf_compare_private_connection_values (wrapped_connection, gconf_connection))
return TRUE;
/* Update private values to catch any certificate path changes */
nm_gconf_copy_private_connection_values (wrapped_connection, gconf_connection);
utils_fill_connection_certs (gconf_connection);
new_settings = nm_connection_to_hash (gconf_connection);
utils_clear_filled_connection_certs (gconf_connection);
if (!nm_connection_replace_settings (wrapped_connection, new_settings, &error)) {
utils_clear_filled_connection_certs (wrapped_connection);
g_hash_table_destroy (new_settings);
g_warning ("%s: '%s' / '%s' invalid: %d",
__func__,
error ? g_type_name (nm_connection_lookup_setting_type_by_quark (error->domain)) : "(none)",
(error && error->message) ? error->message : "(none)",
error ? error->code : -1);
goto invalid;
}
g_object_unref (gconf_connection);
g_hash_table_destroy (new_settings);
fill_vpn_user_name (wrapped_connection);
settings = nm_connection_to_hash (wrapped_connection);
utils_clear_filled_connection_certs (wrapped_connection);
nm_exported_connection_signal_updated (NM_EXPORTED_CONNECTION (self), settings);
g_hash_table_destroy (settings);
return TRUE;
invalid:
g_clear_error (&error);
nm_exported_connection_signal_removed (NM_EXPORTED_CONNECTION (self));
return FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793)
If a connection was created with a CA certificate, but the user later
moved or deleted that CA certificate, the applet would simply provide the
connection to NetworkManager without any CA certificate. This could cause
NM to connect to the original network (or a network spoofing the original
network) without verifying the identity of the network as the user
expects.
In the future we can/should do better here by (1) alerting the user that
some connection is now no longer complete by flagging it in the connection
editor or notifying the user somehow, and (2) by using a freaking' cert
store already (not that Linux has one yet).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: nm_gconf_read_connection (GConfClient *client,
const char *dir)
{
ReadFromGConfInfo info;
GSList *list;
GError *err = NULL;
list = gconf_client_all_dirs (client, dir, &err);
if (err) {
g_warning ("Error while reading connection: %s", err->message);
g_error_free (err);
return NULL;
}
if (!list) {
g_warning ("Invalid connection (empty)");
return NULL;
}
info.connection = nm_connection_new ();
info.client = client;
info.dir = dir;
info.dir_len = strlen (dir);
g_slist_foreach (list, read_one_setting, &info);
g_slist_free (list);
return info.connection;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793)
If a connection was created with a CA certificate, but the user later
moved or deleted that CA certificate, the applet would simply provide the
connection to NetworkManager without any CA certificate. This could cause
NM to connect to the original network (or a network spoofing the original
network) without verifying the identity of the network as the user
expects.
In the future we can/should do better here by (1) alerting the user that
some connection is now no longer complete by flagging it in the connection
editor or notifying the user somehow, and (2) by using a freaking' cert
store already (not that Linux has one yet).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: connection_struct *make_connection_snum(struct smbd_server_connection *sconn,
int snum, user_struct *vuser,
DATA_BLOB password,
const char *pdev,
NTSTATUS *pstatus)
{
connection_struct *conn;
struct smb_filename *smb_fname_cpath = NULL;
fstring dev;
int ret;
char addr[INET6_ADDRSTRLEN];
bool on_err_call_dis_hook = false;
NTSTATUS status;
fstrcpy(dev, pdev);
if (NT_STATUS_IS_ERR(*pstatus = share_sanity_checks(snum, dev))) {
return NULL;
}
conn = conn_new(sconn);
if (!conn) {
DEBUG(0,("Couldn't find free connection.\n"));
*pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
return NULL;
}
conn->params->service = snum;
status = create_connection_server_info(sconn,
conn, snum, vuser ? vuser->server_info : NULL, password,
&conn->server_info);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(1, ("create_connection_server_info failed: %s\n",
nt_errstr(status)));
*pstatus = status;
conn_free(conn);
return NULL;
}
if ((lp_guest_only(snum)) || (lp_security() == SEC_SHARE)) {
conn->force_user = true;
}
add_session_user(sconn, conn->server_info->unix_name);
safe_strcpy(conn->client_address,
client_addr(get_client_fd(),addr,sizeof(addr)),
sizeof(conn->client_address)-1);
conn->num_files_open = 0;
conn->lastused = conn->lastused_count = time(NULL);
conn->used = True;
conn->printer = (strncmp(dev,"LPT",3) == 0);
conn->ipc = ( (strncmp(dev,"IPC",3) == 0) ||
( lp_enable_asu_support() && strequal(dev,"ADMIN$")) );
/* Case options for the share. */
if (lp_casesensitive(snum) == Auto) {
/* We will be setting this per packet. Set to be case
* insensitive for now. */
conn->case_sensitive = False;
} else {
conn->case_sensitive = (bool)lp_casesensitive(snum);
}
conn->case_preserve = lp_preservecase(snum);
conn->short_case_preserve = lp_shortpreservecase(snum);
conn->encrypt_level = lp_smb_encrypt(snum);
conn->veto_list = NULL;
conn->hide_list = NULL;
conn->veto_oplock_list = NULL;
conn->aio_write_behind_list = NULL;
conn->read_only = lp_readonly(SNUM(conn));
conn->admin_user = False;
if (*lp_force_user(snum)) {
/*
* Replace conn->server_info with a completely faked up one
* from the username we are forced into :-)
*/
char *fuser;
struct auth_serversupplied_info *forced_serverinfo;
fuser = talloc_string_sub(conn, lp_force_user(snum), "%S",
lp_servicename(snum));
if (fuser == NULL) {
conn_free(conn);
*pstatus = NT_STATUS_NO_MEMORY;
return NULL;
}
status = make_serverinfo_from_username(
conn, fuser, conn->server_info->guest,
&forced_serverinfo);
if (!NT_STATUS_IS_OK(status)) {
conn_free(conn);
*pstatus = status;
return NULL;
}
TALLOC_FREE(conn->server_info);
conn->server_info = forced_serverinfo;
conn->force_user = True;
DEBUG(3,("Forced user %s\n", fuser));
}
/*
* If force group is true, then override
* any groupid stored for the connecting user.
*/
if (*lp_force_group(snum)) {
status = find_forced_group(
conn->force_user, snum, conn->server_info->unix_name,
&conn->server_info->ptok->user_sids[1],
&conn->server_info->utok.gid);
if (!NT_STATUS_IS_OK(status)) {
conn_free(conn);
*pstatus = status;
return NULL;
}
/*
* We need to cache this gid, to use within
* change_to_user() separately from the conn->server_info
* struct. We only use conn->server_info directly if
* "force_user" was set.
*/
conn->force_group_gid = conn->server_info->utok.gid;
}
conn->vuid = (vuser != NULL) ? vuser->vuid : UID_FIELD_INVALID;
{
char *s = talloc_sub_advanced(talloc_tos(),
lp_servicename(SNUM(conn)),
conn->server_info->unix_name,
conn->connectpath,
conn->server_info->utok.gid,
conn->server_info->sanitized_username,
pdb_get_domain(conn->server_info->sam_account),
lp_pathname(snum));
if (!s) {
conn_free(conn);
*pstatus = NT_STATUS_NO_MEMORY;
return NULL;
}
if (!set_conn_connectpath(conn,s)) {
TALLOC_FREE(s);
conn_free(conn);
*pstatus = NT_STATUS_NO_MEMORY;
return NULL;
}
DEBUG(3,("Connect path is '%s' for service [%s]\n",s,
lp_servicename(snum)));
TALLOC_FREE(s);
}
/*
* New code to check if there's a share security descripter
* added from NT server manager. This is done after the
* smb.conf checks are done as we need a uid and token. JRA.
*
*/
{
bool can_write = False;
can_write = share_access_check(conn->server_info->ptok,
lp_servicename(snum),
FILE_WRITE_DATA);
if (!can_write) {
if (!share_access_check(conn->server_info->ptok,
lp_servicename(snum),
FILE_READ_DATA)) {
/* No access, read or write. */
DEBUG(0,("make_connection: connection to %s "
"denied due to security "
"descriptor.\n",
lp_servicename(snum)));
conn_free(conn);
*pstatus = NT_STATUS_ACCESS_DENIED;
return NULL;
} else {
conn->read_only = True;
}
}
}
/* Initialise VFS function pointers */
if (!smbd_vfs_init(conn)) {
DEBUG(0, ("vfs_init failed for service %s\n",
lp_servicename(snum)));
conn_free(conn);
*pstatus = NT_STATUS_BAD_NETWORK_NAME;
return NULL;
}
/*
* If widelinks are disallowed we need to canonicalise the connect
* path here to ensure we don't have any symlinks in the
* connectpath. We will be checking all paths on this connection are
* below this directory. We must do this after the VFS init as we
* depend on the realpath() pointer in the vfs table. JRA.
*/
if (!lp_widelinks(snum)) {
if (!canonicalize_connect_path(conn)) {
DEBUG(0, ("canonicalize_connect_path failed "
"for service %s, path %s\n",
lp_servicename(snum),
conn->connectpath));
conn_free(conn);
*pstatus = NT_STATUS_BAD_NETWORK_NAME;
return NULL;
}
}
if ((!conn->printer) && (!conn->ipc)) {
conn->notify_ctx = notify_init(conn, server_id_self(),
smbd_messaging_context(),
smbd_event_context(),
conn);
}
/* ROOT Activities: */
/*
* Enforce the max connections parameter.
*/
if ((lp_max_connections(snum) > 0)
&& (count_current_connections(lp_servicename(SNUM(conn)), True) >=
lp_max_connections(snum))) {
DEBUG(1, ("Max connections (%d) exceeded for %s\n",
lp_max_connections(snum), lp_servicename(snum)));
conn_free(conn);
*pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
return NULL;
}
/*
* Get us an entry in the connections db
*/
if (!claim_connection(conn, lp_servicename(snum), 0)) {
DEBUG(1, ("Could not store connections entry\n"));
conn_free(conn);
*pstatus = NT_STATUS_INTERNAL_DB_ERROR;
return NULL;
}
/* Preexecs are done here as they might make the dir we are to ChDir
* to below */
/* execute any "root preexec = " line */
if (*lp_rootpreexec(snum)) {
char *cmd = talloc_sub_advanced(talloc_tos(),
lp_servicename(SNUM(conn)),
conn->server_info->unix_name,
conn->connectpath,
conn->server_info->utok.gid,
conn->server_info->sanitized_username,
pdb_get_domain(conn->server_info->sam_account),
lp_rootpreexec(snum));
DEBUG(5,("cmd=%s\n",cmd));
ret = smbrun(cmd,NULL);
TALLOC_FREE(cmd);
if (ret != 0 && lp_rootpreexec_close(snum)) {
DEBUG(1,("root preexec gave %d - failing "
"connection\n", ret));
yield_connection(conn, lp_servicename(snum));
conn_free(conn);
*pstatus = NT_STATUS_ACCESS_DENIED;
return NULL;
}
}
/* USER Activites: */
if (!change_to_user(conn, conn->vuid)) {
/* No point continuing if they fail the basic checks */
DEBUG(0,("Can't become connected user!\n"));
yield_connection(conn, lp_servicename(snum));
conn_free(conn);
*pstatus = NT_STATUS_LOGON_FAILURE;
return NULL;
}
/* Remember that a different vuid can connect later without these
* checks... */
/* Preexecs are done here as they might make the dir we are to ChDir
* to below */
/* execute any "preexec = " line */
if (*lp_preexec(snum)) {
char *cmd = talloc_sub_advanced(talloc_tos(),
lp_servicename(SNUM(conn)),
conn->server_info->unix_name,
conn->connectpath,
conn->server_info->utok.gid,
conn->server_info->sanitized_username,
pdb_get_domain(conn->server_info->sam_account),
lp_preexec(snum));
ret = smbrun(cmd,NULL);
TALLOC_FREE(cmd);
if (ret != 0 && lp_preexec_close(snum)) {
DEBUG(1,("preexec gave %d - failing connection\n",
ret));
*pstatus = NT_STATUS_ACCESS_DENIED;
goto err_root_exit;
}
}
#ifdef WITH_FAKE_KASERVER
if (lp_afs_share(snum)) {
afs_login(conn);
}
#endif
/* Add veto/hide lists */
if (!IS_IPC(conn) && !IS_PRINT(conn)) {
set_namearray( &conn->veto_list, lp_veto_files(snum));
set_namearray( &conn->hide_list, lp_hide_files(snum));
set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(snum));
set_namearray( &conn->aio_write_behind_list,
lp_aio_write_behind(snum));
}
/* Invoke VFS make connection hook - do this before the VFS_STAT call
to allow any filesystems needing user credentials to initialize
themselves. */
if (SMB_VFS_CONNECT(conn, lp_servicename(snum),
conn->server_info->unix_name) < 0) {
DEBUG(0,("make_connection: VFS make connection failed!\n"));
*pstatus = NT_STATUS_UNSUCCESSFUL;
goto err_root_exit;
}
/* Any error exit after here needs to call the disconnect hook. */
on_err_call_dis_hook = true;
status = create_synthetic_smb_fname(talloc_tos(), conn->connectpath,
NULL, NULL, &smb_fname_cpath);
if (!NT_STATUS_IS_OK(status)) {
*pstatus = status;
goto err_root_exit;
}
/* win2000 does not check the permissions on the directory
during the tree connect, instead relying on permission
check during individual operations. To match this behaviour
I have disabled this chdir check (tridge) */
/* the alternative is just to check the directory exists */
if ((ret = SMB_VFS_STAT(conn, smb_fname_cpath)) != 0 ||
!S_ISDIR(smb_fname_cpath->st.st_ex_mode)) {
if (ret == 0 && !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) {
DEBUG(0,("'%s' is not a directory, when connecting to "
"[%s]\n", conn->connectpath,
lp_servicename(snum)));
} else {
DEBUG(0,("'%s' does not exist or permission denied "
"when connecting to [%s] Error was %s\n",
conn->connectpath, lp_servicename(snum),
strerror(errno) ));
}
*pstatus = NT_STATUS_BAD_NETWORK_NAME;
goto err_root_exit;
}
string_set(&conn->origpath,conn->connectpath);
#if SOFTLINK_OPTIMISATION
/* resolve any soft links early if possible */
if (vfs_ChDir(conn,conn->connectpath) == 0) {
TALLOC_CTX *ctx = talloc_tos();
char *s = vfs_GetWd(ctx,s);
if (!s) {
*status = map_nt_error_from_unix(errno);
goto err_root_exit;
}
if (!set_conn_connectpath(conn,s)) {
*status = NT_STATUS_NO_MEMORY;
goto err_root_exit;
}
vfs_ChDir(conn,conn->connectpath);
}
#endif
/* Figure out the characteristics of the underlying filesystem. This
* assumes that all the filesystem mounted withing a share path have
* the same characteristics, which is likely but not guaranteed.
*/
conn->fs_capabilities = SMB_VFS_FS_CAPABILITIES(conn, &conn->ts_res);
/*
* Print out the 'connected as' stuff here as we need
* to know the effective uid and gid we will be using
* (at least initially).
*/
if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
dbgtext( "%s (%s) ", get_remote_machine_name(),
conn->client_address );
dbgtext( "%s", srv_is_signing_active(smbd_server_conn) ? "signed " : "");
dbgtext( "connect to service %s ", lp_servicename(snum) );
dbgtext( "initially as user %s ",
conn->server_info->unix_name );
dbgtext( "(uid=%d, gid=%d) ", (int)geteuid(), (int)getegid() );
dbgtext( "(pid %d)\n", (int)sys_getpid() );
}
/* we've finished with the user stuff - go back to root */
change_to_root_user();
return(conn);
err_root_exit:
TALLOC_FREE(smb_fname_cpath);
change_to_root_user();
if (on_err_call_dis_hook) {
/* Call VFS disconnect hook */
SMB_VFS_DISCONNECT(conn);
}
yield_connection(conn, lp_servicename(snum));
conn_free(conn);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'Fix bug 7104 - "wide links" and "unix extensions" are incompatible.
Change parameter "wide links" to default to "no".
Ensure "wide links = no" if "unix extensions = yes" on a share.
Fix man pages to refect this.
Remove "within share" checks for a UNIX symlink set - even if
widelinks = no. The server will not follow that link anyway.
Correct DEBUG message in check_reduced_name() to add missing "\n"
so it's really clear when a path is being denied as it's outside
the enclosing share path.
Jeremy.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: snd_seq_oss_open(struct file *file, int level)
{
int i, rc;
struct seq_oss_devinfo *dp;
dp = kzalloc(sizeof(*dp), GFP_KERNEL);
if (!dp) {
snd_printk(KERN_ERR "can't malloc device info\n");
return -ENOMEM;
}
debug_printk(("oss_open: dp = %p\n", dp));
dp->cseq = system_client;
dp->port = -1;
dp->queue = -1;
for (i = 0; i < SNDRV_SEQ_OSS_MAX_CLIENTS; i++) {
if (client_table[i] == NULL)
break;
}
dp->index = i;
if (i >= SNDRV_SEQ_OSS_MAX_CLIENTS) {
snd_printk(KERN_ERR "too many applications\n");
rc = -ENOMEM;
goto _error;
}
/* look up synth and midi devices */
snd_seq_oss_synth_setup(dp);
snd_seq_oss_midi_setup(dp);
if (dp->synth_opened == 0 && dp->max_mididev == 0) {
/* snd_printk(KERN_ERR "no device found\n"); */
rc = -ENODEV;
goto _error;
}
/* create port */
debug_printk(("create new port\n"));
rc = create_port(dp);
if (rc < 0) {
snd_printk(KERN_ERR "can't create port\n");
goto _error;
}
/* allocate queue */
debug_printk(("allocate queue\n"));
rc = alloc_seq_queue(dp);
if (rc < 0)
goto _error;
/* set address */
dp->addr.client = dp->cseq;
dp->addr.port = dp->port;
/*dp->addr.queue = dp->queue;*/
/*dp->addr.channel = 0;*/
dp->seq_mode = level;
/* set up file mode */
dp->file_mode = translate_mode(file);
/* initialize read queue */
debug_printk(("initialize read queue\n"));
if (is_read_mode(dp->file_mode)) {
dp->readq = snd_seq_oss_readq_new(dp, maxqlen);
if (!dp->readq) {
rc = -ENOMEM;
goto _error;
}
}
/* initialize write queue */
debug_printk(("initialize write queue\n"));
if (is_write_mode(dp->file_mode)) {
dp->writeq = snd_seq_oss_writeq_new(dp, maxqlen);
if (!dp->writeq) {
rc = -ENOMEM;
goto _error;
}
}
/* initialize timer */
debug_printk(("initialize timer\n"));
dp->timer = snd_seq_oss_timer_new(dp);
if (!dp->timer) {
snd_printk(KERN_ERR "can't alloc timer\n");
rc = -ENOMEM;
goto _error;
}
debug_printk(("timer initialized\n"));
/* set private data pointer */
file->private_data = dp;
/* set up for mode2 */
if (level == SNDRV_SEQ_OSS_MODE_MUSIC)
snd_seq_oss_synth_setup_midi(dp);
else if (is_read_mode(dp->file_mode))
snd_seq_oss_midi_open_all(dp, SNDRV_SEQ_OSS_FILE_READ);
client_table[dp->index] = dp;
num_clients++;
debug_printk(("open done\n"));
return 0;
_error:
snd_seq_oss_writeq_delete(dp->writeq);
snd_seq_oss_readq_delete(dp->readq);
snd_seq_oss_synth_cleanup(dp);
snd_seq_oss_midi_cleanup(dp);
delete_port(dp);
delete_seq_queue(dp->queue);
kfree(dp);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'ALSA: seq/oss - Fix double-free at error path of snd_seq_oss_open()
The error handling in snd_seq_oss_open() has several bad codes that
do dereferecing released pointers and double-free of kmalloc'ed data.
The object dp is release in free_devinfo() that is called via
private_free callback. The rest shouldn't touch this object any more.
The patch changes delete_port() to call kfree() in any case, and gets
rid of unnecessary calls of destructors in snd_seq_oss_open().
Fixes CVE-2010-3080.
Reported-and-tested-by: Tavis Ormandy <taviso@cmpxchg8b.com>
Cc: <stable@kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s> |
<s>[INST] Given the following code containing errors, provide 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 u16 kvm_read_fs(void)
{
u16 seg;
asm("mov %%fs, %0" : "=g"(seg));
return seg;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt
kvm reloads the host's fs and gs blindly, however the underlying segment
descriptors may be invalid due to the user modifying the ldt after loading
them.
Fix by using the safe accessors (loadsegment() and load_gs_index()) instead
of home grown unsafe versions.
This is CVE-2010-3698.
KVM-Stable-Tag.
Signed-off-by: Avi Kivity <avi@redhat.com>
Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide 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 packet_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
if (peer)
return -EOPNOTSUPP;
sll->sll_family = AF_PACKET;
sll->sll_ifindex = po->ifindex;
sll->sll_protocol = po->num;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
if (dev) {
sll->sll_hatype = dev->type;
sll->sll_halen = dev->addr_len;
memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
} else {
sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
sll->sll_halen = 0;
}
rcu_read_unlock();
*uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-909'], 'message': 'net: packet: fix information leak to userland
packet_getname_spkt() doesn't initialize all members of sa_data field of
sockaddr struct if strlen(dev->name) < 13. This structure is then copied
to userland. It leads to leaking of contents of kernel stack memory.
We have to fully fill sa_data with strncpy() instead of strlcpy().
The same with packet_getname(): it doesn't initialize sll_pkttype field of
sockaddr_ll. Set it to zero.
Signed-off-by: Vasiliy Kulikov <segooon@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 __must_check int sk_add_backlog(struct sock *sk, struct sk_buff *skb)
{
if (sk->sk_backlog.len >= max(sk->sk_backlog.limit, sk->sk_rcvbuf << 1))
return -ENOBUFS;
__sk_add_backlog(sk, skb);
sk->sk_backlog.len += skb->truesize;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account
Current socket backlog limit is not enough to really stop DDOS attacks,
because user thread spend many time to process a full backlog each
round, and user might crazy spin on socket lock.
We should add backlog size and receive_queue size (aka rmem_alloc) to
pace writers, and let user run without being slow down too much.
Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in
stress situations.
Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp
receiver can now process ~200.000 pps (instead of ~100 pps before the
patch) on a 8 core machine.
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 tfm_load_file(const char *filename, TFMInfo *info)
{
int lf, lh, bc, ec, nw, nh, nd, ne;
int i, n;
Uchar *tfm;
Uchar *ptr;
struct stat st;
int size;
FILE *in;
Int32 *cb;
Int32 *charinfo;
Int32 *widths;
Int32 *heights;
Int32 *depths;
Uint32 checksum;
in = fopen(filename, "rb");
if(in == NULL)
return -1;
tfm = NULL;
DEBUG((DBG_FONTS, "(mt) reading TFM file `%s'\n",
filename));
/* We read the entire TFM file into core */
if(fstat(fileno(in), &st) < 0)
return -1;
if(st.st_size == 0)
goto bad_tfm;
/* allocate a word-aligned buffer to hold the file */
size = 4 * ROUND(st.st_size, 4);
if(size != st.st_size)
mdvi_warning(_("Warning: TFM file `%s' has suspicious size\n"),
filename);
tfm = (Uchar *)mdvi_malloc(size);
if(fread(tfm, st.st_size, 1, in) != 1)
goto error;
/* we don't need this anymore */
fclose(in);
in = NULL;
/* not a checksum, but serves a similar purpose */
checksum = 0;
ptr = tfm;
/* get the counters */
lf = muget2(ptr);
lh = muget2(ptr); checksum += 6 + lh;
bc = muget2(ptr);
ec = muget2(ptr); checksum += ec - bc + 1;
nw = muget2(ptr); checksum += nw;
nh = muget2(ptr); checksum += nh;
nd = muget2(ptr); checksum += nd;
checksum += muget2(ptr); /* skip italics correction count */
checksum += muget2(ptr); /* skip lig/kern table size */
checksum += muget2(ptr); /* skip kern table size */
ne = muget2(ptr); checksum += ne;
checksum += muget2(ptr); /* skip # of font parameters */
size = ec - bc + 1;
cb = (Int32 *)tfm; cb += 6 + lh;
charinfo = cb; cb += size;
widths = cb; cb += nw;
heights = cb; cb += nh;
depths = cb;
if(widths[0] || heights[0] || depths[0] ||
checksum != lf || bc - 1 > ec || ec > 255 || ne > 256)
goto bad_tfm;
/* from this point on, no error checking is done */
/* now we're at the header */
/* get the checksum */
info->checksum = muget4(ptr);
/* get the design size */
info->design = muget4(ptr);
/* get the coding scheme */
if(lh > 2) {
/* get the coding scheme */
i = n = msget1(ptr);
if(n < 0 || n > 39) {
mdvi_warning(_("%s: font coding scheme truncated to 40 bytes\n"),
filename);
n = 39;
}
memcpy(info->coding, ptr, n);
info->coding[n] = 0;
ptr += i;
} else
strcpy(info->coding, "FontSpecific");
/* get the font family */
if(lh > 12) {
n = msget1(ptr);
if(n > 0) {
i = Max(n, 63);
memcpy(info->family, ptr, i);
info->family[i] = 0;
} else
strcpy(info->family, "unspecified");
ptr += n;
}
/* now we don't read from `ptr' anymore */
info->loc = bc;
info->hic = ec;
info->type = DviFontTFM;
/* allocate characters */
info->chars = xnalloc(TFMChar, size);
#ifdef WORD_LITTLE_ENDIAN
/* byte-swap the three arrays at once (they are consecutive in memory) */
swap_array((Uint32 *)widths, nw + nh + nd);
#endif
/* get the relevant data */
ptr = (Uchar *)charinfo;
for(i = bc; i <= ec; ptr += 3, i++) {
int ndx;
ndx = (int)*ptr; ptr++;
info->chars[i-bc].advance = widths[ndx];
/* TFM files lack this information */
info->chars[i-bc].left = 0;
info->chars[i-bc].right = widths[ndx];
info->chars[i-bc].present = (ndx != 0);
if(ndx) {
ndx = ((*ptr >> 4) & 0xf);
info->chars[i-bc].height = heights[ndx];
ndx = (*ptr & 0xf);
info->chars[i-bc].depth = depths[ndx];
}
}
/* free everything */
mdvi_free(tfm);
return 0;
bad_tfm:
mdvi_error(_("%s: File corrupted, or not a TFM file\n"), filename);
error:
if(tfm) mdvi_free(tfm);
if(in) fclose(in);
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'backends: Fix several security issues in the dvi-backend.
See CVE-2010-2640, CVE-2010-2641, CVE-2010-2642 and CVE-2010-2643.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xfs_ioc_fsgeometry_v1(
xfs_mount_t *mp,
void __user *arg)
{
xfs_fsop_geom_v1_t fsgeo;
int error;
error = xfs_fs_geometry(mp, (xfs_fsop_geom_t *)&fsgeo, 3);
if (error)
return -error;
if (copy_to_user(arg, &fsgeo, sizeof(fsgeo)))
return -XFS_ERROR(EFAULT);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'xfs: zero proper structure size for geometry calls
Commit 493f3358cb289ccf716c5a14fa5bb52ab75943e5 added this call to
xfs_fs_geometry() in order to avoid passing kernel stack data back
to user space:
+ memset(geo, 0, sizeof(*geo));
Unfortunately, one of the callers of that function passes the
address of a smaller data type, cast to fit the type that
xfs_fs_geometry() requires. As a result, this can happen:
Kernel panic - not syncing: stack-protector: Kernel stack is corrupted
in: f87aca93
Pid: 262, comm: xfs_fsr Not tainted 2.6.38-rc6-493f3358cb2+ #1
Call Trace:
[<c12991ac>] ? panic+0x50/0x150
[<c102ed71>] ? __stack_chk_fail+0x10/0x18
[<f87aca93>] ? xfs_ioc_fsgeometry_v1+0x56/0x5d [xfs]
Fix this by fixing that one caller to pass the right type and then
copy out the subset it is interested in.
Note: This patch is an alternative to one originally proposed by
Eric Sandeen.
Reported-by: Jeffrey Hundstad <jeffrey.hundstad@mnsu.edu>
Signed-off-by: Alex Elder <aelder@sgi.com>
Reviewed-by: Eric Sandeen <sandeen@redhat.com>
Tested-by: Jeffrey Hundstad <jeffrey.hundstad@mnsu.edu>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: irc_server_gnutls_callback (void *data, gnutls_session_t tls_session,
const gnutls_datum_t *req_ca, int nreq,
const gnutls_pk_algorithm_t *pk_algos,
int pk_algos_len, gnutls_retr_st *answer)
{
struct t_irc_server *server;
gnutls_retr_st tls_struct;
gnutls_x509_crt_t cert_temp;
const gnutls_datum_t *cert_list;
gnutls_datum_t filedatum;
unsigned int cert_list_len, status;
time_t cert_time;
char *cert_path0, *cert_path1, *cert_path2, *cert_str, *hostname;
const char *weechat_dir;
int rc, ret, i, j, hostname_match;
#if LIBGNUTLS_VERSION_NUMBER >= 0x010706
gnutls_datum_t cinfo;
int rinfo;
#endif
/* make C compiler happy */
(void) req_ca;
(void) nreq;
(void) pk_algos;
(void) pk_algos_len;
rc = 0;
if (!data)
return -1;
server = (struct t_irc_server *) data;
hostname = server->current_address;
hostname_match = 0;
weechat_printf (server->buffer,
_("gnutls: connected using %d-bit Diffie-Hellman shared "
"secret exchange"),
IRC_SERVER_OPTION_INTEGER (server,
IRC_SERVER_OPTION_SSL_DHKEY_SIZE));
if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0)
{
weechat_printf (server->buffer,
_("%sgnutls: error while checking peer's certificate"),
weechat_prefix ("error"));
rc = -1;
}
else
{
/* some checks */
if (status & GNUTLS_CERT_INVALID)
{
weechat_printf (server->buffer,
_("%sgnutls: peer's certificate is NOT trusted"),
weechat_prefix ("error"));
rc = -1;
}
else
{
weechat_printf (server->buffer,
_("gnutls: peer's certificate is trusted"));
}
if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
{
weechat_printf (server->buffer,
_("%sgnutls: peer's certificate issuer is unknown"),
weechat_prefix ("error"));
rc = -1;
}
if (status & GNUTLS_CERT_REVOKED)
{
weechat_printf (server->buffer,
_("%sgnutls: the certificate has been revoked"),
weechat_prefix ("error"));
rc = -1;
}
/* check certificates */
if (gnutls_x509_crt_init (&cert_temp) >= 0)
{
cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len);
if (cert_list)
{
weechat_printf (server->buffer,
NG_("gnutls: receiving %d certificate",
"gnutls: receiving %d certificates",
cert_list_len),
cert_list_len);
for (i = 0, j = (int) cert_list_len; i < j; i++)
{
if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0)
{
/* checking if hostname matches in the first certificate */
if (i == 0 && gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0)
{
hostname_match = 1;
}
#if LIBGNUTLS_VERSION_NUMBER >= 0x010706
/* displaying infos about certificate */
#if LIBGNUTLS_VERSION_NUMBER < 0x020400
rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo);
#else
rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo);
#endif
if (rinfo == 0)
{
weechat_printf (server->buffer,
_(" - certificate[%d] info:"), i + 1);
weechat_printf (server->buffer,
" - %s", cinfo.data);
gnutls_free (cinfo.data);
}
#endif
/* check expiration date */
cert_time = gnutls_x509_crt_get_expiration_time (cert_temp);
if (cert_time < time(NULL))
{
weechat_printf (server->buffer,
_("%sgnutls: certificate has expired"),
weechat_prefix ("error"));
rc = -1;
}
/* check expiration date */
cert_time = gnutls_x509_crt_get_activation_time (cert_temp);
if (cert_time > time(NULL))
{
weechat_printf (server->buffer,
_("%sgnutls: certificate is not yet activated"),
weechat_prefix ("error"));
rc = -1;
}
}
}
if (hostname_match == 0)
{
weechat_printf (server->buffer,
_("%sgnutls: the hostname in the "
"certificate does NOT match \"%s\""),
weechat_prefix ("error"), hostname);
rc = -1;
}
}
}
}
/* using client certificate if it exists */
cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server,
IRC_SERVER_OPTION_SSL_CERT);
if (cert_path0 && cert_path0[0])
{
weechat_dir = weechat_info_get ("weechat_dir", "");
cert_path1 = weechat_string_replace (cert_path0, "%h", weechat_dir);
cert_path2 = (cert_path1) ?
weechat_string_expand_home (cert_path1) : NULL;
if (cert_path2)
{
cert_str = weechat_file_get_content (cert_path2);
if (cert_str)
{
weechat_printf (server->buffer,
_("gnutls: sending one certificate"));
filedatum.data = (unsigned char *) cert_str;
filedatum.size = strlen (cert_str);
/* certificate */
gnutls_x509_crt_init (&server->tls_cert);
gnutls_x509_crt_import (server->tls_cert, &filedatum,
GNUTLS_X509_FMT_PEM);
/* key */
gnutls_x509_privkey_init (&server->tls_cert_key);
ret = gnutls_x509_privkey_import (server->tls_cert_key,
&filedatum,
GNUTLS_X509_FMT_PEM);
if (ret < 0)
{
ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key,
&filedatum,
GNUTLS_X509_FMT_PEM,
NULL,
GNUTLS_PKCS_PLAIN);
}
if (ret < 0)
{
weechat_printf (server->buffer,
_("%sgnutls: invalid certificate \"%s\", "
"error: %s"),
weechat_prefix ("error"), cert_path2,
gnutls_strerror (ret));
rc = -1;
}
else
{
tls_struct.type = GNUTLS_CRT_X509;
tls_struct.ncerts = 1;
tls_struct.deinit_all = 0;
tls_struct.cert.x509 = &server->tls_cert;
tls_struct.key.x509 = server->tls_cert_key;
#if LIBGNUTLS_VERSION_NUMBER >= 0x010706
/* client certificate info */
#if LIBGNUTLS_VERSION_NUMBER < 0x020400
rinfo = gnutls_x509_crt_print (server->tls_cert,
GNUTLS_X509_CRT_ONELINE,
&cinfo);
#else
rinfo = gnutls_x509_crt_print (server->tls_cert,
GNUTLS_CRT_PRINT_ONELINE,
&cinfo);
#endif
if (rinfo == 0)
{
weechat_printf (server->buffer,
_(" - client certificate info (%s):"),
cert_path2);
weechat_printf (server->buffer, " - %s", cinfo.data);
gnutls_free (cinfo.data);
}
#endif
memcpy (answer, &tls_struct, sizeof (gnutls_retr_st));
free (cert_str);
}
}
else
{
weechat_printf (server->buffer,
_("%sgnutls: unable to read certifcate \"%s\""),
weechat_prefix ("error"), cert_path2);
}
}
if (cert_path1)
free (cert_path1);
if (cert_path2)
free (cert_path2);
}
/* an error should stop the handshake unless the user doesn't care */
if ((rc == -1)
&& (IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_SSL_VERIFY) == 0))
{
rc = 0;
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix verification of SSL certificates by calling gnutls verify callback (patch #7459)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compat_do_replace(struct net *net, void __user *user, unsigned int len)
{
int ret;
struct compat_ip6t_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ip6t_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.size >= INT_MAX / num_possible_cpus())
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
/* choose the copy that is on our node/cpu */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(net, tmp.name, tmp.valid_hooks,
&newinfo, &loc_cpu_entry, tmp.size,
tmp.num_entries, tmp.hook_entry,
tmp.underflow);
if (ret != 0)
goto free_newinfo;
duprintf("compat_do_replace: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'ipv6: netfilter: ip6_tables: fix infoleak to userspace
Structures ip6t_replace, compat_ip6t_replace, and xt_get_revision are
copied from userspace. Fields of these structs that are
zero-terminated strings are not checked. When they are used as argument
to a format string containing "%s" in request_module(), some sensitive
information is leaked to userspace via argument of spawned modprobe
process.
The first bug was introduced before the git epoch; the second was
introduced in 3bc3fe5e (v2.6.25-rc1); the third is introduced by
6b7d31fc (v2.6.15-rc1). To trigger the bug one should have
CAP_NET_ADMIN.
Signed-off-by: Vasiliy Kulikov <segoon@openwall.com>
Signed-off-by: Patrick McHardy <kaber@trash.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: batchInit(batch_t *pBatch, int maxElem) {
DEFiRet;
pBatch->maxElem = maxElem;
CHKmalloc(pBatch->pElem = calloc((size_t)maxElem, sizeof(batch_obj_t)));
// TODO: replace calloc by inidividual writes?
finalize_it:
RETiRet;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'bugfix: fixed a memory leak and potential abort condition
this could happen if multiple rulesets were used and some output batches
contained messages belonging to more than one ruleset.
fixes: http://bugzilla.adiscon.com/show_bug.cgi?id=226
fixes: http://bugzilla.adiscon.com/show_bug.cgi?id=218'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mono_runtime_shutdown (void)
{
mono_domain_foreach (fire_process_exit_event, NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods.
* reflection.c: Use a reference queue to cleanup
dynamic methods instead of finalization.
* runtime.c: Shutdown the dynamic method queue
before runtime cleanup begins.
* DynamicMethod.cs: No longer finalizable.
* icall-def.h: Remove unused dynamic method icall.
Fixes #660422'</s> |
<s>[INST] Given the following code containing errors, provide 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 agp_generic_insert_memory(struct agp_memory * mem, off_t pg_start, int type)
{
int num_entries;
size_t i;
off_t j;
void *temp;
struct agp_bridge_data *bridge;
int mask_type;
bridge = mem->bridge;
if (!bridge)
return -EINVAL;
if (mem->page_count == 0)
return 0;
temp = bridge->current_size;
switch (bridge->driver->size_type) {
case U8_APER_SIZE:
num_entries = A_SIZE_8(temp)->num_entries;
break;
case U16_APER_SIZE:
num_entries = A_SIZE_16(temp)->num_entries;
break;
case U32_APER_SIZE:
num_entries = A_SIZE_32(temp)->num_entries;
break;
case FIXED_APER_SIZE:
num_entries = A_SIZE_FIX(temp)->num_entries;
break;
case LVL2_APER_SIZE:
/* The generic routines can't deal with 2 level gatt's */
return -EINVAL;
break;
default:
num_entries = 0;
break;
}
num_entries -= agp_memory_reserved/PAGE_SIZE;
if (num_entries < 0) num_entries = 0;
if (type != mem->type)
return -EINVAL;
mask_type = bridge->driver->agp_type_to_mask_type(bridge, type);
if (mask_type != 0) {
/* The generic routines know nothing of memory types */
return -EINVAL;
}
/* AK: could wrap */
if ((pg_start + mem->page_count) > num_entries)
return -EINVAL;
j = pg_start;
while (j < (pg_start + mem->page_count)) {
if (!PGE_EMPTY(bridge, readl(bridge->gatt_table+j)))
return -EBUSY;
j++;
}
if (!mem->is_flushed) {
bridge->driver->cache_flush();
mem->is_flushed = true;
}
for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
writel(bridge->driver->mask_memory(bridge,
page_to_phys(mem->pages[i]),
mask_type),
bridge->gatt_table+j);
}
readl(bridge->gatt_table+j-1); /* PCI Posting. */
bridge->driver->tlb_flush(mem);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'agp: fix arbitrary kernel memory writes
pg_start is copied from userspace on AGPIOC_BIND and AGPIOC_UNBIND ioctl
cmds of agp_ioctl() and passed to agpioc_bind_wrap(). As said in the
comment, (pg_start + mem->page_count) may wrap in case of AGPIOC_BIND,
and it is not checked at all in case of AGPIOC_UNBIND. As a result, user
with sufficient privileges (usually "video" group) may generate either
local DoS or privilege escalation.
Signed-off-by: Vasiliy Kulikov <segoon@openwall.com>
Signed-off-by: Dave Airlie <airlied@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_NPN_GetValue(NPP instance, NPNVariable variable, void *value)
{
D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable)));
if (!thread_check()) {
npw_printf("WARNING: NPN_GetValue not called from the main thread\n");
return NPERR_INVALID_INSTANCE_ERROR;
}
PluginInstance *plugin = NULL;
if (instance)
plugin = PLUGIN_INSTANCE(instance);
switch (variable) {
case NPNVxDisplay:
*(void **)value = x_display;
break;
case NPNVxtAppContext:
*(void **)value = XtDisplayToApplicationContext(x_display);
break;
case NPNVToolkit:
*(NPNToolkitType *)value = NPW_TOOLKIT;
break;
#if USE_XPCOM
case NPNVserviceManager: {
nsIServiceManager *sm;
int ret = NS_GetServiceManager(&sm);
if (NS_FAILED(ret)) {
npw_printf("WARNING: NS_GetServiceManager failed\n");
return NPERR_GENERIC_ERROR;
}
*(nsIServiceManager **)value = sm;
break;
}
case NPNVDOMWindow:
case NPNVDOMElement:
npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable));
return NPERR_INVALID_PARAM;
#endif
case NPNVnetscapeWindow:
if (plugin == NULL) {
npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n");
return NPERR_INVALID_INSTANCE_ERROR;
}
if (plugin->browser_toplevel == NULL) {
GdkNativeWindow netscape_xid = None;
NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid);
if (error != NPERR_NO_ERROR)
return error;
if (netscape_xid == None)
return NPERR_GENERIC_ERROR;
plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid);
if (plugin->browser_toplevel == NULL)
return NPERR_GENERIC_ERROR;
}
*((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel);
break;
#if ALLOW_WINDOWLESS_PLUGINS
case NPNVSupportsWindowless:
#endif
case NPNVSupportsXEmbedBool:
case NPNVWindowNPObject:
case NPNVPluginElementNPObject:
return g_NPN_GetValue_real(instance, variable, value);
default:
switch (variable & 0xff) {
case 13: /* NPNVToolkit */
if (NPW_TOOLKIT == NPNVGtk2) {
// Gtk2 does not need to depend on a specific C++ ABI
*(NPNToolkitType *)value = NPW_TOOLKIT;
return NPERR_NO_ERROR;
}
break;
}
D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable)));
return NPERR_INVALID_PARAM;
}
return NPERR_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Support all the new variables added'</s> |
<s>[INST] Given the following code containing errors, provide 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_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) == -1 ||
check_newline(progname, dir) == -1)
return EX_USAGE;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'mount.cifs: check_newline returns EX_USAGE on error, not -1
Reported-by: Jan Lieskovsky <jlieskov@redhat.com>
Signed-off-by: Jeff Layton <jlayton@samba.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gdk_pixbuf__tiff_fill_vtable (GdkPixbufModule *module)
{
module->load = gdk_pixbuf__tiff_image_load;
module->begin_load = gdk_pixbuf__tiff_image_begin_load;
module->stop_load = gdk_pixbuf__tiff_image_stop_load;
module->load_increment = gdk_pixbuf__tiff_image_load_increment;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work.
Fri Jun 1 18:54:47 2001 Jonathan Blandford <jrb@redhat.com>
* gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at
getting the focus code to work.
(gtk_tree_view_class_init): Add a bunch of keybindings.
* gtk/gtktreeviewcolumn.c
(gtk_tree_view_column_set_cell_data_func):
s/GtkCellDataFunc/GtkTreeCellDataFunc.
(_gtk_tree_view_column_set_tree_view): Use "notify::model" instead
of "properties_changed" to help justify the death of the latter
signal. (-:
* tests/testtreefocus.c (main): Let some columns be focussable to
test focus better.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gif_prepare_lzw (GifContext *context)
{
gint i;
if (!gif_read (context, &(context->lzw_set_code_size), 1)) {
/*g_message (_("GIF: EOF / read error on image data\n"));*/
return -1;
}
context->lzw_code_size = context->lzw_set_code_size + 1;
context->lzw_clear_code = 1 << context->lzw_set_code_size;
context->lzw_end_code = context->lzw_clear_code + 1;
context->lzw_max_code_size = 2 * context->lzw_clear_code;
context->lzw_max_code = context->lzw_clear_code + 2;
context->lzw_fresh = TRUE;
context->code_curbit = 0;
context->code_lastbit = 0;
context->code_last_byte = 0;
context->code_done = FALSE;
for (i = 0; i < context->lzw_clear_code; ++i) {
context->lzw_table[0][i] = 0;
context->lzw_table[1][i] = i;
}
for (; i < (1 << MAX_LZW_BITS); ++i)
context->lzw_table[0][i] = context->lzw_table[1][0] = 0;
context->lzw_sp = context->lzw_stack;
gif_set_get_lzw (context);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work.
Fri Jun 1 18:54:47 2001 Jonathan Blandford <jrb@redhat.com>
* gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at
getting the focus code to work.
(gtk_tree_view_class_init): Add a bunch of keybindings.
* gtk/gtktreeviewcolumn.c
(gtk_tree_view_column_set_cell_data_func):
s/GtkCellDataFunc/GtkTreeCellDataFunc.
(_gtk_tree_view_column_set_tree_view): Use "notify::model" instead
of "properties_changed" to help justify the death of the latter
signal. (-:
* tests/testtreefocus.c (main): Let some columns be focussable to
test focus better.'</s> |
<s>[INST] Given the following code containing errors, provide 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 unsigned long do_div_llr(const long long dividend,
const long divisor, long *remainder)
{
u64 result = dividend;
*(remainder) = do_div(result, divisor);
return (unsigned long) result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <zippel@linux-m68k.org>
Cc: Ralf Baechle <ralf@linux-mips.org>
Cc: Ingo Molnar <mingo@elte.hu>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: john stultz <johnstul@us.ibm.com>
Cc: Christoph Lameter <clameter@sgi.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 list_locations(struct kmem_cache *s, char *buf,
enum track_item alloc)
{
int len = 0;
unsigned long i;
struct loc_track t = { 0, 0, NULL };
int node;
if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
GFP_TEMPORARY))
return sprintf(buf, "Out of memory\n");
/* Push back cpu slabs */
flush_all(s);
for_each_node_state(node, N_NORMAL_MEMORY) {
struct kmem_cache_node *n = get_node(s, node);
unsigned long flags;
struct page *page;
if (!atomic_long_read(&n->nr_slabs))
continue;
spin_lock_irqsave(&n->list_lock, flags);
list_for_each_entry(page, &n->partial, lru)
process_slab(&t, s, page, alloc);
list_for_each_entry(page, &n->full, lru)
process_slab(&t, s, page, alloc);
spin_unlock_irqrestore(&n->list_lock, flags);
}
for (i = 0; i < t.count; i++) {
struct location *l = &t.loc[i];
if (len > PAGE_SIZE - 100)
break;
len += sprintf(buf + len, "%7ld ", l->count);
if (l->addr)
len += sprint_symbol(buf + len, (unsigned long)l->addr);
else
len += sprintf(buf + len, "<not-available>");
if (l->sum_time != l->min_time) {
unsigned long remainder;
len += sprintf(buf + len, " age=%ld/%ld/%ld",
l->min_time,
div_long_long_rem(l->sum_time, l->count, &remainder),
l->max_time);
} else
len += sprintf(buf + len, " age=%ld",
l->min_time);
if (l->min_pid != l->max_pid)
len += sprintf(buf + len, " pid=%ld-%ld",
l->min_pid, l->max_pid);
else
len += sprintf(buf + len, " pid=%ld",
l->min_pid);
if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " cpus=");
len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->cpus);
}
if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " nodes=");
len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->nodes);
}
len += sprintf(buf + len, "\n");
}
free_loc_track(&t);
if (!t.count)
len += sprintf(buf, "No data\n");
return len;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <zippel@linux-m68k.org>
Cc: Ralf Baechle <ralf@linux-mips.org>
Cc: Ingo Molnar <mingo@elte.hu>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: john stultz <johnstul@us.ibm.com>
Cc: Christoph Lameter <clameter@sgi.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
n = r->sector_count;
if (n > SCSI_DMA_BUF_SIZE / 512)
n = SCSI_DMA_BUF_SIZE / 512;
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
r->iov.iov_len = n * 512;
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: commonize iovec creation between reads and writes
Also, consistently use qiov.size instead of iov.iov_len.
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide 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 fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_entry_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message
FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the
message processing could overrun and result in a "kernel BUG at
fs/fuse/dev.c:629!"
Reported-by: Han-Wen Nienhuys <hanwenn@gmail.com>
Signed-off-by: Miklos Szeredi <mszeredi@suse.cz>
CC: stable@kernel.org'</s> |
<s>[INST] Given the following code containing errors, provide 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 deliver_remote(message_data_t *msg, struct dest *dlist)
{
struct dest *d;
/* run the txns */
for (d = dlist; d; d = d->next) {
struct backend *be;
char buf[4096];
be = proxy_findserver(d->server, &nntp_protocol,
nntp_userid ? nntp_userid : "anonymous",
&backend_cached, &backend_current,
NULL, nntp_in);
if (!be) return IMAP_SERVER_UNAVAILABLE;
/* tell the backend about our new article */
prot_printf(be->out, "IHAVE %s\r\n", msg->id);
prot_flush(be->out);
if (!prot_fgets(buf, sizeof(buf), be->in) ||
strncmp("335", buf, 3)) {
syslog(LOG_NOTICE, "backend doesn't want article %s", msg->id);
continue;
}
/* send the article */
rewind(msg->f);
while (fgets(buf, sizeof(buf), msg->f)) {
if (buf[0] == '.') prot_putc('.', be->out);
do {
prot_printf(be->out, "%s", buf);
} while (buf[strlen(buf)-1] != '\n' &&
fgets(buf, sizeof(buf), msg->f));
}
/* Protect against messages not ending in CRLF */
if (buf[strlen(buf)-1] != '\n') prot_printf(be->out, "\r\n");
prot_printf(be->out, ".\r\n");
if (!prot_fgets(buf, sizeof(buf), be->in) ||
strncmp("235", buf, 3)) {
syslog(LOG_WARNING, "article %s transfer to backend failed",
msg->id);
return NNTP_FAIL_TRANSFER;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes
Discovered by Stefan Cornelius, Secunia Research
The vulnerability is caused due to the access restriction for certain
commands only checking whether or not variable "nntp_userid" is non-NULL,
without performing additional checks to verify that a complete, successful
authentication actually took place. The variable "nntp_userid" can be set to
point to a string holding the username (changing it to a non-NULL, thus
allowing attackers to bypass the checks) by sending an "AUTHINFO USER"
command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO
PASS" command is received. This can be exploited to bypass the
authentication mechanism and allows access to e.g. the "NEWNEWS" or the
"LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a
following "AUTHINFO PASS" command.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: process_ra(struct Interface *iface, unsigned char *msg, int len,
struct sockaddr_in6 *addr)
{
struct nd_router_advert *radvert;
char addr_str[INET6_ADDRSTRLEN];
uint8_t *opt_str;
print_addr(&addr->sin6_addr, addr_str);
radvert = (struct nd_router_advert *) msg;
if ((radvert->nd_ra_curhoplimit && iface->AdvCurHopLimit) &&
(radvert->nd_ra_curhoplimit != iface->AdvCurHopLimit))
{
flog(LOG_WARNING, "our AdvCurHopLimit on %s doesn't agree with %s",
iface->Name, addr_str);
}
if ((radvert->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED) && !iface->AdvManagedFlag)
{
flog(LOG_WARNING, "our AdvManagedFlag on %s doesn't agree with %s",
iface->Name, addr_str);
}
if ((radvert->nd_ra_flags_reserved & ND_RA_FLAG_OTHER) && !iface->AdvOtherConfigFlag)
{
flog(LOG_WARNING, "our AdvOtherConfigFlag on %s doesn't agree with %s",
iface->Name, addr_str);
}
/* note: we don't check the default router preference here, because they're likely different */
if ((radvert->nd_ra_reachable && iface->AdvReachableTime) &&
(ntohl(radvert->nd_ra_reachable) != iface->AdvReachableTime))
{
flog(LOG_WARNING, "our AdvReachableTime on %s doesn't agree with %s",
iface->Name, addr_str);
}
if ((radvert->nd_ra_retransmit && iface->AdvRetransTimer) &&
(ntohl(radvert->nd_ra_retransmit) != iface->AdvRetransTimer))
{
flog(LOG_WARNING, "our AdvRetransTimer on %s doesn't agree with %s",
iface->Name, addr_str);
}
len -= sizeof(struct nd_router_advert);
if (len == 0)
return;
opt_str = (uint8_t *)(msg + sizeof(struct nd_router_advert));
while (len > 0)
{
int optlen;
struct nd_opt_prefix_info *pinfo;
struct nd_opt_rdnss_info_local *rdnssinfo;
struct nd_opt_dnssl_info_local *dnsslinfo;
struct nd_opt_mtu *mtu;
struct AdvPrefix *prefix;
struct AdvRDNSS *rdnss;
char prefix_str[INET6_ADDRSTRLEN];
char rdnss_str[INET6_ADDRSTRLEN];
char suffix[256];
int offset, label_len;
uint32_t preferred, valid, count;
if (len < 2)
{
flog(LOG_ERR, "trailing garbage in RA on %s from %s",
iface->Name, addr_str);
break;
}
optlen = (opt_str[1] << 3);
if (optlen == 0)
{
flog(LOG_ERR, "zero length option in RA on %s from %s",
iface->Name, addr_str);
break;
}
else if (optlen > len)
{
flog(LOG_ERR, "option length greater than total"
" length in RA on %s from %s",
iface->Name, addr_str);
break;
}
switch (*opt_str)
{
case ND_OPT_MTU:
mtu = (struct nd_opt_mtu *)opt_str;
if (iface->AdvLinkMTU && (ntohl(mtu->nd_opt_mtu_mtu) != iface->AdvLinkMTU))
{
flog(LOG_WARNING, "our AdvLinkMTU on %s doesn't agree with %s",
iface->Name, addr_str);
}
break;
case ND_OPT_PREFIX_INFORMATION:
pinfo = (struct nd_opt_prefix_info *) opt_str;
preferred = ntohl(pinfo->nd_opt_pi_preferred_time);
valid = ntohl(pinfo->nd_opt_pi_valid_time);
prefix = iface->AdvPrefixList;
while (prefix)
{
if (prefix->enabled &&
(prefix->PrefixLen == pinfo->nd_opt_pi_prefix_len) &&
addr_match(&prefix->Prefix, &pinfo->nd_opt_pi_prefix,
prefix->PrefixLen))
{
print_addr(&prefix->Prefix, prefix_str);
if (!prefix->DecrementLifetimesFlag && valid != prefix->AdvValidLifetime)
{
flog(LOG_WARNING, "our AdvValidLifetime on"
" %s for %s doesn't agree with %s",
iface->Name,
prefix_str,
addr_str
);
}
if (!prefix->DecrementLifetimesFlag && preferred != prefix->AdvPreferredLifetime)
{
flog(LOG_WARNING, "our AdvPreferredLifetime on"
" %s for %s doesn't agree with %s",
iface->Name,
prefix_str,
addr_str
);
}
}
prefix = prefix->next;
}
break;
case ND_OPT_ROUTE_INFORMATION:
/* not checked: these will very likely vary a lot */
break;
case ND_OPT_SOURCE_LINKADDR:
/* not checked */
break;
case ND_OPT_TARGET_LINKADDR:
case ND_OPT_REDIRECTED_HEADER:
flog(LOG_ERR, "invalid option %d in RA on %s from %s",
(int)*opt_str, iface->Name, addr_str);
break;
/* Mobile IPv6 extensions */
case ND_OPT_RTR_ADV_INTERVAL:
case ND_OPT_HOME_AGENT_INFO:
/* not checked */
break;
case ND_OPT_RDNSS_INFORMATION:
rdnssinfo = (struct nd_opt_rdnss_info_local *) opt_str;
count = rdnssinfo->nd_opt_rdnssi_len;
/* Check the RNDSS addresses received */
switch (count) {
case 7:
rdnss = iface->AdvRDNSSList;
if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr3 )) {
/* no match found in iface->AdvRDNSSList */
print_addr(&rdnssinfo->nd_opt_rdnssi_addr3, rdnss_str);
flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us",
rdnss_str, iface->Name, addr_str);
}
/* FALLTHROUGH */
case 5:
rdnss = iface->AdvRDNSSList;
if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr2 )) {
/* no match found in iface->AdvRDNSSList */
print_addr(&rdnssinfo->nd_opt_rdnssi_addr2, rdnss_str);
flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us",
rdnss_str, iface->Name, addr_str);
}
/* FALLTHROUGH */
case 3:
rdnss = iface->AdvRDNSSList;
if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr1 )) {
/* no match found in iface->AdvRDNSSList */
print_addr(&rdnssinfo->nd_opt_rdnssi_addr1, rdnss_str);
flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us",
rdnss_str, iface->Name, addr_str);
}
break;
default:
flog(LOG_ERR, "invalid len %i in RDNSS option on %s from %s",
count, iface->Name, addr_str);
}
break;
case ND_OPT_DNSSL_INFORMATION:
dnsslinfo = (struct nd_opt_dnssl_info_local *) opt_str;
suffix[0] = '\0';
for (offset = 0; offset < (dnsslinfo->nd_opt_dnssli_len-1)*8;) {
label_len = dnsslinfo->nd_opt_dnssli_suffixes[offset++];
if (label_len == 0) {
/*
* Ignore empty suffixes. They're
* probably just padding...
*/
if (suffix[0] == '\0')
continue;
if (!check_dnssl_presence(iface->AdvDNSSLList, suffix)) {
flog(LOG_WARNING, "DNSSL suffix %s received on %s from %s is not advertised by us",
suffix, iface->Name, addr_str);
}
suffix[0] = '\0';
continue;
}
if ((sizeof(suffix) - strlen(suffix)) < (label_len + 2)) {
flog(LOG_ERR, "oversized suffix in DNSSL option on %s from %s",
iface->Name, addr_str);
break;
}
if (suffix[0] != '\0')
strcat(suffix, ".");
strncat(suffix, &dnsslinfo->nd_opt_dnssli_suffixes[offset], label_len);
offset += label_len;
}
break;
default:
dlog(LOG_DEBUG, 1, "unknown option %d in RA on %s from %s",
(int)*opt_str, iface->Name, addr_str);
break;
}
len -= optlen;
opt_str += optlen;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'In process_ra() ND_OPT_DNSSL_INFORMATION option parsing "label_len"
is not checked for negativeness; it leads to "suffix" buffer overflow,
which leads to privilege escalation (at least with -fno-stack-protector,
I didn't discover whether it's possible with -fstack-protector).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int cli_bytecode_runhook(cli_ctx *cctx, const struct cl_engine *engine, struct cli_bc_ctx *ctx,
unsigned id, fmap_t *map, const char **virname)
{
const unsigned *hooks = engine->hooks[id - _BC_START_HOOKS];
unsigned i, hooks_cnt = engine->hooks_cnt[id - _BC_START_HOOKS];
int ret;
unsigned executed = 0, breakflag = 0, errorflag = 0;
cli_dbgmsg("Bytecode executing hook id %u (%u hooks)\n", id, hooks_cnt);
/* restore match counts */
cli_bytecode_context_setfile(ctx, map);
ctx->hooks.match_counts = ctx->lsigcnt;
ctx->hooks.match_offsets = ctx->lsigoff;
for (i=0;i < hooks_cnt;i++) {
const struct cli_bc *bc = &engine->bcs.all_bcs[hooks[i]];
if (bc->lsig) {
if (!cctx->hook_lsig_matches ||
!cli_bitset_test(cctx->hook_lsig_matches, bc->hook_lsig_id-1))
continue;
cli_dbgmsg("Bytecode: executing bytecode %u (lsig matched)\n" , bc->id);
}
cli_bytecode_context_setfuncid(ctx, bc, 0);
ret = cli_bytecode_run(&engine->bcs, bc, ctx);
executed++;
if (ret != CL_SUCCESS) {
cli_warnmsg("Bytecode %u failed to run: %s\n", bc->id, cl_strerror(ret));
errorflag = 1;
continue;
}
if (ctx->virname) {
cli_dbgmsg("Bytecode found virus: %s\n", ctx->virname);
if (virname)
*virname = ctx->virname;
cli_bytecode_context_clear(ctx);
return CL_VIRUS;
}
ret = cli_bytecode_context_getresult_int(ctx);
/* TODO: use prefix here */
cli_dbgmsg("Bytecode %u returned %u\n", bc->id, ret);
if (ret == 0xcea5e) {
cli_dbgmsg("Bytecode set BREAK flag in hook!\n");
breakflag = 1;
}
if (!ret) {
char *tempfile;
int fd = cli_bytecode_context_getresult_file(ctx, &tempfile);
if (fd && fd != -1) {
if (cctx && cctx->engine->keeptmp)
cli_dbgmsg("Bytecode %u unpacked file saved in %s\n",
bc->id, tempfile);
else
cli_dbgmsg("Bytecode %u unpacked file\n", bc->id);
lseek(fd, 0, SEEK_SET);
cli_dbgmsg("***** Scanning unpacked file ******\n");
ret = cli_magic_scandesc(fd, cctx);
if (!cctx || !cctx->engine->keeptmp)
if (ftruncate(fd, 0) == -1)
cli_dbgmsg("ftruncate failed on %d\n", fd);
close(fd);
if (!cctx || !cctx->engine->keeptmp) {
if (tempfile && cli_unlink(tempfile))
ret = CL_EUNLINK;
}
free(tempfile);
if (ret != CL_CLEAN) {
if (ret == CL_VIRUS)
cli_dbgmsg("Scanning unpacked file by bytecode %u found a virus\n", bc->id);
cli_bytecode_context_clear(ctx);
return ret;
}
cli_bytecode_context_reset(ctx);
continue;
}
}
cli_bytecode_context_reset(ctx);
}
if (executed)
cli_dbgmsg("Bytecode: executed %u bytecodes for this hook\n", executed);
else
cli_dbgmsg("Bytecode: no logical signature matched, no bytecode executed\n");
if (errorflag && cctx && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST)
return CL_EBYTECODE_TESTFAIL;
return breakflag ? CL_BREAK : CL_CLEAN;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'fix recursion level crash (bb #3706).
Thanks to Stephane Chazelas for the analysis.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: command_process_create_cell(cell_t *cell, or_connection_t *conn)
{
or_circuit_t *circ;
int id_is_high;
if (we_are_hibernating()) {
log_info(LD_OR,
"Received create cell but we're shutting down. Sending back "
"destroy.");
connection_or_send_destroy(cell->circ_id, conn,
END_CIRC_REASON_HIBERNATING);
return;
}
if (!server_mode(get_options())) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received create cell (type %d) from %s:%d, but we're a client. "
"Sending back a destroy.",
(int)cell->command, conn->_base.address, conn->_base.port);
connection_or_send_destroy(cell->circ_id, conn,
END_CIRC_REASON_TORPROTOCOL);
return;
}
/* If the high bit of the circuit ID is not as expected, close the
* circ. */
id_is_high = cell->circ_id & (1<<15);
if ((id_is_high && conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ||
(!id_is_high && conn->circ_id_type == CIRC_ID_TYPE_LOWER)) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received create cell with unexpected circ_id %d. Closing.",
cell->circ_id);
connection_or_send_destroy(cell->circ_id, conn,
END_CIRC_REASON_TORPROTOCOL);
return;
}
if (circuit_id_in_use_on_orconn(cell->circ_id, conn)) {
routerinfo_t *router = router_get_by_digest(conn->identity_digest);
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received CREATE cell (circID %d) for known circ. "
"Dropping (age %d).",
cell->circ_id, (int)(time(NULL) - conn->_base.timestamp_created));
if (router)
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Details: nickname \"%s\", platform %s.",
router->nickname, escaped(router->platform));
return;
}
circ = or_circuit_new(cell->circ_id, conn);
circ->_base.purpose = CIRCUIT_PURPOSE_OR;
circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_ONIONSKIN_PENDING);
if (cell->command == CELL_CREATE) {
char *onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
memcpy(onionskin, cell->payload, ONIONSKIN_CHALLENGE_LEN);
/* hand it off to the cpuworkers, and then return. */
if (assign_onionskin_to_cpuworker(NULL, circ, onionskin) < 0) {
log_warn(LD_GENERAL,"Failed to hand off onionskin. Closing.");
circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
return;
}
log_debug(LD_OR,"success: handed off onionskin.");
} else {
/* This is a CREATE_FAST cell; we can handle it immediately without using
* a CPU worker. */
char keys[CPATH_KEY_MATERIAL_LEN];
char reply[DIGEST_LEN*2];
tor_assert(cell->command == CELL_CREATE_FAST);
/* Make sure we never try to use the OR connection on which we
* received this cell to satisfy an EXTEND request, */
conn->is_connection_with_client = 1;
if (fast_server_handshake(cell->payload, (uint8_t*)reply,
(uint8_t*)keys, sizeof(keys))<0) {
log_warn(LD_OR,"Failed to generate key material. Closing.");
circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
return;
}
if (onionskin_answer(circ, CELL_CREATED_FAST, reply, keys)<0) {
log_warn(LD_OR,"Failed to reply to CREATE_FAST cell. Closing.");
circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
return;
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Reject create cells on outgoing OR connections from bridges'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) {
int ret = 0;
int avail, tlen;
xmlChar cur, next;
const xmlChar *lastlt, *lastgt;
if (ctxt->input == NULL)
return(0);
#ifdef DEBUG_PUSH
switch (ctxt->instate) {
case XML_PARSER_EOF:
xmlGenericError(xmlGenericErrorContext,
"PP: try EOF\n"); break;
case XML_PARSER_START:
xmlGenericError(xmlGenericErrorContext,
"PP: try START\n"); break;
case XML_PARSER_MISC:
xmlGenericError(xmlGenericErrorContext,
"PP: try MISC\n");break;
case XML_PARSER_COMMENT:
xmlGenericError(xmlGenericErrorContext,
"PP: try COMMENT\n");break;
case XML_PARSER_PROLOG:
xmlGenericError(xmlGenericErrorContext,
"PP: try PROLOG\n");break;
case XML_PARSER_START_TAG:
xmlGenericError(xmlGenericErrorContext,
"PP: try START_TAG\n");break;
case XML_PARSER_CONTENT:
xmlGenericError(xmlGenericErrorContext,
"PP: try CONTENT\n");break;
case XML_PARSER_CDATA_SECTION:
xmlGenericError(xmlGenericErrorContext,
"PP: try CDATA_SECTION\n");break;
case XML_PARSER_END_TAG:
xmlGenericError(xmlGenericErrorContext,
"PP: try END_TAG\n");break;
case XML_PARSER_ENTITY_DECL:
xmlGenericError(xmlGenericErrorContext,
"PP: try ENTITY_DECL\n");break;
case XML_PARSER_ENTITY_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: try ENTITY_VALUE\n");break;
case XML_PARSER_ATTRIBUTE_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: try ATTRIBUTE_VALUE\n");break;
case XML_PARSER_DTD:
xmlGenericError(xmlGenericErrorContext,
"PP: try DTD\n");break;
case XML_PARSER_EPILOG:
xmlGenericError(xmlGenericErrorContext,
"PP: try EPILOG\n");break;
case XML_PARSER_PI:
xmlGenericError(xmlGenericErrorContext,
"PP: try PI\n");break;
case XML_PARSER_IGNORE:
xmlGenericError(xmlGenericErrorContext,
"PP: try IGNORE\n");break;
}
#endif
if ((ctxt->input != NULL) &&
(ctxt->input->cur - ctxt->input->base > 4096)) {
xmlSHRINK(ctxt);
ctxt->checkIndex = 0;
}
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
while (1) {
if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))
return(0);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if (ctxt->input == NULL) break;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else {
/*
* If we are operating on converted input, try to flush
* remainng chars to avoid them stalling in the non-converted
* buffer.
*/
if ((ctxt->input->buf->raw != NULL) &&
(ctxt->input->buf->raw->use > 0)) {
int base = ctxt->input->base -
ctxt->input->buf->buffer->content;
int current = ctxt->input->cur - ctxt->input->base;
xmlParserInputBufferPush(ctxt->input->buf, 0, "");
ctxt->input->base = ctxt->input->buf->buffer->content + base;
ctxt->input->cur = ctxt->input->base + current;
ctxt->input->end =
&ctxt->input->buf->buffer->content[
ctxt->input->buf->buffer->use];
}
avail = ctxt->input->buf->buffer->use -
(ctxt->input->cur - ctxt->input->base);
}
if (avail < 1)
goto done;
switch (ctxt->instate) {
case XML_PARSER_EOF:
/*
* Document parsing is done !
*/
goto done;
case XML_PARSER_START:
if (ctxt->charset == XML_CHAR_ENCODING_NONE) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* Very first chars read from the document flow.
*/
if (avail < 4)
goto done;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines,
* else xmlSwitchEncoding will set to (default)
* UTF8.
*/
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
xmlSwitchEncoding(ctxt, enc);
break;
}
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if (cur == 0) {
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
ctxt->instate = XML_PARSER_EOF;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering EOF\n");
#endif
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
if ((cur == '<') && (next == '?')) {
/* PI or XML decl */
if (avail < 5) return(ret);
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
return(ret);
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
if ((ctxt->input->cur[2] == 'x') &&
(ctxt->input->cur[3] == 'm') &&
(ctxt->input->cur[4] == 'l') &&
(IS_BLANK_CH(ctxt->input->cur[5]))) {
ret += 5;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing XML Decl\n");
#endif
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right
* here
*/
ctxt->instate = XML_PARSER_EOF;
return(0);
}
ctxt->standalone = ctxt->input->standalone;
if ((ctxt->encoding == NULL) &&
(ctxt->input->encoding != NULL))
ctxt->encoding = xmlStrdup(ctxt->input->encoding);
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
}
} else {
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
if (ctxt->version == NULL) {
xmlErrMemory(ctxt, NULL);
break;
}
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
}
break;
case XML_PARSER_START_TAG: {
const xmlChar *name;
const xmlChar *prefix = NULL;
const xmlChar *URI = NULL;
int nsNr = ctxt->nsNr;
if ((avail < 2) && (ctxt->inputNr == 1))
goto done;
cur = ctxt->input->cur[0];
if (cur != '<') {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
ctxt->instate = XML_PARSER_EOF;
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
if (!terminate) {
if (ctxt->progressive) {
/* > can be found unescaped in attribute values */
if ((lastgt == NULL) || (ctxt->input->cur >= lastgt))
goto done;
} else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) {
goto done;
}
}
if (ctxt->spaceNr == 0)
spacePush(ctxt, -1);
else if (*ctxt->space == -2)
spacePush(ctxt, -1);
else
spacePush(ctxt, *ctxt->space);
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax2)
#endif /* LIBXML_SAX1_ENABLED */
name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen);
#ifdef LIBXML_SAX1_ENABLED
else
name = xmlParseStartTag(ctxt);
#endif /* LIBXML_SAX1_ENABLED */
if (name == NULL) {
spacePop(ctxt);
ctxt->instate = XML_PARSER_EOF;
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
#ifdef LIBXML_VALID_ENABLED
/*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match
* the element type of the root element.
*/
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
ctxt->node && (ctxt->node == ctxt->myDoc->children))
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
#endif /* LIBXML_VALID_ENABLED */
/*
* Check for an Empty Element.
*/
if ((RAW == '/') && (NXT(1) == '>')) {
SKIP(2);
if (ctxt->sax2) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, name,
prefix, URI);
if (ctxt->nsNr - nsNr > 0)
nsPop(ctxt, ctxt->nsNr - nsNr);
#ifdef LIBXML_SAX1_ENABLED
} else {
if ((ctxt->sax != NULL) &&
(ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, name);
#endif /* LIBXML_SAX1_ENABLED */
}
spacePop(ctxt);
if (ctxt->nameNr == 0) {
ctxt->instate = XML_PARSER_EPILOG;
} else {
ctxt->instate = XML_PARSER_CONTENT;
}
break;
}
if (RAW == '>') {
NEXT;
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s\n",
name);
nodePop(ctxt);
spacePop(ctxt);
}
if (ctxt->sax2)
nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr);
#ifdef LIBXML_SAX1_ENABLED
else
namePush(ctxt, name);
#endif /* LIBXML_SAX1_ENABLED */
ctxt->instate = XML_PARSER_CONTENT;
break;
}
case XML_PARSER_CONTENT: {
const xmlChar *test;
unsigned int cons;
if ((avail < 2) && (ctxt->inputNr == 1))
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
test = CUR_PTR;
cons = ctxt->input->consumed;
if ((cur == '<') && (next == '/')) {
ctxt->instate = XML_PARSER_END_TAG;
break;
} else if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
xmlParsePI(ctxt);
} else if ((cur == '<') && (next != '!')) {
ctxt->instate = XML_PARSER_START_TAG;
break;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') &&
(ctxt->input->cur[3] == '-')) {
int term;
if (avail < 4)
goto done;
ctxt->input->cur += 4;
term = xmlParseLookupSequence(ctxt, '-', '-', '>');
ctxt->input->cur -= 4;
if ((!terminate) && (term < 0))
goto done;
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_CONTENT;
} else if ((cur == '<') && (ctxt->input->cur[1] == '!') &&
(ctxt->input->cur[2] == '[') &&
(ctxt->input->cur[3] == 'C') &&
(ctxt->input->cur[4] == 'D') &&
(ctxt->input->cur[5] == 'A') &&
(ctxt->input->cur[6] == 'T') &&
(ctxt->input->cur[7] == 'A') &&
(ctxt->input->cur[8] == '[')) {
SKIP(9);
ctxt->instate = XML_PARSER_CDATA_SECTION;
break;
} else if ((cur == '<') && (next == '!') &&
(avail < 9)) {
goto done;
} else if (cur == '&') {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, ';', 0, 0) < 0))
goto done;
xmlParseReference(ctxt);
} else {
/* TODO Avoid the extra copy, handle directly !!! */
/*
* Goal of the following test is:
* - minimize calls to the SAX 'character' callback
* when they are mergeable
* - handle an problem for isBlank when we only parse
* a sequence of blank chars and the next one is
* not available to check against '<' presence.
* - tries to homogenize the differences in SAX
* callbacks between the push and pull versions
* of the parser.
*/
if ((ctxt->inputNr == 1) &&
(avail < XML_PARSER_BIG_BUFFER_SIZE)) {
if (!terminate) {
if (ctxt->progressive) {
if ((lastlt == NULL) ||
(ctxt->input->cur > lastlt))
goto done;
} else if (xmlParseLookupSequence(ctxt,
'<', 0, 0) < 0) {
goto done;
}
}
}
ctxt->checkIndex = 0;
xmlParseCharData(ctxt, 0);
}
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"detected an error in element content\n");
ctxt->instate = XML_PARSER_EOF;
break;
}
break;
}
case XML_PARSER_END_TAG:
if (avail < 2)
goto done;
if (!terminate) {
if (ctxt->progressive) {
/* > can be found unescaped in attribute values */
if ((lastgt == NULL) || (ctxt->input->cur >= lastgt))
goto done;
} else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) {
goto done;
}
}
if (ctxt->sax2) {
xmlParseEndTag2(ctxt,
(void *) ctxt->pushTab[ctxt->nameNr * 3 - 3],
(void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0,
(int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0);
nameNsPop(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
else
xmlParseEndTag1(ctxt, 0);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->nameNr == 0) {
ctxt->instate = XML_PARSER_EPILOG;
} else {
ctxt->instate = XML_PARSER_CONTENT;
}
break;
case XML_PARSER_CDATA_SECTION: {
/*
* The Push mode need to have the SAX callback for
* cdataBlock merge back contiguous callbacks.
*/
int base;
base = xmlParseLookupSequence(ctxt, ']', ']', '>');
if (base < 0) {
if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) {
int tmp;
tmp = xmlCheckCdataPush(ctxt->input->cur,
XML_PARSER_BIG_BUFFER_SIZE);
if (tmp < 0) {
tmp = -tmp;
ctxt->input->cur += tmp;
goto encoding_error;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData,
ctxt->input->cur, tmp);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, tmp);
}
SKIPL(tmp);
ctxt->checkIndex = 0;
}
goto done;
} else {
int tmp;
tmp = xmlCheckCdataPush(ctxt->input->cur, base);
if ((tmp < 0) || (tmp != base)) {
tmp = -tmp;
ctxt->input->cur += tmp;
goto encoding_error;
}
if ((ctxt->sax != NULL) && (base == 0) &&
(ctxt->sax->cdataBlock != NULL) &&
(!ctxt->disableSAX)) {
/*
* Special case to provide identical behaviour
* between pull and push parsers on enpty CDATA
* sections
*/
if ((ctxt->input->cur - ctxt->input->base >= 9) &&
(!strncmp((const char *)&ctxt->input->cur[-9],
"<![CDATA[", 9)))
ctxt->sax->cdataBlock(ctxt->userData,
BAD_CAST "", 0);
} else if ((ctxt->sax != NULL) && (base > 0) &&
(!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData,
ctxt->input->cur, base);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, base);
}
SKIPL(base + 3);
ctxt->checkIndex = 0;
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
}
break;
}
case XML_PARSER_MISC:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else
avail = ctxt->input->buf->buffer->use -
(ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
ctxt->checkIndex = 0;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') &&
(ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_MISC;
ctxt->checkIndex = 0;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == 'D') &&
(ctxt->input->cur[3] == 'O') &&
(ctxt->input->cur[4] == 'C') &&
(ctxt->input->cur[5] == 'T') &&
(ctxt->input->cur[6] == 'Y') &&
(ctxt->input->cur[7] == 'P') &&
(ctxt->input->cur[8] == 'E')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '>', 0, 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing internal subset\n");
#endif
ctxt->inSubset = 1;
xmlParseDocTypeDecl(ctxt);
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
} else {
/*
* Create and update the external subset.
*/
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->externalSubset != NULL))
ctxt->sax->externalSubset(ctxt->userData,
ctxt->intSubName, ctxt->extSubSystem,
ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering PROLOG\n");
#endif
}
} else if ((cur == '<') && (next == '!') &&
(avail < 9)) {
goto done;
} else {
ctxt->instate = XML_PARSER_START_TAG;
ctxt->progressive = 1;
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
}
break;
case XML_PARSER_PROLOG:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base);
else
avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
} else if ((cur == '<') && (next == '!') &&
(avail < 4)) {
goto done;
} else {
ctxt->instate = XML_PARSER_START_TAG;
if (ctxt->progressive == 0)
ctxt->progressive = 1;
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
}
break;
case XML_PARSER_EPILOG:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base);
else
avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
ctxt->instate = XML_PARSER_EPILOG;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_EPILOG;
} else if ((cur == '<') && (next == '!') &&
(avail < 4)) {
goto done;
} else {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
ctxt->instate = XML_PARSER_EOF;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering EOF\n");
#endif
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
break;
case XML_PARSER_DTD: {
/*
* Sorry but progressive parsing of the internal subset
* is not expected to be supported. We first check that
* the full content of the internal subset is available and
* the parsing is launched only at that point.
* Internal subset ends up with "']' S? '>'" in an unescaped
* section and not in a ']]>' sequence which are conditional
* sections (whoever argued to keep that crap in XML deserve
* a place in hell !).
*/
int base, i;
xmlChar *buf;
xmlChar quote = 0;
base = ctxt->input->cur - ctxt->input->base;
if (base < 0) return(0);
if (ctxt->checkIndex > base)
base = ctxt->checkIndex;
buf = ctxt->input->buf->buffer->content;
for (;(unsigned int) base < ctxt->input->buf->buffer->use;
base++) {
if (quote != 0) {
if (buf[base] == quote)
quote = 0;
continue;
}
if ((quote == 0) && (buf[base] == '<')) {
int found = 0;
/* special handling of comments */
if (((unsigned int) base + 4 <
ctxt->input->buf->buffer->use) &&
(buf[base + 1] == '!') &&
(buf[base + 2] == '-') &&
(buf[base + 3] == '-')) {
for (;(unsigned int) base + 3 <
ctxt->input->buf->buffer->use; base++) {
if ((buf[base] == '-') &&
(buf[base + 1] == '-') &&
(buf[base + 2] == '>')) {
found = 1;
base += 2;
break;
}
}
if (!found) {
#if 0
fprintf(stderr, "unfinished comment\n");
#endif
break; /* for */
}
continue;
}
}
if (buf[base] == '"') {
quote = '"';
continue;
}
if (buf[base] == '\'') {
quote = '\'';
continue;
}
if (buf[base] == ']') {
#if 0
fprintf(stderr, "%c%c%c%c: ", buf[base],
buf[base + 1], buf[base + 2], buf[base + 3]);
#endif
if ((unsigned int) base +1 >=
ctxt->input->buf->buffer->use)
break;
if (buf[base + 1] == ']') {
/* conditional crap, skip both ']' ! */
base++;
continue;
}
for (i = 1;
(unsigned int) base + i < ctxt->input->buf->buffer->use;
i++) {
if (buf[base + i] == '>') {
#if 0
fprintf(stderr, "found\n");
#endif
goto found_end_int_subset;
}
if (!IS_BLANK_CH(buf[base + i])) {
#if 0
fprintf(stderr, "not found\n");
#endif
goto not_end_of_int_subset;
}
}
#if 0
fprintf(stderr, "end of stream\n");
#endif
break;
}
not_end_of_int_subset:
continue; /* for */
}
/*
* We didn't found the end of the Internal subset
*/
#ifdef DEBUG_PUSH
if (next == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup of int subset end filed\n");
#endif
goto done;
found_end_int_subset:
xmlParseInternalSubset(ctxt);
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->externalSubset != NULL))
ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
ctxt->extSubSystem, ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
ctxt->checkIndex = 0;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering PROLOG\n");
#endif
break;
}
case XML_PARSER_COMMENT:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == COMMENT\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
break;
case XML_PARSER_IGNORE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == IGNORE");
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_PI:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == PI\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
break;
case XML_PARSER_ENTITY_DECL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ENTITY_DECL\n");
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_ENTITY_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ENTITY_VALUE\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_ATTRIBUTE_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ATTRIBUTE_VALUE\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
case XML_PARSER_SYSTEM_LITERAL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == SYSTEM_LITERAL\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
case XML_PARSER_PUBLIC_LITERAL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == PUBLIC_LITERAL\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
}
}
done:
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret);
#endif
return(ret);
encoding_error:
{
char buffer[150];
snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
ctxt->input->cur[0], ctxt->input->cur[1],
ctxt->input->cur[2], ctxt->input->cur[3]);
__xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
"Input is not proper UTF-8, indicate encoding !\n%s",
BAD_CAST buffer, NULL);
}
return(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Make sure the parser returns when getting a Stop order
patch backported from chromiun bug fixes, assuming author is Chris'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlDictComputeFastKey(const xmlChar *name, int namelen) {
unsigned long value = 0L;
if (name == NULL) return(0);
value = *name;
value <<= 5;
if (namelen > 10) {
value += name[namelen - 1];
namelen = 10;
}
switch (namelen) {
case 10: value += name[9];
case 9: value += name[8];
case 8: value += name[7];
case 7: value += name[6];
case 6: value += name[5];
case 5: value += name[4];
case 4: value += name[3];
case 3: value += name[2];
case 2: value += name[1];
default: break;
}
return(value);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures
Following http://www.ocert.org/advisories/ocert-2011-003.html
it seems that having hash randomization might be a good idea
when using XML with untrusted data
* configure.in: lookup for rand, srand and time
* dict.c: add randomization to dictionaries hash tables
* hash.c: add randomization to normal hash tables'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xsltCompilePatternInternal(const xmlChar *pattern, xmlDocPtr doc,
xmlNodePtr node, xsltStylesheetPtr style,
xsltTransformContextPtr runtime, int novar) {
xsltParserContextPtr ctxt = NULL;
xsltCompMatchPtr element, first = NULL, previous = NULL;
int current, start, end, level, j;
if (pattern == NULL) {
xsltTransformError(NULL, NULL, node,
"xsltCompilePattern : NULL pattern\n");
return(NULL);
}
ctxt = xsltNewParserContext(style, runtime);
if (ctxt == NULL)
return(NULL);
ctxt->doc = doc;
ctxt->elem = node;
current = end = 0;
while (pattern[current] != 0) {
start = current;
while (IS_BLANK_CH(pattern[current]))
current++;
end = current;
level = 0;
while ((pattern[end] != 0) && ((pattern[end] != '|') || (level != 0))) {
if (pattern[end] == '[')
level++;
else if (pattern[end] == ']')
level--;
else if (pattern[end] == '\'') {
end++;
while ((pattern[end] != 0) && (pattern[end] != '\''))
end++;
} else if (pattern[end] == '"') {
end++;
while ((pattern[end] != 0) && (pattern[end] != '"'))
end++;
}
end++;
}
if (current == end) {
xsltTransformError(NULL, NULL, node,
"xsltCompilePattern : NULL pattern\n");
goto error;
}
element = xsltNewCompMatch();
if (element == NULL) {
goto error;
}
if (first == NULL)
first = element;
else if (previous != NULL)
previous->next = element;
previous = element;
ctxt->comp = element;
ctxt->base = xmlStrndup(&pattern[start], end - start);
if (ctxt->base == NULL)
goto error;
ctxt->cur = &(ctxt->base)[current - start];
element->pattern = ctxt->base;
element->nsList = xmlGetNsList(doc, node);
j = 0;
if (element->nsList != NULL) {
while (element->nsList[j] != NULL)
j++;
}
element->nsNr = j;
#ifdef WITH_XSLT_DEBUG_PATTERN
xsltGenericDebug(xsltGenericDebugContext,
"xsltCompilePattern : parsing '%s'\n",
element->pattern);
#endif
/*
Preset default priority to be zero.
This may be changed by xsltCompileLocationPathPattern.
*/
element->priority = 0;
xsltCompileLocationPathPattern(ctxt, novar);
if (ctxt->error) {
xsltTransformError(NULL, style, node,
"xsltCompilePattern : failed to compile '%s'\n",
element->pattern);
if (style != NULL) style->errors++;
goto error;
}
/*
* Reverse for faster interpretation.
*/
xsltReverseCompMatch(ctxt, element);
/*
* Set-up the priority
*/
if (element->priority == 0) { /* if not yet determined */
if (((element->steps[0].op == XSLT_OP_ELEM) ||
(element->steps[0].op == XSLT_OP_ATTR) ||
(element->steps[0].op == XSLT_OP_PI)) &&
(element->steps[0].value != NULL) &&
(element->steps[1].op == XSLT_OP_END)) {
; /* previously preset */
} else if ((element->steps[0].op == XSLT_OP_ATTR) &&
(element->steps[0].value2 != NULL) &&
(element->steps[1].op == XSLT_OP_END)) {
element->priority = -0.25;
} else if ((element->steps[0].op == XSLT_OP_NS) &&
(element->steps[0].value != NULL) &&
(element->steps[1].op == XSLT_OP_END)) {
element->priority = -0.25;
} else if ((element->steps[0].op == XSLT_OP_ATTR) &&
(element->steps[0].value == NULL) &&
(element->steps[0].value2 == NULL) &&
(element->steps[1].op == XSLT_OP_END)) {
element->priority = -0.5;
} else if (((element->steps[0].op == XSLT_OP_PI) ||
(element->steps[0].op == XSLT_OP_TEXT) ||
(element->steps[0].op == XSLT_OP_ALL) ||
(element->steps[0].op == XSLT_OP_NODE) ||
(element->steps[0].op == XSLT_OP_COMMENT)) &&
(element->steps[1].op == XSLT_OP_END)) {
element->priority = -0.5;
} else {
element->priority = 0.5;
}
}
#ifdef WITH_XSLT_DEBUG_PATTERN
xsltGenericDebug(xsltGenericDebugContext,
"xsltCompilePattern : parsed %s, default priority %f\n",
element->pattern, element->priority);
#endif
if (pattern[end] == '|')
end++;
current = end;
}
if (end == 0) {
xsltTransformError(NULL, style, node,
"xsltCompilePattern : NULL pattern\n");
if (style != NULL) style->errors++;
goto error;
}
xsltFreeParserContext(ctxt);
return(first);
error:
if (ctxt != NULL)
xsltFreeParserContext(ctxt);
if (first != NULL)
xsltFreeCompMatchList(first);
return(NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix some case of pattern parsing errors
We could accidentally hit an off by one string array access
due to improper loop exit when parsing patterns'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bgp_open_receive (struct peer *peer, bgp_size_t size)
{
int ret;
u_char version;
u_char optlen;
u_int16_t holdtime;
u_int16_t send_holdtime;
as_t remote_as;
as_t as4 = 0;
struct peer *realpeer;
struct in_addr remote_id;
int capability;
u_int8_t notify_data_remote_as[2];
u_int8_t notify_data_remote_id[4];
realpeer = NULL;
/* Parse open packet. */
version = stream_getc (peer->ibuf);
memcpy (notify_data_remote_as, stream_pnt (peer->ibuf), 2);
remote_as = stream_getw (peer->ibuf);
holdtime = stream_getw (peer->ibuf);
memcpy (notify_data_remote_id, stream_pnt (peer->ibuf), 4);
remote_id.s_addr = stream_get_ipv4 (peer->ibuf);
/* Receive OPEN message log */
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s rcv OPEN, version %d, remote-as (in open) %u,"
" holdtime %d, id %s",
peer->host, version, remote_as, holdtime,
inet_ntoa (remote_id));
/* BEGIN to read the capability here, but dont do it yet */
capability = 0;
optlen = stream_getc (peer->ibuf);
if (optlen != 0)
{
/* We need the as4 capability value *right now* because
* if it is there, we have not got the remote_as yet, and without
* that we do not know which peer is connecting to us now.
*/
as4 = peek_for_as4_capability (peer, optlen);
}
/* Just in case we have a silly peer who sends AS4 capability set to 0 */
if (CHECK_FLAG (peer->cap, PEER_CAP_AS4_RCV) && !as4)
{
zlog_err ("%s bad OPEN, got AS4 capability, but AS4 set to 0",
peer->host);
bgp_notify_send (peer, BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_PEER_AS);
return -1;
}
if (remote_as == BGP_AS_TRANS)
{
/* Take the AS4 from the capability. We must have received the
* capability now! Otherwise we have a asn16 peer who uses
* BGP_AS_TRANS, for some unknown reason.
*/
if (as4 == BGP_AS_TRANS)
{
zlog_err ("%s [AS4] NEW speaker using AS_TRANS for AS4, not allowed",
peer->host);
bgp_notify_send (peer, BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_PEER_AS);
return -1;
}
if (!as4 && BGP_DEBUG (as4, AS4))
zlog_debug ("%s [AS4] OPEN remote_as is AS_TRANS, but no AS4."
" Odd, but proceeding.", peer->host);
else if (as4 < BGP_AS_MAX && BGP_DEBUG (as4, AS4))
zlog_debug ("%s [AS4] OPEN remote_as is AS_TRANS, but AS4 (%u) fits "
"in 2-bytes, very odd peer.", peer->host, as4);
if (as4)
remote_as = as4;
}
else
{
/* We may have a partner with AS4 who has an asno < BGP_AS_MAX */
/* If we have got the capability, peer->as4cap must match remote_as */
if (CHECK_FLAG (peer->cap, PEER_CAP_AS4_RCV)
&& as4 != remote_as)
{
/* raise error, log this, close session */
zlog_err ("%s bad OPEN, got AS4 capability, but remote_as %u"
" mismatch with 16bit 'myasn' %u in open",
peer->host, as4, remote_as);
bgp_notify_send (peer, BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_PEER_AS);
return -1;
}
}
/* Lookup peer from Open packet. */
if (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER))
{
int as = 0;
realpeer = peer_lookup_with_open (&peer->su, remote_as, &remote_id, &as);
if (! realpeer)
{
/* Peer's source IP address is check in bgp_accept(), so this
must be AS number mismatch or remote-id configuration
mismatch. */
if (as)
{
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s bad OPEN, wrong router identifier %s",
peer->host, inet_ntoa (remote_id));
bgp_notify_send_with_data (peer, BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_BGP_IDENT,
notify_data_remote_id, 4);
}
else
{
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s bad OPEN, remote AS is %u, expected %u",
peer->host, remote_as, peer->as);
bgp_notify_send_with_data (peer, BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_PEER_AS,
notify_data_remote_as, 2);
}
return -1;
}
}
/* When collision is detected and this peer is closed. Retrun
immidiately. */
ret = bgp_collision_detect (peer, remote_id);
if (ret < 0)
return ret;
/* Hack part. */
if (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER))
{
if (realpeer->status == Established
&& CHECK_FLAG (realpeer->sflags, PEER_STATUS_NSF_MODE))
{
realpeer->last_reset = PEER_DOWN_NSF_CLOSE_SESSION;
SET_FLAG (realpeer->sflags, PEER_STATUS_NSF_WAIT);
}
else if (ret == 0 && realpeer->status != Active
&& realpeer->status != OpenSent
&& realpeer->status != OpenConfirm
&& realpeer->status != Connect)
{
/* XXX: This is an awful problem..
*
* According to the RFC we should just let this connection (of the
* accepted 'peer') continue on to Established if the other
* connection (the 'realpeer' one) is in state Connect, and deal
* with the more larval FSM as/when it gets far enough to receive
* an Open. We don't do that though, we instead close the (more
* developed) accepted connection.
*
* This means there's a race, which if hit, can loop:
*
* FSM for A FSM for B
* realpeer accept-peer realpeer accept-peer
*
* Connect Connect
* Active
* OpenSent OpenSent
* <arrive here,
* Notify, delete>
* Idle Active
* OpenSent OpenSent
* <arrive here,
* Notify, delete>
* Idle
* <wait> <wait>
* Connect Connect
*
*
* If both sides are Quagga, they're almost certain to wait for
* the same amount of time of course (which doesn't preclude other
* implementations also waiting for same time). The race is
* exacerbated by high-latency (in bgpd and/or the network).
*
* The reason we do this is because our FSM is tied to our peer
* structure, which carries our configuration information, etc.
* I.e. we can't let the accepted-peer FSM continue on as it is,
* cause it's not associated with any actual peer configuration -
* it's just a dummy.
*
* It's possible we could hack-fix this by just bgp_stop'ing the
* realpeer and continueing on with the 'transfer FSM' below.
* Ideally, we need to seperate FSMs from struct peer.
*
* Setting one side to passive avoids the race, as a workaround.
*/
if (BGP_DEBUG (events, EVENTS))
zlog_debug ("%s peer status is %s close connection",
realpeer->host, LOOKUP (bgp_status_msg,
realpeer->status));
bgp_notify_send (peer, BGP_NOTIFY_CEASE,
BGP_NOTIFY_CEASE_CONNECT_REJECT);
return -1;
}
if (BGP_DEBUG (events, EVENTS))
zlog_debug ("%s [Event] Transfer accept BGP peer to real (state %s)",
peer->host,
LOOKUP (bgp_status_msg, realpeer->status));
bgp_stop (realpeer);
/* Transfer file descriptor. */
realpeer->fd = peer->fd;
peer->fd = -1;
/* Transfer input buffer. */
stream_free (realpeer->ibuf);
realpeer->ibuf = peer->ibuf;
realpeer->packet_size = peer->packet_size;
peer->ibuf = NULL;
/* Transfer status. */
realpeer->status = peer->status;
bgp_stop (peer);
/* peer pointer change. Open packet send to neighbor. */
peer = realpeer;
bgp_open_send (peer);
if (peer->fd < 0)
{
zlog_err ("bgp_open_receive peer's fd is negative value %d",
peer->fd);
return -1;
}
BGP_READ_ON (peer->t_read, bgp_read, peer->fd);
}
/* remote router-id check. */
if (remote_id.s_addr == 0
|| IPV4_CLASS_DE (ntohl (remote_id.s_addr))
|| ntohl (peer->local_id.s_addr) == ntohl (remote_id.s_addr))
{
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s bad OPEN, wrong router identifier %s",
peer->host, inet_ntoa (remote_id));
bgp_notify_send_with_data (peer,
BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_BGP_IDENT,
notify_data_remote_id, 4);
return -1;
}
/* Set remote router-id */
peer->remote_id = remote_id;
/* Peer BGP version check. */
if (version != BGP_VERSION_4)
{
u_int8_t maxver = BGP_VERSION_4;
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s bad protocol version, remote requested %d, local request %d",
peer->host, version, BGP_VERSION_4);
bgp_notify_send_with_data (peer,
BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_UNSUP_VERSION,
&maxver, 1);
return -1;
}
/* Check neighbor as number. */
if (remote_as != peer->as)
{
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s bad OPEN, remote AS is %u, expected %u",
peer->host, remote_as, peer->as);
bgp_notify_send_with_data (peer,
BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_BAD_PEER_AS,
notify_data_remote_as, 2);
return -1;
}
/* From the rfc: Upon receipt of an OPEN message, a BGP speaker MUST
calculate the value of the Hold Timer by using the smaller of its
configured Hold Time and the Hold Time received in the OPEN message.
The Hold Time MUST be either zero or at least three seconds. An
implementation may reject connections on the basis of the Hold Time. */
if (holdtime < 3 && holdtime != 0)
{
bgp_notify_send (peer,
BGP_NOTIFY_OPEN_ERR,
BGP_NOTIFY_OPEN_UNACEP_HOLDTIME);
return -1;
}
/* From the rfc: A reasonable maximum time between KEEPALIVE messages
would be one third of the Hold Time interval. KEEPALIVE messages
MUST NOT be sent more frequently than one per second. An
implementation MAY adjust the rate at which it sends KEEPALIVE
messages as a function of the Hold Time interval. */
if (CHECK_FLAG (peer->config, PEER_CONFIG_TIMER))
send_holdtime = peer->holdtime;
else
send_holdtime = peer->bgp->default_holdtime;
if (holdtime < send_holdtime)
peer->v_holdtime = holdtime;
else
peer->v_holdtime = send_holdtime;
peer->v_keepalive = peer->v_holdtime / 3;
/* Open option part parse. */
if (optlen != 0)
{
ret = bgp_open_option_parse (peer, optlen, &capability);
if (ret < 0)
return ret;
}
else
{
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s rcvd OPEN w/ OPTION parameter len: 0",
peer->host);
}
/* Override capability. */
if (! capability || CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))
{
peer->afc_nego[AFI_IP][SAFI_UNICAST] = peer->afc[AFI_IP][SAFI_UNICAST];
peer->afc_nego[AFI_IP][SAFI_MULTICAST] = peer->afc[AFI_IP][SAFI_MULTICAST];
peer->afc_nego[AFI_IP6][SAFI_UNICAST] = peer->afc[AFI_IP6][SAFI_UNICAST];
peer->afc_nego[AFI_IP6][SAFI_MULTICAST] = peer->afc[AFI_IP6][SAFI_MULTICAST];
}
/* Get sockname. */
bgp_getsockname (peer);
BGP_EVENT_ADD (peer, Receive_OPEN_message);
peer->packet_size = 0;
if (peer->ibuf)
stream_reset (peer->ibuf);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'bgpd: Open option parse errors don't NOTIFY, resulting in abort & DoS
* bgp_packet.c: (bgp_open_receive) Errors from bgp_open_option_parse are
detected, and the code will stop processing the OPEN and return. However
it does so without calling bgp_notify_send to send a NOTIFY - which means
the peer FSM doesn't get stopped, and bgp_read will be called again later.
Because it returns, it doesn't go through the code near the end of the
function that removes the current message from the peer input streaam.
Thus the next call to bgp_read will try to parse a half-parsed stream as
if it were a new BGP message, leading to an assert later in the code when
it tries to read stuff that isn't there. Add the required call to
bgp_notify_send before returning.
* bgp_open.c: (bgp_capability_as4) Be a bit stricter, check the length field
corresponds to the only value it can be, which is the amount we're going to
read off the stream. And make sure the capability flag gets set, so
callers can know this capability was read, regardless.
(peek_for_as4_capability) Let bgp_capability_as4 do the length check.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
pmd_t *pmd;
unsigned long next;
int err = 0;
pmd = pmd_offset(pud, addr);
do {
again:
next = pmd_addr_end(addr, end);
if (pmd_none(*pmd)) {
if (walk->pte_hole)
err = walk->pte_hole(addr, next, walk);
if (err)
break;
continue;
}
/*
* This implies that each ->pmd_entry() handler
* needs to know about pmd_trans_huge() pmds
*/
if (walk->pmd_entry)
err = walk->pmd_entry(pmd, addr, next, walk);
if (err)
break;
/*
* Check this here so we only break down trans_huge
* pages when we _need_ to
*/
if (!walk->pte_entry)
continue;
split_huge_page_pmd(walk->mm, pmd);
if (pmd_none_or_clear_bad(pmd))
goto again;
err = walk_pte_range(pmd, addr, next, walk);
if (err)
break;
} while (pmd++, addr = next, addr != end);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[akpm@linux-foundation.org: checkpatch fixes]
Reported-by: Ulrich Obergfell <uobergfe@redhat.com>
Signed-off-by: Andrea Arcangeli <aarcange@redhat.com>
Acked-by: Johannes Weiner <hannes@cmpxchg.org>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Hugh Dickins <hughd@google.com>
Cc: Dave Jones <davej@redhat.com>
Acked-by: Larry Woodman <lwoodman@redhat.com>
Acked-by: Rik van Riel <riel@redhat.com>
Cc: <stable@vger.kernel.org> [2.6.38+]
Cc: Mark Salter <msalter@redhat.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 gather_pte_stats(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct numa_maps *md;
spinlock_t *ptl;
pte_t *orig_pte;
pte_t *pte;
md = walk->private;
spin_lock(&walk->mm->page_table_lock);
if (pmd_trans_huge(*pmd)) {
if (pmd_trans_splitting(*pmd)) {
spin_unlock(&walk->mm->page_table_lock);
wait_split_huge_page(md->vma->anon_vma, pmd);
} else {
pte_t huge_pte = *(pte_t *)pmd;
struct page *page;
page = can_gather_numa_stats(huge_pte, md->vma, addr);
if (page)
gather_stats(page, md, pte_dirty(huge_pte),
HPAGE_PMD_SIZE/PAGE_SIZE);
spin_unlock(&walk->mm->page_table_lock);
return 0;
}
} else {
spin_unlock(&walk->mm->page_table_lock);
}
orig_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
do {
struct page *page = can_gather_numa_stats(*pte, md->vma, addr);
if (!page)
continue;
gather_stats(page, md, pte_dirty(*pte), 1);
} while (pte++, addr += PAGE_SIZE, addr != end);
pte_unmap_unlock(orig_pte, ptl);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[akpm@linux-foundation.org: checkpatch fixes]
Reported-by: Ulrich Obergfell <uobergfe@redhat.com>
Signed-off-by: Andrea Arcangeli <aarcange@redhat.com>
Acked-by: Johannes Weiner <hannes@cmpxchg.org>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Hugh Dickins <hughd@google.com>
Cc: Dave Jones <davej@redhat.com>
Acked-by: Larry Woodman <lwoodman@redhat.com>
Acked-by: Rik van Riel <riel@redhat.com>
Cc: <stable@vger.kernel.org> [2.6.38+]
Cc: Mark Salter <msalter@redhat.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
ssize_t nr;
scn->sst_len = cdf_count_chain(sat, sid, ss);
scn->sst_dirlen = len;
if (scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read long sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading long sector chain "
"%u > %u\n", i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h,
sid)) != (ssize_t)ss) {
if (i == scn->sst_len - 1 && nr > 0) {
/* Last sector might be truncated */
return 0;
}
DPRINTF(("Reading long sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': '- add float and double types
- fix debug printf formats
- fix short stream sizes
- don't fail if we don't know about a type'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compressed_to_ciphertext (gnutls_session_t session,
uint8_t * cipher_data, int cipher_size,
gnutls_datum_t *compressed,
content_type_t type,
record_parameters_st * params)
{
uint8_t * tag_ptr = NULL;
uint8_t pad;
int length, length_to_encrypt, ret;
uint8_t preamble[MAX_PREAMBLE_SIZE];
int preamble_size;
int tag_size = _gnutls_auth_cipher_tag_len (¶ms->write.cipher_state);
int blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
unsigned block_algo =
_gnutls_cipher_is_block (params->cipher_algorithm);
uint8_t *data_ptr;
int ver = gnutls_protocol_get_version (session);
int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);
int auth_cipher = _gnutls_auth_cipher_is_aead(¶ms->write.cipher_state);
int random_pad;
/* We don't use long padding if requested or if we are in DTLS.
*/
if (session->internals.priorities.no_padding == 0 && (!IS_DTLS(session)))
random_pad = 1;
else
random_pad = 0;
_gnutls_hard_log("ENC[%p]: cipher: %s, MAC: %s, Epoch: %u\n",
session, gnutls_cipher_get_name(params->cipher_algorithm), gnutls_mac_get_name(params->mac_algorithm),
(unsigned int)params->epoch);
preamble_size =
make_preamble (UINT64DATA
(params->write.sequence_number),
type, compressed->size, ver, preamble);
/* Calculate the encrypted length (padding etc.)
*/
length_to_encrypt = length =
calc_enc_length (session, compressed->size, tag_size, &pad,
random_pad, block_algo, auth_cipher, blocksize);
if (length < 0)
{
return gnutls_assert_val(length);
}
/* copy the encrypted data to cipher_data.
*/
if (cipher_size < length)
{
return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
}
data_ptr = cipher_data;
if (explicit_iv)
{
if (block_algo == CIPHER_BLOCK)
{
/* copy the random IV.
*/
ret = _gnutls_rnd (GNUTLS_RND_NONCE, data_ptr, blocksize);
if (ret < 0)
return gnutls_assert_val(ret);
_gnutls_auth_cipher_setiv(¶ms->write.cipher_state, data_ptr, blocksize);
data_ptr += blocksize;
cipher_data += blocksize;
length_to_encrypt -= blocksize;
}
else if (auth_cipher)
{
uint8_t nonce[blocksize];
/* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block
*/
if (params->write.IV.data == NULL || params->write.IV.size != AEAD_IMPLICIT_DATA_SIZE)
return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
/* Instead of generating a new nonce on every packet, we use the
* write.sequence_number (It is a MAY on RFC 5288).
*/
memcpy(nonce, params->write.IV.data, params->write.IV.size);
memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], UINT64DATA(params->write.sequence_number), 8);
_gnutls_auth_cipher_setiv(¶ms->write.cipher_state, nonce, AEAD_IMPLICIT_DATA_SIZE+AEAD_EXPLICIT_DATA_SIZE);
/* copy the explicit part */
memcpy(data_ptr, &nonce[AEAD_IMPLICIT_DATA_SIZE], AEAD_EXPLICIT_DATA_SIZE);
data_ptr += AEAD_EXPLICIT_DATA_SIZE;
cipher_data += AEAD_EXPLICIT_DATA_SIZE;
/* In AEAD ciphers we don't encrypt the tag
*/
length_to_encrypt -= AEAD_EXPLICIT_DATA_SIZE + tag_size;
}
}
else
{
/* AEAD ciphers have an explicit IV. Shouldn't be used otherwise.
*/
if (auth_cipher) return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
}
memcpy (data_ptr, compressed->data, compressed->size);
data_ptr += compressed->size;
if (tag_size > 0)
{
tag_ptr = data_ptr;
data_ptr += tag_size;
}
if (block_algo == CIPHER_BLOCK && pad > 0)
{
memset (data_ptr, pad - 1, pad);
}
/* add the authenticate data */
ret = _gnutls_auth_cipher_add_auth(¶ms->write.cipher_state, preamble, preamble_size);
if (ret < 0)
return gnutls_assert_val(ret);
/* Actual encryption (inplace).
*/
ret =
_gnutls_auth_cipher_encrypt2_tag (¶ms->write.cipher_state,
cipher_data, length_to_encrypt,
cipher_data, cipher_size,
tag_ptr, tag_size, compressed->size);
if (ret < 0)
return gnutls_assert_val(ret);
return length;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'changes in packet parsing.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int phar_tar_process_metadata(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
{
char *metadata;
size_t save = php_stream_tell(fp), read;
phar_entry_info *mentry;
metadata = (char *) emalloc(entry->uncompressed_filesize + 1);
read = php_stream_read(fp, metadata, entry->uncompressed_filesize);
if (read != entry->uncompressed_filesize) {
efree(metadata);
php_stream_seek(fp, save, SEEK_SET);
return FAILURE;
}
if (phar_parse_metadata(&metadata, &entry->metadata, entry->uncompressed_filesize TSRMLS_CC) == FAILURE) {
/* if not valid serialized data, it is a regular string */
efree(metadata);
php_stream_seek(fp, save, SEEK_SET);
return FAILURE;
}
if (entry->filename_len == sizeof(".phar/.metadata.bin")-1 && !memcmp(entry->filename, ".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1)) {
entry->phar->metadata = entry->metadata;
entry->metadata = NULL;
} else if (entry->filename_len >= sizeof(".phar/.metadata/") + sizeof("/.metadata.bin") - 1 && SUCCESS == zend_hash_find(&(entry->phar->manifest), entry->filename + sizeof(".phar/.metadata/") - 1, entry->filename_len - (sizeof("/.metadata.bin") - 1 + sizeof(".phar/.metadata/") - 1), (void *)&mentry)) {
/* transfer this metadata to the entry it refers */
mentry->metadata = entry->metadata;
entry->metadata = NULL;
}
efree(metadata);
php_stream_seek(fp, save, SEEK_SET);
return SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'fix unchecked emalloc'</s> |
<s>[INST] Given the following code containing errors, provide 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 * calloc(size_t n, size_t lb)
{
if (lb && n > GC_SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'Speedup calloc size overflow check by preventing division if small values
* malloc.c (GC_SQRT_SIZE_MAX): New macro.
* malloc.c (calloc): Add fast initial size overflow check to avoid
integer division for reasonably small values passed.'</s> |
<s>[INST] Given the following code containing errors, provide 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 copy_creds(struct task_struct *p, unsigned long clone_flags)
{
#ifdef CONFIG_KEYS
struct thread_group_cred *tgcred;
#endif
struct cred *new;
int ret;
if (
#ifdef CONFIG_KEYS
!p->cred->thread_keyring &&
#endif
clone_flags & CLONE_THREAD
) {
p->real_cred = get_cred(p->cred);
get_cred(p->cred);
alter_cred_subscribers(p->cred, 2);
kdebug("share_creds(%p{%d,%d})",
p->cred, atomic_read(&p->cred->usage),
read_cred_subscribers(p->cred));
atomic_inc(&p->cred->user->processes);
return 0;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
goto error_put;
}
/* cache user_ns in cred. Doesn't need a refcount because it will
* stay pinned by cred->user
*/
new->user_ns = new->user->user_ns;
#ifdef CONFIG_KEYS
/* new threads get their own thread keyrings if their parent already
* had one */
if (new->thread_keyring) {
key_put(new->thread_keyring);
new->thread_keyring = NULL;
if (clone_flags & CLONE_THREAD)
install_thread_keyring_to_cred(new);
}
/* we share the process and session keyrings between all the threads in
* a process - this is slightly icky as we violate COW credentials a
* bit */
if (!(clone_flags & CLONE_THREAD)) {
tgcred = kmalloc(sizeof(*tgcred), GFP_KERNEL);
if (!tgcred) {
ret = -ENOMEM;
goto error_put;
}
atomic_set(&tgcred->usage, 1);
spin_lock_init(&tgcred->lock);
tgcred->process_keyring = NULL;
tgcred->session_keyring = key_get(new->tgcred->session_keyring);
release_tgcred(new);
new->tgcred = tgcred;
}
#endif
atomic_inc(&new->user->processes);
p->cred = p->real_cred = get_cred(new);
alter_cred_subscribers(new, 2);
validate_creds(new);
return 0;
error_put:
put_cred(new);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'cred: copy_process() should clear child->replacement_session_keyring
keyctl_session_to_parent(task) sets ->replacement_session_keyring,
it should be processed and cleared by key_replace_session_keyring().
However, this task can fork before it notices TIF_NOTIFY_RESUME and
the new child gets the bogus ->replacement_session_keyring copied by
dup_task_struct(). This is obviously wrong and, if nothing else, this
leads to put_cred(already_freed_cred).
change copy_creds() to clear this member. If copy_process() fails
before this point the wrong ->replacement_session_keyring doesn't
matter, exit_creds() won't be called.
Cc: <stable@vger.kernel.org>
Signed-off-by: Oleg Nesterov <oleg@redhat.com>
Acked-by: David Howells <dhowells@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'udf: Fortify loading of sparing table
Add sanity checks when loading sparing table from disk to avoid accessing
unallocated memory or writing to it.
Signed-off-by: Jan Kara <jack@suse.cz>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static long madvise_remove(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
loff_t offset;
int error;
*prev = NULL; /* tell sys_madvise we drop mmap_sem */
if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB))
return -EINVAL;
if (!vma->vm_file || !vma->vm_file->f_mapping
|| !vma->vm_file->f_mapping->host) {
return -EINVAL;
}
if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
return -EACCES;
offset = (loff_t)(start - vma->vm_start)
+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
/* filesystem's fallocate may need to take i_mutex */
up_read(¤t->mm->mmap_sem);
error = do_fallocate(vma->vm_file,
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, end - start);
down_read(¤t->mm->mmap_sem);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'mm: Hold a file reference in madvise_remove
Otherwise the code races with munmap (causing a use-after-free
of the vma) or with close (causing a use-after-free of the struct
file).
The bug was introduced by commit 90ed52ebe481 ("[PATCH] holepunch: fix
mmap_sem i_mutex deadlock")
Cc: Hugh Dickins <hugh@veritas.com>
Cc: Miklos Szeredi <mszeredi@suse.cz>
Cc: Badari Pulavarty <pbadari@us.ibm.com>
Cc: Nick Piggin <npiggin@suse.de>
Cc: stable@vger.kernel.org
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide 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 sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet_request_sock *ireq;
struct inet_sock *newinet;
struct sock *newsk;
if (sk_acceptq_is_full(sk))
goto exit_overflow;
if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL)
goto exit;
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto exit_nonewsk;
sk_setup_caps(newsk, dst);
newinet = inet_sk(newsk);
ireq = inet_rsk(req);
newinet->inet_daddr = ireq->rmt_addr;
newinet->inet_rcv_saddr = ireq->loc_addr;
newinet->inet_saddr = ireq->loc_addr;
newinet->opt = ireq->opt;
ireq->opt = NULL;
newinet->mc_index = inet_iif(skb);
newinet->mc_ttl = ip_hdr(skb)->ttl;
newinet->inet_id = jiffies;
dccp_sync_mss(newsk, dst_mtu(dst));
if (__inet_inherit_port(sk, newsk) < 0) {
sock_put(newsk);
goto exit;
}
__inet_hash_nolisten(newsk, NULL);
return newsk;
exit_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
exit_nonewsk:
dst_release(dst);
exit:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int do_ip_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct inet_sock *inet = inet_sk(sk);
int val = 0, err;
if (((1<<optname) & ((1<<IP_PKTINFO) | (1<<IP_RECVTTL) |
(1<<IP_RECVOPTS) | (1<<IP_RECVTOS) |
(1<<IP_RETOPTS) | (1<<IP_TOS) |
(1<<IP_TTL) | (1<<IP_HDRINCL) |
(1<<IP_MTU_DISCOVER) | (1<<IP_RECVERR) |
(1<<IP_ROUTER_ALERT) | (1<<IP_FREEBIND) |
(1<<IP_PASSSEC) | (1<<IP_TRANSPARENT) |
(1<<IP_MINTTL) | (1<<IP_NODEFRAG))) ||
optname == IP_MULTICAST_TTL ||
optname == IP_MULTICAST_ALL ||
optname == IP_MULTICAST_LOOP ||
optname == IP_RECVORIGDSTADDR) {
if (optlen >= sizeof(int)) {
if (get_user(val, (int __user *) optval))
return -EFAULT;
} else if (optlen >= sizeof(char)) {
unsigned char ucval;
if (get_user(ucval, (unsigned char __user *) optval))
return -EFAULT;
val = (int) ucval;
}
}
/* If optlen==0, it is equivalent to val == 0 */
if (ip_mroute_opt(optname))
return ip_mroute_setsockopt(sk, optname, optval, optlen);
err = 0;
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
struct ip_options *opt = NULL;
if (optlen > 40)
goto e_inval;
err = ip_options_get_from_user(sock_net(sk), &opt,
optval, optlen);
if (err)
break;
if (inet->is_icsk) {
struct inet_connection_sock *icsk = inet_csk(sk);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
if (sk->sk_family == PF_INET ||
(!((1 << sk->sk_state) &
(TCPF_LISTEN | TCPF_CLOSE)) &&
inet->inet_daddr != LOOPBACK4_IPV6)) {
#endif
if (inet->opt)
icsk->icsk_ext_hdr_len -= inet->opt->optlen;
if (opt)
icsk->icsk_ext_hdr_len += opt->optlen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
}
#endif
}
opt = xchg(&inet->opt, opt);
kfree(opt);
break;
}
case IP_PKTINFO:
if (val)
inet->cmsg_flags |= IP_CMSG_PKTINFO;
else
inet->cmsg_flags &= ~IP_CMSG_PKTINFO;
break;
case IP_RECVTTL:
if (val)
inet->cmsg_flags |= IP_CMSG_TTL;
else
inet->cmsg_flags &= ~IP_CMSG_TTL;
break;
case IP_RECVTOS:
if (val)
inet->cmsg_flags |= IP_CMSG_TOS;
else
inet->cmsg_flags &= ~IP_CMSG_TOS;
break;
case IP_RECVOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RECVOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RECVOPTS;
break;
case IP_RETOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RETOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RETOPTS;
break;
case IP_PASSSEC:
if (val)
inet->cmsg_flags |= IP_CMSG_PASSSEC;
else
inet->cmsg_flags &= ~IP_CMSG_PASSSEC;
break;
case IP_RECVORIGDSTADDR:
if (val)
inet->cmsg_flags |= IP_CMSG_ORIGDSTADDR;
else
inet->cmsg_flags &= ~IP_CMSG_ORIGDSTADDR;
break;
case IP_TOS: /* This sets both TOS and Precedence */
if (sk->sk_type == SOCK_STREAM) {
val &= ~3;
val |= inet->tos & 3;
}
if (inet->tos != val) {
inet->tos = val;
sk->sk_priority = rt_tos2priority(val);
sk_dst_reset(sk);
}
break;
case IP_TTL:
if (optlen < 1)
goto e_inval;
if (val != -1 && (val < 0 || val > 255))
goto e_inval;
inet->uc_ttl = val;
break;
case IP_HDRINCL:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->hdrincl = val ? 1 : 0;
break;
case IP_NODEFRAG:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->nodefrag = val ? 1 : 0;
break;
case IP_MTU_DISCOVER:
if (val < IP_PMTUDISC_DONT || val > IP_PMTUDISC_PROBE)
goto e_inval;
inet->pmtudisc = val;
break;
case IP_RECVERR:
inet->recverr = !!val;
if (!val)
skb_queue_purge(&sk->sk_error_queue);
break;
case IP_MULTICAST_TTL:
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
if (optlen < 1)
goto e_inval;
if (val == -1)
val = 1;
if (val < 0 || val > 255)
goto e_inval;
inet->mc_ttl = val;
break;
case IP_MULTICAST_LOOP:
if (optlen < 1)
goto e_inval;
inet->mc_loop = !!val;
break;
case IP_MULTICAST_IF:
{
struct ip_mreqn mreq;
struct net_device *dev = NULL;
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
/*
* Check the arguments are allowable
*/
if (optlen < sizeof(struct in_addr))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (optlen >= sizeof(struct in_addr) &&
copy_from_user(&mreq.imr_address, optval,
sizeof(struct in_addr)))
break;
}
if (!mreq.imr_ifindex) {
if (mreq.imr_address.s_addr == htonl(INADDR_ANY)) {
inet->mc_index = 0;
inet->mc_addr = 0;
err = 0;
break;
}
dev = ip_dev_find(sock_net(sk), mreq.imr_address.s_addr);
if (dev)
mreq.imr_ifindex = dev->ifindex;
} else
dev = dev_get_by_index(sock_net(sk), mreq.imr_ifindex);
err = -EADDRNOTAVAIL;
if (!dev)
break;
dev_put(dev);
err = -EINVAL;
if (sk->sk_bound_dev_if &&
mreq.imr_ifindex != sk->sk_bound_dev_if)
break;
inet->mc_index = mreq.imr_ifindex;
inet->mc_addr = mreq.imr_address.s_addr;
err = 0;
break;
}
case IP_ADD_MEMBERSHIP:
case IP_DROP_MEMBERSHIP:
{
struct ip_mreqn mreq;
err = -EPROTO;
if (inet_sk(sk)->is_icsk)
break;
if (optlen < sizeof(struct ip_mreq))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq)))
break;
}
if (optname == IP_ADD_MEMBERSHIP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case IP_MSFILTER:
{
struct ip_msfilter *msf;
if (optlen < IP_MSFILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
msf = kmalloc(optlen, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(msf, optval, optlen)) {
kfree(msf);
break;
}
/* numsrc >= (1G-4) overflow in 32 bits */
if (msf->imsf_numsrc >= 0x3ffffffcU ||
msf->imsf_numsrc > sysctl_igmp_max_msf) {
kfree(msf);
err = -ENOBUFS;
break;
}
if (IP_MSFILTER_SIZE(msf->imsf_numsrc) > optlen) {
kfree(msf);
err = -EINVAL;
break;
}
err = ip_mc_msfilter(sk, msf, 0);
kfree(msf);
break;
}
case IP_BLOCK_SOURCE:
case IP_UNBLOCK_SOURCE:
case IP_ADD_SOURCE_MEMBERSHIP:
case IP_DROP_SOURCE_MEMBERSHIP:
{
struct ip_mreq_source mreqs;
int omode, add;
if (optlen != sizeof(struct ip_mreq_source))
goto e_inval;
if (copy_from_user(&mreqs, optval, sizeof(mreqs))) {
err = -EFAULT;
break;
}
if (optname == IP_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == IP_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == IP_ADD_SOURCE_MEMBERSHIP) {
struct ip_mreqn mreq;
mreq.imr_multiaddr.s_addr = mreqs.imr_multiaddr;
mreq.imr_address.s_addr = mreqs.imr_interface;
mreq.imr_ifindex = 0;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
omode = MCAST_INCLUDE;
add = 1;
} else /* IP_DROP_SOURCE_MEMBERSHIP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs, 0);
break;
}
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct group_req greq;
struct sockaddr_in *psin;
struct ip_mreqn mreq;
if (optlen < sizeof(struct group_req))
goto e_inval;
err = -EFAULT;
if (copy_from_user(&greq, optval, sizeof(greq)))
break;
psin = (struct sockaddr_in *)&greq.gr_group;
if (psin->sin_family != AF_INET)
goto e_inval;
memset(&mreq, 0, sizeof(mreq));
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_ifindex = greq.gr_interface;
if (optname == MCAST_JOIN_GROUP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct group_source_req greqs;
struct ip_mreq_source mreqs;
struct sockaddr_in *psin;
int omode, add;
if (optlen != sizeof(struct group_source_req))
goto e_inval;
if (copy_from_user(&greqs, optval, sizeof(greqs))) {
err = -EFAULT;
break;
}
if (greqs.gsr_group.ss_family != AF_INET ||
greqs.gsr_source.ss_family != AF_INET) {
err = -EADDRNOTAVAIL;
break;
}
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreqs.imr_multiaddr = psin->sin_addr.s_addr;
psin = (struct sockaddr_in *)&greqs.gsr_source;
mreqs.imr_sourceaddr = psin->sin_addr.s_addr;
mreqs.imr_interface = 0; /* use index for mc_source */
if (optname == MCAST_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == MCAST_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == MCAST_JOIN_SOURCE_GROUP) {
struct ip_mreqn mreq;
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_address.s_addr = 0;
mreq.imr_ifindex = greqs.gsr_interface;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
greqs.gsr_interface = mreq.imr_ifindex;
omode = MCAST_INCLUDE;
add = 1;
} else /* MCAST_LEAVE_SOURCE_GROUP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs,
greqs.gsr_interface);
break;
}
case MCAST_MSFILTER:
{
struct sockaddr_in *psin;
struct ip_msfilter *msf = NULL;
struct group_filter *gsf = NULL;
int msize, i, ifindex;
if (optlen < GROUP_FILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
gsf = kmalloc(optlen, GFP_KERNEL);
if (!gsf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(gsf, optval, optlen))
goto mc_msf_out;
/* numsrc >= (4G-140)/128 overflow in 32 bits */
if (gsf->gf_numsrc >= 0x1ffffff ||
gsf->gf_numsrc > sysctl_igmp_max_msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) {
err = -EINVAL;
goto mc_msf_out;
}
msize = IP_MSFILTER_SIZE(gsf->gf_numsrc);
msf = kmalloc(msize, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
ifindex = gsf->gf_interface;
psin = (struct sockaddr_in *)&gsf->gf_group;
if (psin->sin_family != AF_INET) {
err = -EADDRNOTAVAIL;
goto mc_msf_out;
}
msf->imsf_multiaddr = psin->sin_addr.s_addr;
msf->imsf_interface = 0;
msf->imsf_fmode = gsf->gf_fmode;
msf->imsf_numsrc = gsf->gf_numsrc;
err = -EADDRNOTAVAIL;
for (i = 0; i < gsf->gf_numsrc; ++i) {
psin = (struct sockaddr_in *)&gsf->gf_slist[i];
if (psin->sin_family != AF_INET)
goto mc_msf_out;
msf->imsf_slist[i] = psin->sin_addr.s_addr;
}
kfree(gsf);
gsf = NULL;
err = ip_mc_msfilter(sk, msf, ifindex);
mc_msf_out:
kfree(msf);
kfree(gsf);
break;
}
case IP_MULTICAST_ALL:
if (optlen < 1)
goto e_inval;
if (val != 0 && val != 1)
goto e_inval;
inet->mc_all = val;
break;
case IP_ROUTER_ALERT:
err = ip_ra_control(sk, val ? 1 : 0, NULL);
break;
case IP_FREEBIND:
if (optlen < 1)
goto e_inval;
inet->freebind = !!val;
break;
case IP_IPSEC_POLICY:
case IP_XFRM_POLICY:
err = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
err = xfrm_user_policy(sk, optname, optval, optlen);
break;
case IP_TRANSPARENT:
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
break;
}
if (optlen < 1)
goto e_inval;
inet->transparent = !!val;
break;
case IP_MINTTL:
if (optlen < 1)
goto e_inval;
if (val < 0 || val > 255)
goto e_inval;
inet->min_ttl = val;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
e_inval:
release_sock(sk);
return -EINVAL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
{
struct ipcm_cookie ipc;
struct rtable *rt = skb_rtable(skb);
struct net *net = dev_net(rt->dst.dev);
struct sock *sk;
struct inet_sock *inet;
__be32 daddr;
if (ip_options_echo(&icmp_param->replyopts, skb))
return;
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
inet = inet_sk(sk);
icmp_param->data.icmph.checksum = 0;
inet->tos = ip_hdr(skb)->tos;
daddr = ipc.addr = rt->rt_src;
ipc.opt = NULL;
ipc.tx_flags = 0;
if (icmp_param->replyopts.optlen) {
ipc.opt = &icmp_param->replyopts;
if (ipc.opt->srr)
daddr = icmp_param->replyopts.faddr;
}
{
struct flowi4 fl4 = {
.daddr = daddr,
.saddr = rt->rt_spec_dst,
.flowi4_tos = RT_TOS(ip_hdr(skb)->tos),
.flowi4_proto = IPPROTO_ICMP,
};
security_skb_classify_flow(skb, flowi4_to_flowi(&fl4));
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
goto out_unlock;
}
if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type,
icmp_param->data.icmph.code))
icmp_push_reply(icmp_param, &ipc, &rt);
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path,
struct ext4_map_blocks *map,
int split_flag,
int flags)
{
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len, depth;
int err = 0;
int uninitialized;
int split_flag1, flags1;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
uninitialized = ext4_ext_is_uninitialized(ex);
if (map->m_lblk + map->m_len < ee_block + ee_len) {
split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
EXT4_EXT_MAY_ZEROOUT : 0;
flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
if (uninitialized)
split_flag1 |= EXT4_EXT_MARK_UNINIT1 |
EXT4_EXT_MARK_UNINIT2;
err = ext4_split_extent_at(handle, inode, path,
map->m_lblk + map->m_len, split_flag1, flags1);
if (err)
goto out;
}
ext4_ext_drop_refs(path);
path = ext4_ext_find_extent(inode, map->m_lblk, path);
if (IS_ERR(path))
return PTR_ERR(path);
if (map->m_lblk >= ee_block) {
split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
EXT4_EXT_MAY_ZEROOUT : 0;
if (uninitialized)
split_flag1 |= EXT4_EXT_MARK_UNINIT1;
if (split_flag & EXT4_EXT_MARK_UNINIT2)
split_flag1 |= EXT4_EXT_MARK_UNINIT2;
err = ext4_split_extent_at(handle, inode, path,
map->m_lblk, split_flag1, flags);
if (err)
goto out;
}
ext4_ext_show_leaf(inode, path);
out:
return err ? err : map->m_len;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <dmonakhov@openvz.org>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Cc: stable@vger.kernel.org'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: hook_process_child (struct t_hook *hook_process)
{
char *exec_args[4] = { "sh", "-c", NULL, NULL };
const char *ptr_url;
int rc;
/*
* close stdin, so that process will fail to read stdin (process reading
* stdin should not be run inside WeeChat!)
*/
close (STDIN_FILENO);
/* redirect stdout/stderr to pipe (so that father process can read them) */
close (HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDOUT]));
close (HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDERR]));
if (dup2 (HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDOUT]),
STDOUT_FILENO) < 0)
{
_exit (EXIT_FAILURE);
}
if (dup2 (HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDERR]),
STDERR_FILENO) < 0)
{
_exit (EXIT_FAILURE);
}
rc = EXIT_SUCCESS;
if (strncmp (HOOK_PROCESS(hook_process, command), "url:", 4) == 0)
{
/* get URL output (on stdout or file, depending on options) */
ptr_url = HOOK_PROCESS(hook_process, command) + 4;
while (ptr_url[0] == ' ')
{
ptr_url++;
}
rc = weeurl_download (ptr_url, HOOK_PROCESS(hook_process, options));
if (rc != 0)
fprintf (stderr, "Error with URL '%s'\n", ptr_url);
}
else
{
/* launch command */
exec_args[2] = HOOK_PROCESS(hook_process, command);
execvp (exec_args[0], exec_args);
/* should not be executed if execvp was ok */
fprintf (stderr, "Error with command '%s'\n",
HOOK_PROCESS(hook_process, command));
rc = EXIT_FAILURE;
}
fflush (stdout);
fflush (stderr);
_exit (rc);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'core: do not call shell to execute command in hook_process (fix security problem when a plugin/script gives untrusted command) (bug #37764)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: insert (position p, position_set *s)
{
int count = s->nelem;
int lo = 0, hi = count;
int i;
while (lo < hi)
{
int mid = ((unsigned) lo + (unsigned) hi) >> 1;
if (s->elems[mid].index > p.index)
lo = mid + 1;
else
hi = mid;
}
if (lo < count && p.index == s->elems[lo].index)
{
s->elems[lo].constraint |= p.constraint;
return;
}
REALLOC_IF_NECESSARY(s->elems, s->alloc, count + 1);
for (i = count; i > lo; i--)
s->elems[i] = s->elems[i - 1];
s->elems[lo] = p;
++s->nelem;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dfaanalyze (struct dfa *d, int searchflag)
{
int *nullable; /* Nullable stack. */
int *nfirstpos; /* Element count stack for firstpos sets. */
position *firstpos; /* Array where firstpos elements are stored. */
int *nlastpos; /* Element count stack for lastpos sets. */
position *lastpos; /* Array where lastpos elements are stored. */
position_set tmp; /* Temporary set for merging sets. */
position_set merged; /* Result of merging sets. */
int separate_contexts; /* Context wanted by some position. */
int *o_nullable;
int *o_nfirst, *o_nlast;
position *o_firstpos, *o_lastpos;
int i, j;
position *pos;
#ifdef DEBUG
fprintf(stderr, "dfaanalyze:\n");
for (i = 0; i < d->tindex; ++i)
{
fprintf(stderr, " %d:", i);
prtok(d->tokens[i]);
}
putc('\n', stderr);
#endif
d->searchflag = searchflag;
MALLOC(nullable, d->depth);
o_nullable = nullable;
MALLOC(nfirstpos, d->depth);
o_nfirst = nfirstpos;
MALLOC(firstpos, d->nleaves);
o_firstpos = firstpos, firstpos += d->nleaves;
MALLOC(nlastpos, d->depth);
o_nlast = nlastpos;
MALLOC(lastpos, d->nleaves);
o_lastpos = lastpos, lastpos += d->nleaves;
alloc_position_set(&merged, d->nleaves);
CALLOC(d->follows, d->tindex);
for (i = 0; i < d->tindex; ++i)
{
switch (d->tokens[i])
{
case EMPTY:
/* The empty set is nullable. */
*nullable++ = 1;
/* The firstpos and lastpos of the empty leaf are both empty. */
*nfirstpos++ = *nlastpos++ = 0;
break;
case STAR:
case PLUS:
/* Every element in the firstpos of the argument is in the follow
of every element in the lastpos. */
tmp.nelem = nfirstpos[-1];
tmp.elems = firstpos;
pos = lastpos;
for (j = 0; j < nlastpos[-1]; ++j)
{
merge(&tmp, &d->follows[pos[j].index], &merged);
copy(&merged, &d->follows[pos[j].index]);
}
case QMARK:
/* A QMARK or STAR node is automatically nullable. */
if (d->tokens[i] != PLUS)
nullable[-1] = 1;
break;
case CAT:
/* Every element in the firstpos of the second argument is in the
follow of every element in the lastpos of the first argument. */
tmp.nelem = nfirstpos[-1];
tmp.elems = firstpos;
pos = lastpos + nlastpos[-1];
for (j = 0; j < nlastpos[-2]; ++j)
{
merge(&tmp, &d->follows[pos[j].index], &merged);
copy(&merged, &d->follows[pos[j].index]);
}
/* The firstpos of a CAT node is the firstpos of the first argument,
union that of the second argument if the first is nullable. */
if (nullable[-2])
nfirstpos[-2] += nfirstpos[-1];
else
firstpos += nfirstpos[-1];
--nfirstpos;
/* The lastpos of a CAT node is the lastpos of the second argument,
union that of the first argument if the second is nullable. */
if (nullable[-1])
nlastpos[-2] += nlastpos[-1];
else
{
pos = lastpos + nlastpos[-2];
for (j = nlastpos[-1] - 1; j >= 0; --j)
pos[j] = lastpos[j];
lastpos += nlastpos[-2];
nlastpos[-2] = nlastpos[-1];
}
--nlastpos;
/* A CAT node is nullable if both arguments are nullable. */
nullable[-2] = nullable[-1] && nullable[-2];
--nullable;
break;
case OR:
/* The firstpos is the union of the firstpos of each argument. */
nfirstpos[-2] += nfirstpos[-1];
--nfirstpos;
/* The lastpos is the union of the lastpos of each argument. */
nlastpos[-2] += nlastpos[-1];
--nlastpos;
/* An OR node is nullable if either argument is nullable. */
nullable[-2] = nullable[-1] || nullable[-2];
--nullable;
break;
default:
/* Anything else is a nonempty position. (Note that special
constructs like \< are treated as nonempty strings here;
an "epsilon closure" effectively makes them nullable later.
Backreferences have to get a real position so we can detect
transitions on them later. But they are nullable. */
*nullable++ = d->tokens[i] == BACKREF;
/* This position is in its own firstpos and lastpos. */
*nfirstpos++ = *nlastpos++ = 1;
--firstpos, --lastpos;
firstpos->index = lastpos->index = i;
firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
/* Allocate the follow set for this position. */
alloc_position_set(&d->follows[i], 1);
break;
}
#ifdef DEBUG
/* ... balance the above nonsyntactic #ifdef goo... */
fprintf(stderr, "node %d:", i);
prtok(d->tokens[i]);
putc('\n', stderr);
fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
fprintf(stderr, " firstpos:");
for (j = nfirstpos[-1] - 1; j >= 0; --j)
{
fprintf(stderr, " %d:", firstpos[j].index);
prtok(d->tokens[firstpos[j].index]);
}
fprintf(stderr, "\n lastpos:");
for (j = nlastpos[-1] - 1; j >= 0; --j)
{
fprintf(stderr, " %d:", lastpos[j].index);
prtok(d->tokens[lastpos[j].index]);
}
putc('\n', stderr);
#endif
}
/* For each follow set that is the follow set of a real position, replace
it with its epsilon closure. */
for (i = 0; i < d->tindex; ++i)
if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
#if MBS_SUPPORT
|| d->tokens[i] == ANYCHAR
|| d->tokens[i] == MBCSET
#endif
|| d->tokens[i] >= CSET)
{
#ifdef DEBUG
fprintf(stderr, "follows(%d:", i);
prtok(d->tokens[i]);
fprintf(stderr, "):");
for (j = d->follows[i].nelem - 1; j >= 0; --j)
{
fprintf(stderr, " %d:", d->follows[i].elems[j].index);
prtok(d->tokens[d->follows[i].elems[j].index]);
}
putc('\n', stderr);
#endif
copy(&d->follows[i], &merged);
epsclosure(&merged, d);
copy(&merged, &d->follows[i]);
}
/* Get the epsilon closure of the firstpos of the regexp. The result will
be the set of positions of state 0. */
merged.nelem = 0;
for (i = 0; i < nfirstpos[-1]; ++i)
insert(firstpos[i], &merged);
epsclosure(&merged, d);
/* Build the initial state. */
d->salloc = 1;
d->sindex = 0;
MALLOC(d->states, d->salloc);
separate_contexts = state_separate_contexts (&merged);
state_index(d, &merged,
(separate_contexts & CTX_NEWLINE
? CTX_NEWLINE
: separate_contexts ^ CTX_ANY));
free(o_nullable);
free(o_nfirst);
free(o_firstpos);
free(o_nlast);
free(o_lastpos);
free(merged.elems);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: addtok (token t)
{
if (MB_CUR_MAX > 1 && t == MBCSET)
{
bool need_or = false;
struct mb_char_classes *work_mbc = &dfa->mbcsets[dfa->nmbcsets - 1];
/* Extract wide characters into alternations for better performance.
This does not require UTF-8. */
if (!work_mbc->invert)
{
int i;
for (i = 0; i < work_mbc->nchars; i++)
{
addtok_wc (work_mbc->chars[i]);
if (need_or)
addtok (OR);
need_or = true;
}
work_mbc->nchars = 0;
}
/* UTF-8 allows treating a simple, non-inverted MBCSET like a CSET. */
if (work_mbc->invert
|| (!using_utf8() && work_mbc->cset != -1)
|| work_mbc->nchars != 0
|| work_mbc->nch_classes != 0
|| work_mbc->nranges != 0
|| work_mbc->nequivs != 0
|| work_mbc->ncoll_elems != 0)
{
addtok_mb (MBCSET, ((dfa->nmbcsets - 1) << 2) + 3);
if (need_or)
addtok (OR);
}
else
{
/* Characters have been handled above, so it is possible
that the mbcset is empty now. Do nothing in that case. */
if (work_mbc->cset != -1)
{
assert (using_utf8 ());
addtok (CSET + work_mbc->cset);
if (need_or)
addtok (OR);
}
}
}
else
{
addtok_mb (t, 3);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dfamust (struct dfa *d)
{
must *musts;
must *mp;
char *result;
int ri;
int i;
int exact;
token t;
static must must0;
struct dfamust *dm;
static char empty_string[] = "";
result = empty_string;
exact = 0;
MALLOC (musts, d->tindex + 1);
mp = musts;
for (i = 0; i <= d->tindex; ++i)
mp[i] = must0;
for (i = 0; i <= d->tindex; ++i)
{
mp[i].in = xmalloc(sizeof *mp[i].in);
mp[i].left = xmalloc(2);
mp[i].right = xmalloc(2);
mp[i].is = xmalloc(2);
mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
mp[i].in[0] = NULL;
}
#ifdef DEBUG
fprintf(stderr, "dfamust:\n");
for (i = 0; i < d->tindex; ++i)
{
fprintf(stderr, " %d:", i);
prtok(d->tokens[i]);
}
putc('\n', stderr);
#endif
for (ri = 0; ri < d->tindex; ++ri)
{
switch (t = d->tokens[ri])
{
case LPAREN:
case RPAREN:
assert (!"neither LPAREN nor RPAREN may appear here");
case EMPTY:
case BEGLINE:
case ENDLINE:
case BEGWORD:
case ENDWORD:
case LIMWORD:
case NOTLIMWORD:
case BACKREF:
resetmust(mp);
break;
case STAR:
case QMARK:
assert (musts < mp);
--mp;
resetmust(mp);
break;
case OR:
assert (&musts[2] <= mp);
{
char **new;
must *lmp;
must *rmp;
int j, ln, rn, n;
rmp = --mp;
lmp = --mp;
/* Guaranteed to be. Unlikely, but. . . */
if (!STREQ (lmp->is, rmp->is))
lmp->is[0] = '\0';
/* Left side--easy */
i = 0;
while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
++i;
lmp->left[i] = '\0';
/* Right side */
ln = strlen(lmp->right);
rn = strlen(rmp->right);
n = ln;
if (n > rn)
n = rn;
for (i = 0; i < n; ++i)
if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
break;
for (j = 0; j < i; ++j)
lmp->right[j] = lmp->right[(ln - i) + j];
lmp->right[j] = '\0';
new = inboth(lmp->in, rmp->in);
if (new == NULL)
goto done;
freelist(lmp->in);
free(lmp->in);
lmp->in = new;
}
break;
case PLUS:
assert (musts < mp);
--mp;
mp->is[0] = '\0';
break;
case END:
assert (mp == &musts[1]);
for (i = 0; musts[0].in[i] != NULL; ++i)
if (strlen(musts[0].in[i]) > strlen(result))
result = musts[0].in[i];
if (STREQ (result, musts[0].is))
exact = 1;
goto done;
case CAT:
assert (&musts[2] <= mp);
{
must *lmp;
must *rmp;
rmp = --mp;
lmp = --mp;
/* In. Everything in left, plus everything in
right, plus catenation of
left's right and right's left. */
lmp->in = addlists(lmp->in, rmp->in);
if (lmp->in == NULL)
goto done;
if (lmp->right[0] != '\0' &&
rmp->left[0] != '\0')
{
char *tp;
tp = icpyalloc(lmp->right);
tp = icatalloc(tp, rmp->left);
lmp->in = enlist(lmp->in, tp, strlen(tp));
free(tp);
if (lmp->in == NULL)
goto done;
}
/* Left-hand */
if (lmp->is[0] != '\0')
{
lmp->left = icatalloc(lmp->left,
rmp->left);
if (lmp->left == NULL)
goto done;
}
/* Right-hand */
if (rmp->is[0] == '\0')
lmp->right[0] = '\0';
lmp->right = icatalloc(lmp->right, rmp->right);
if (lmp->right == NULL)
goto done;
/* Guaranteed to be */
if (lmp->is[0] != '\0' && rmp->is[0] != '\0')
{
lmp->is = icatalloc(lmp->is, rmp->is);
if (lmp->is == NULL)
goto done;
}
else
lmp->is[0] = '\0';
}
break;
default:
if (t < END)
{
assert (!"oops! t >= END");
}
else if (t == '\0')
{
/* not on *my* shift */
goto done;
}
else if (t >= CSET
|| !MBS_SUPPORT
|| t == ANYCHAR
|| t == MBCSET
)
{
/* easy enough */
resetmust(mp);
}
else
{
/* plain character */
resetmust(mp);
mp->is[0] = mp->left[0] = mp->right[0] = t;
mp->is[1] = mp->left[1] = mp->right[1] = '\0';
mp->in = enlist(mp->in, mp->is, (size_t)1);
if (mp->in == NULL)
goto done;
}
break;
}
#ifdef DEBUG
fprintf(stderr, " node: %d:", ri);
prtok(d->tokens[ri]);
fprintf(stderr, "\n in:");
for (i = 0; mp->in[i]; ++i)
fprintf(stderr, " \"%s\"", mp->in[i]);
fprintf(stderr, "\n is: \"%s\"\n", mp->is);
fprintf(stderr, " left: \"%s\"\n", mp->left);
fprintf(stderr, " right: \"%s\"\n", mp->right);
#endif
++mp;
}
done:
if (strlen(result))
{
MALLOC(dm, 1);
dm->exact = exact;
MALLOC(dm->must, strlen(result) + 1);
strcpy(dm->must, result);
dm->next = d->musts;
d->musts = dm;
}
mp = musts;
for (i = 0; i <= d->tindex; ++i)
{
freelist(mp[i].in);
free(mp[i].in);
free(mp[i].left);
free(mp[i].right);
free(mp[i].is);
}
free(mp);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: context_length_arg (char const *str, int *out)
{
uintmax_t value;
if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK
&& 0 <= (*out = value)
&& *out == value))
{
error (EXIT_TROUBLE, 0, "%s: %s", str,
_("invalid context length argument"));
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program
* NEWS: Document this.
* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.
Remove xstrtoumax.
* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.
(context_length_arg, prtext, grepbuf, grep, grepfile)
(get_nondigit_option, main):
Use intmax_t, not int, for line counts.
(context_length_arg, main): Silently ceiling line counts
to maximum value, since there's no practical difference between
doing that and using infinite-precision arithmetic.
(out_before, out_after, pending): Now intmax_t, not int.
(max_count, outleft): Now intmax_t, not off_t.
(prepend_args, prepend_default_options, main):
Use size_t, not int, for sizes.
(prepend_default_options): Check for int and size_t overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: crm_recv_remote_msg(void *session, gboolean encrypted)
{
char *reply = NULL;
xmlNode *xml = NULL;
if (encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
reply = cib_recv_tls(session);
#else
CRM_ASSERT(encrypted == FALSE);
#endif
} else {
reply = cib_recv_plaintext(GPOINTER_TO_INT(session));
}
if (reply == NULL || strlen(reply) == 0) {
crm_trace("Empty reply");
} else {
xml = string2xml(reply);
if (xml == NULL) {
crm_err("Couldn't parse: '%.120s'", reply);
}
}
free(reply);
return xml;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_recv_plaintext(int sock)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = 512;
buf = calloc(1, chunk_size);
while (1) {
errno = 0;
rc = read(sock, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
if (errno == EINTR || errno == EAGAIN) {
crm_trace("Retry: %d", (int)rc);
if (rc > 0) {
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
}
} else if (rc < 0) {
crm_perror(LOG_ERR, "Error receiving message: %d", (int)rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
return buf;
}
}
bail:
free(buf);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: add_account (GoaProvider *provider,
GoaClient *client,
GtkDialog *dialog,
GtkBox *vbox,
GError **error)
{
AddAccountData data;
GVariantBuilder credentials;
GVariantBuilder details;
GoaHttpClient *http_client;
GoaObject *ret;
const gchar *uri_text;
const gchar *password;
const gchar *username;
const gchar *provider_type;
gchar *presentation_identity;
gchar *server;
gchar *uri;
gchar *uri_webdav;
gint response;
http_client = NULL;
presentation_identity = NULL;
server = NULL;
uri = NULL;
ret = NULL;
memset (&data, 0, sizeof (AddAccountData));
data.cancellable = g_cancellable_new ();
data.loop = g_main_loop_new (NULL, FALSE);
data.dialog = dialog;
data.error = NULL;
create_account_details_ui (provider, dialog, vbox, TRUE, &data);
gtk_widget_show_all (GTK_WIDGET (vbox));
g_signal_connect (dialog, "response", G_CALLBACK (dialog_response_cb), &data);
http_client = goa_http_client_new ();
http_again:
response = gtk_dialog_run (dialog);
if (response != GTK_RESPONSE_OK)
{
g_set_error (&data.error,
GOA_ERROR,
GOA_ERROR_DIALOG_DISMISSED,
_("Dialog was dismissed"));
goto out;
}
uri_text = gtk_entry_get_text (GTK_ENTRY (data.uri));
username = gtk_entry_get_text (GTK_ENTRY (data.username));
password = gtk_entry_get_text (GTK_ENTRY (data.password));
/* See if there's already an account of this type with the
* given identity
*/
provider_type = goa_provider_get_provider_type (provider);
if (!goa_utils_check_duplicate (client,
username,
provider_type,
(GoaPeekInterfaceFunc) goa_object_peek_password_based,
&data.error))
goto out;
uri = normalize_uri (uri_text, &server);
uri_webdav = g_strconcat (uri, WEBDAV_ENDPOINT, NULL);
g_cancellable_reset (data.cancellable);
goa_http_client_check (http_client,
uri_webdav,
username,
password,
data.cancellable,
check_cb,
&data);
g_free (uri_webdav);
gtk_widget_set_sensitive (data.connect_button, FALSE);
gtk_widget_show (data.progress_grid);
g_main_loop_run (data.loop);
if (g_cancellable_is_cancelled (data.cancellable))
{
g_prefix_error (&data.error,
_("Dialog was dismissed (%s, %d): "),
g_quark_to_string (data.error->domain),
data.error->code);
data.error->domain = GOA_ERROR;
data.error->code = GOA_ERROR_DIALOG_DISMISSED;
goto out;
}
else if (data.error != NULL)
{
gchar *markup;
markup = g_strdup_printf ("<b>%s:</b> %s",
_("Error connecting to ownCloud server"),
data.error->message);
g_clear_error (&data.error);
gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
g_free (markup);
gtk_button_set_label (GTK_BUTTON (data.connect_button), _("_Try Again"));
gtk_widget_set_no_show_all (data.cluebar, FALSE);
gtk_widget_show_all (data.cluebar);
g_clear_pointer (&server, g_free);
g_clear_pointer (&uri, g_free);
goto http_again;
}
gtk_widget_hide (GTK_WIDGET (dialog));
g_variant_builder_init (&credentials, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&credentials, "{sv}", "password", g_variant_new_string (password));
g_variant_builder_init (&details, G_VARIANT_TYPE ("a{ss}"));
g_variant_builder_add (&details, "{ss}", "CalendarEnabled", "true");
g_variant_builder_add (&details, "{ss}", "ContactsEnabled", "true");
g_variant_builder_add (&details, "{ss}", "FilesEnabled", "true");
g_variant_builder_add (&details, "{ss}", "Uri", uri);
/* OK, everything is dandy, add the account */
/* we want the GoaClient to update before this method returns (so it
* can create a proxy for the new object) so run the mainloop while
* waiting for this to complete
*/
presentation_identity = g_strconcat (username, "@", server, NULL);
goa_manager_call_add_account (goa_client_get_manager (client),
goa_provider_get_provider_type (provider),
username,
presentation_identity,
g_variant_builder_end (&credentials),
g_variant_builder_end (&details),
NULL, /* GCancellable* */
(GAsyncReadyCallback) add_account_cb,
&data);
g_main_loop_run (data.loop);
if (data.error != NULL)
goto out;
ret = GOA_OBJECT (g_dbus_object_manager_get_object (goa_client_get_object_manager (client),
data.account_object_path));
out:
/* We might have an object even when data.error is set.
* eg., if we failed to store the credentials in the keyring.
*/
if (data.error != NULL)
g_propagate_error (error, data.error);
else
g_assert (ret != NULL);
g_free (presentation_identity);
g_free (server);
g_free (uri);
g_free (data.account_object_path);
if (data.loop != NULL)
g_main_loop_unref (data.loop);
g_clear_object (&data.cancellable);
g_clear_object (&http_client);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: refresh_account (GoaProvider *provider,
GoaClient *client,
GoaObject *object,
GtkWindow *parent,
GError **error)
{
AddAccountData data;
GVariantBuilder builder;
GoaAccount *account;
GoaEwsClient *ews_client;
GoaExchange *exchange;
GtkWidget *dialog;
GtkWidget *vbox;
gboolean ret;
const gchar *email_address;
const gchar *server;
const gchar *password;
const gchar *username;
gint response;
g_return_val_if_fail (GOA_IS_EXCHANGE_PROVIDER (provider), FALSE);
g_return_val_if_fail (GOA_IS_CLIENT (client), FALSE);
g_return_val_if_fail (GOA_IS_OBJECT (object), FALSE);
g_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
ews_client = NULL;
ret = FALSE;
dialog = gtk_dialog_new_with_buttons (NULL,
parent,
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
NULL);
gtk_container_set_border_width (GTK_CONTAINER (dialog), 12);
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
vbox = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
gtk_box_set_spacing (GTK_BOX (vbox), 12);
memset (&data, 0, sizeof (AddAccountData));
data.loop = g_main_loop_new (NULL, FALSE);
data.dialog = GTK_DIALOG (dialog);
data.error = NULL;
create_account_details_ui (provider, GTK_DIALOG (dialog), GTK_BOX (vbox), FALSE, &data);
account = goa_object_peek_account (object);
email_address = goa_account_get_presentation_identity (account);
gtk_entry_set_text (GTK_ENTRY (data.email_address), email_address);
gtk_editable_set_editable (GTK_EDITABLE (data.email_address), FALSE);
gtk_widget_show_all (dialog);
ews_client = goa_ews_client_new ();
ews_again:
response = gtk_dialog_run (GTK_DIALOG (dialog));
if (response != GTK_RESPONSE_OK)
{
g_set_error (error,
GOA_ERROR,
GOA_ERROR_DIALOG_DISMISSED,
_("Dialog was dismissed"));
goto out;
}
password = gtk_entry_get_text (GTK_ENTRY (data.password));
username = goa_account_get_identity (account);
exchange = goa_object_peek_exchange (object);
server = goa_exchange_get_host (exchange);
goa_ews_client_autodiscover (ews_client,
email_address,
password,
username,
server,
NULL,
autodiscover_cb,
&data);
goa_spinner_button_start (GOA_SPINNER_BUTTON (data.spinner_button));
g_main_loop_run (data.loop);
if (data.error != NULL)
{
GtkWidget *button;
gchar *markup;
markup = g_strdup_printf ("<b>%s:</b> %s",
_("Error connecting to Microsoft Exchange server"),
data.error->message);
g_clear_error (&data.error);
gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
g_free (markup);
button = gtk_dialog_get_widget_for_response (data.dialog, GTK_RESPONSE_OK);
gtk_button_set_label (GTK_BUTTON (button), _("_Try Again"));
gtk_widget_set_no_show_all (data.cluebar, FALSE);
gtk_widget_show_all (data.cluebar);
goto ews_again;
}
/* TODO: run in worker thread */
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "password", g_variant_new_string (password));
if (!goa_utils_store_credentials_for_object_sync (provider,
object,
g_variant_builder_end (&builder),
NULL, /* GCancellable */
error))
goto out;
goa_account_call_ensure_credentials (account,
NULL, /* GCancellable */
NULL, NULL); /* callback, user_data */
ret = TRUE;
out:
gtk_widget_destroy (dialog);
if (data.loop != NULL)
g_main_loop_unref (data.loop);
if (ews_client != NULL)
g_object_unref (ews_client);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
int j, loops = server.cronloops++;
REDIS_NOTUSED(eventLoop);
REDIS_NOTUSED(id);
REDIS_NOTUSED(clientData);
/* We take a cached value of the unix time in the global state because
* with virtual memory and aging there is to store the current time
* in objects at every object access, and accuracy is not needed.
* To access a global var is faster than calling time(NULL) */
server.unixtime = time(NULL);
/* We have just 22 bits per object for LRU information.
* So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
* 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
*
* Note that even if this will wrap after 1.5 years it's not a problem,
* everything will still work but just some object will appear younger
* to Redis. But for this to happen a given object should never be touched
* for 1.5 years.
*
* Note that you can change the resolution altering the
* REDIS_LRU_CLOCK_RESOLUTION define.
*/
updateLRUClock();
/* We received a SIGTERM, shutting down here in a safe way, as it is
* not ok doing so inside the signal handler. */
if (server.shutdown_asap) {
if (prepareForShutdown() == REDIS_OK) exit(0);
redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
}
/* Show some info about non-empty databases */
for (j = 0; j < server.dbnum; j++) {
long long size, used, vkeys;
size = dictSlots(server.db[j].dict);
used = dictSize(server.db[j].dict);
vkeys = dictSize(server.db[j].expires);
if (!(loops % 50) && (used || vkeys)) {
redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
/* dictPrintStats(server.dict); */
}
}
/* We don't want to resize the hash tables while a bacground saving
* is in progress: the saving child is created using fork() that is
* implemented with a copy-on-write semantic in most modern systems, so
* if we resize the HT while there is the saving child at work actually
* a lot of memory movements in the parent will cause a lot of pages
* copied. */
if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
if (!(loops % 10)) tryResizeHashTables();
if (server.activerehashing) incrementallyRehash();
}
/* Show information about connected clients */
if (!(loops % 50)) {
redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
listLength(server.clients)-listLength(server.slaves),
listLength(server.slaves),
zmalloc_used_memory());
}
/* Close connections of timedout clients */
if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
closeTimedoutClients();
/* Check if a background saving or AOF rewrite in progress terminated */
if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
int statloc;
pid_t pid;
if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
if (pid == server.bgsavechildpid) {
backgroundSaveDoneHandler(statloc);
} else {
backgroundRewriteDoneHandler(statloc);
}
updateDictResizePolicy();
}
} else {
/* If there is not a background saving in progress check if
* we have to save now */
time_t now = time(NULL);
for (j = 0; j < server.saveparamslen; j++) {
struct saveparam *sp = server.saveparams+j;
if (server.dirty >= sp->changes &&
now-server.lastsave > sp->seconds) {
redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
sp->changes, sp->seconds);
rdbSaveBackground(server.dbfilename);
break;
}
}
}
/* Expire a few keys per cycle, only if this is a master.
* On slaves we wait for DEL operations synthesized by the master
* in order to guarantee a strict consistency. */
if (server.masterhost == NULL) activeExpireCycle();
/* Swap a few keys on disk if we are over the memory limit and VM
* is enbled. Try to free objects from the free list first. */
if (vmCanSwapOut()) {
while (server.vm_enabled && zmalloc_used_memory() >
server.vm_max_memory)
{
int retval = (server.vm_max_threads == 0) ?
vmSwapOneObjectBlocking() :
vmSwapOneObjectThreaded();
if (retval == REDIS_ERR && !(loops % 300) &&
zmalloc_used_memory() >
(server.vm_max_memory+server.vm_max_memory/10))
{
redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
}
/* Note that when using threade I/O we free just one object,
* because anyway when the I/O thread in charge to swap this
* object out will finish, the handler of completed jobs
* will try to swap more objects if we are still out of memory. */
if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
}
}
/* Replication cron function -- used to reconnect to master and
* to detect transfer failures. */
if (!(loops % 10)) replicationCron();
return 100;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PHP_FUNCTION(openssl_encrypt)
{
zend_bool raw_output = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0, max_iv_len;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {
return;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
max_iv_len = EVP_CIPHER_iv_length(cipher_type);
if (iv_len <= 0 && max_iv_len > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
if (data_len > 0) {
EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
}
outlen = i;
if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
if (raw_output) {
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
int base64_str_len;
char *base64_str;
base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
efree(outbuf);
RETVAL_STRINGL(base64_str, base64_str_len, 0);
}
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fix bug #61413 ext\openssl\tests\openssl_encrypt_crash.phpt fails 5.3 only'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type,
record_parameters_st * params)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
unsigned int pad;
int length;
uint16_t blocksize;
int ret, i, pad_failed = 0;
opaque preamble[PREAMBLE_SIZE];
int preamble_size;
int ver = gnutls_protocol_get_version (session);
int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm);
blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
/* actual decryption (inplace)
*/
switch (_gnutls_cipher_is_block (params->cipher_algorithm))
{
case CIPHER_STREAM:
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (_gnutls_version_has_explicit_iv
(session->security_parameters.version))
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
}
if (ciphertext.size < hash_size)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
pad = ciphertext.data[ciphertext.size - 1]; /* pad */
/* Check the pading bytes (TLS 1.x).
* Note that we access all 256 bytes of ciphertext for padding check
* because there is a timing channel in that memory access (in certain CPUs).
*/
if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0)
for (i = 2; i <= pad; i++)
{
if (ciphertext.data[ciphertext.size - i] !=
ciphertext.data[ciphertext.size - 1])
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
if (pad_failed)
pad = 0;
length = ciphertext.size - hash_size - pad;
break;
default:
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (params->mac_algorithm != GNUTLS_MAC_NULL)
{
digest_hd_st td;
ret = mac_init (&td, params->mac_algorithm,
params->read.mac_secret.data,
params->read.mac_secret.size, ver);
if (ret < 0)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
preamble_size =
make_preamble (UINT64DATA
(params->read.sequence_number), type,
c_length, ver, preamble);
mac_hash (&td, preamble, preamble_size, ver);
if (length > 0)
mac_hash (&td, ciphertext.data, length, ver);
mac_deinit (&td, MAC, ver);
}
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0 || pad_failed != 0)
{
gnutls_datum_t compressed = {compress_data, compress_size};
/* HMAC was not the same. */
dummy_wait(params, &compressed, pad_failed, pad, length+preamble_size);
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compressed_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'corrected fix'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int btrfs_add_link(struct btrfs_trans_handle *trans,
struct inode *parent_inode, struct inode *inode,
const char *name, int name_len, int add_backref, u64 index)
{
int ret = 0;
struct btrfs_key key;
struct btrfs_root *root = BTRFS_I(parent_inode)->root;
u64 ino = btrfs_ino(inode);
u64 parent_ino = btrfs_ino(parent_inode);
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
} else {
key.objectid = ino;
btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
key.offset = 0;
}
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, index, name, name_len);
} else if (add_backref) {
ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
parent_ino, index);
}
/* Nothing to clean up yet */
if (ret)
return ret;
ret = btrfs_insert_dir_item(trans, root, name, name_len,
parent_inode, &key,
btrfs_inode_type(inode), index);
if (ret == -EEXIST)
goto fail_dir_item;
else if (ret) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
btrfs_i_size_write(parent_inode, parent_inode->i_size +
name_len * 2);
inode_inc_iversion(parent_inode);
parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode(trans, root, parent_inode);
if (ret)
btrfs_abort_transaction(trans, root, ret);
return ret;
fail_dir_item:
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
u64 local_index;
int err;
err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, &local_index, name, name_len);
} else if (add_backref) {
u64 local_index;
int err;
err = btrfs_del_inode_ref(trans, root, name, name_len,
ino, parent_ino, &local_index);
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <chris.mason@fusionio.com>
Reported-by: Pascal Junod <pascal@junod.info>'</s> |
<s>[INST] Given the following code containing errors, provide 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 cipso_v4_validate(const struct sk_buff *skb, unsigned char **option)
{
unsigned char *opt = *option;
unsigned char *tag;
unsigned char opt_iter;
unsigned char err_offset = 0;
u8 opt_len;
u8 tag_len;
struct cipso_v4_doi *doi_def = NULL;
u32 tag_iter;
/* caller already checks for length values that are too large */
opt_len = opt[1];
if (opt_len < 8) {
err_offset = 1;
goto validate_return;
}
rcu_read_lock();
doi_def = cipso_v4_doi_search(get_unaligned_be32(&opt[2]));
if (doi_def == NULL) {
err_offset = 2;
goto validate_return_locked;
}
opt_iter = CIPSO_V4_HDR_LEN;
tag = opt + opt_iter;
while (opt_iter < opt_len) {
for (tag_iter = 0; doi_def->tags[tag_iter] != tag[0];)
if (doi_def->tags[tag_iter] == CIPSO_V4_TAG_INVALID ||
++tag_iter == CIPSO_V4_TAG_MAXCNT) {
err_offset = opt_iter;
goto validate_return_locked;
}
tag_len = tag[1];
if (tag_len > (opt_len - opt_iter)) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
switch (tag[0]) {
case CIPSO_V4_TAG_RBITMAP:
if (tag_len < CIPSO_V4_TAG_RBM_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
/* We are already going to do all the verification
* necessary at the socket layer so from our point of
* view it is safe to turn these checks off (and less
* work), however, the CIPSO draft says we should do
* all the CIPSO validations here but it doesn't
* really specify _exactly_ what we need to validate
* ... so, just make it a sysctl tunable. */
if (cipso_v4_rbm_strictvalid) {
if (cipso_v4_map_lvl_valid(doi_def,
tag[3]) < 0) {
err_offset = opt_iter + 3;
goto validate_return_locked;
}
if (tag_len > CIPSO_V4_TAG_RBM_BLEN &&
cipso_v4_map_cat_rbm_valid(doi_def,
&tag[4],
tag_len - 4) < 0) {
err_offset = opt_iter + 4;
goto validate_return_locked;
}
}
break;
case CIPSO_V4_TAG_ENUM:
if (tag_len < CIPSO_V4_TAG_ENUM_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
if (cipso_v4_map_lvl_valid(doi_def,
tag[3]) < 0) {
err_offset = opt_iter + 3;
goto validate_return_locked;
}
if (tag_len > CIPSO_V4_TAG_ENUM_BLEN &&
cipso_v4_map_cat_enum_valid(doi_def,
&tag[4],
tag_len - 4) < 0) {
err_offset = opt_iter + 4;
goto validate_return_locked;
}
break;
case CIPSO_V4_TAG_RANGE:
if (tag_len < CIPSO_V4_TAG_RNG_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
if (cipso_v4_map_lvl_valid(doi_def,
tag[3]) < 0) {
err_offset = opt_iter + 3;
goto validate_return_locked;
}
if (tag_len > CIPSO_V4_TAG_RNG_BLEN &&
cipso_v4_map_cat_rng_valid(doi_def,
&tag[4],
tag_len - 4) < 0) {
err_offset = opt_iter + 4;
goto validate_return_locked;
}
break;
case CIPSO_V4_TAG_LOCAL:
/* This is a non-standard tag that we only allow for
* local connections, so if the incoming interface is
* not the loopback device drop the packet. */
if (!(skb->dev->flags & IFF_LOOPBACK)) {
err_offset = opt_iter;
goto validate_return_locked;
}
if (tag_len != CIPSO_V4_TAG_LOC_BLEN) {
err_offset = opt_iter + 1;
goto validate_return_locked;
}
break;
default:
err_offset = opt_iter;
goto validate_return_locked;
}
tag += tag_len;
opt_iter += tag_len;
}
validate_return_locked:
rcu_read_unlock();
validate_return:
*option = opt + err_offset;
return err_offset;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'cipso: don't follow a NULL pointer when setsockopt() is called
As reported by Alan Cox, and verified by Lin Ming, when a user
attempts to add a CIPSO option to a socket using the CIPSO_V4_TAG_LOCAL
tag the kernel dies a terrible death when it attempts to follow a NULL
pointer (the skb argument to cipso_v4_validate() is NULL when called via
the setsockopt() syscall).
This patch fixes this by first checking to ensure that the skb is
non-NULL before using it to find the incoming network interface. In
the unlikely case where the skb is NULL and the user attempts to add
a CIPSO option with the _TAG_LOCAL tag we return an error as this is
not something we want to allow.
A simple reproducer, kindly supplied by Lin Ming, although you must
have the CIPSO DOI #3 configure on the system first or you will be
caught early in cipso_v4_validate():
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <string.h>
struct local_tag {
char type;
char length;
char info[4];
};
struct cipso {
char type;
char length;
char doi[4];
struct local_tag local;
};
int main(int argc, char **argv)
{
int sockfd;
struct cipso cipso = {
.type = IPOPT_CIPSO,
.length = sizeof(struct cipso),
.local = {
.type = 128,
.length = sizeof(struct local_tag),
},
};
memset(cipso.doi, 0, 4);
cipso.doi[3] = 3;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
#define SOL_IP 0
setsockopt(sockfd, SOL_IP, IP_OPTIONS,
&cipso, sizeof(struct cipso));
return 0;
}
CC: Lin Ming <mlin@ss.pku.edu.cn>
Reported-by: Alan Cox <alan@lxorguk.ukuu.org.uk>
Signed-off-by: Paul Moore <pmoore@redhat.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 kvm_set_guest_paused(struct kvm_vcpu *vcpu)
{
if (!vcpu->arch.time_page)
return -EINVAL;
vcpu->arch.pvclock_set_guest_stopped_request = true;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)
There is a potential use after free issue with the handling of
MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable
memory such as frame buffers then KVM might continue to write to that
address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins
the page in memory so it's unlikely to cause an issue, but if the user
space component re-purposes the memory previously used for the guest, then
the guest will be able to corrupt that memory.
Tested: Tested against kvmclock unit test
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: php_libxml_input_buffer_create_filename(const char *URI, xmlCharEncoding enc)
{
xmlParserInputBufferPtr ret;
void *context = NULL;
if (URI == NULL)
return(NULL);
context = php_libxml_streams_IO_open_read_wrapper(URI);
if (context == NULL) {
return(NULL);
}
/* Allocate the Input buffer front-end. */
ret = xmlAllocParserInputBuffer(enc);
if (ret != NULL) {
ret->context = context;
ret->readcallback = php_libxml_streams_IO_read;
ret->closecallback = php_libxml_streams_IO_close;
} else
php_libxml_streams_IO_close(context);
return(ret);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int dcbnl_ieee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *ieee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx;
int err;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
return -EMSGSIZE;
ieee = nla_nest_start(skb, DCB_ATTR_IEEE);
if (!ieee)
return -EMSGSIZE;
if (ops->ieee_getets) {
struct ieee_ets ets;
err = ops->ieee_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_getmaxrate) {
struct ieee_maxrate maxrate;
err = ops->ieee_getmaxrate(netdev, &maxrate);
if (!err) {
err = nla_put(skb, DCB_ATTR_IEEE_MAXRATE,
sizeof(maxrate), &maxrate);
if (err)
return -EMSGSIZE;
}
}
if (ops->ieee_getpfc) {
struct ieee_pfc pfc;
err = ops->ieee_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
app = nla_nest_start(skb, DCB_ATTR_IEEE_APP_TABLE);
if (!app)
return -EMSGSIZE;
spin_lock(&dcb_lock);
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
err = nla_put(skb, DCB_ATTR_IEEE_APP, sizeof(itr->app),
&itr->app);
if (err) {
spin_unlock(&dcb_lock);
return -EMSGSIZE;
}
}
}
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
nla_nest_end(skb, app);
/* get peer info if available */
if (ops->ieee_peer_getets) {
struct ieee_ets ets;
err = ops->ieee_peer_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_peer_getpfc) {
struct ieee_pfc pfc;
err = ops->ieee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_IEEE_PEER_APP,
DCB_ATTR_IEEE_APP_UNSPEC,
DCB_ATTR_IEEE_APP);
if (err)
return -EMSGSIZE;
}
nla_nest_end(skb, ieee);
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
return -EMSGSIZE;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'dcbnl: fix various netlink info leaks
The dcb netlink interface leaks stack memory in various places:
* perm_addr[] buffer is only filled at max with 12 of the 32 bytes but
copied completely,
* no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand,
so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes
for ieee_pfc structs, etc.,
* the same is true for CEE -- no in-kernel driver fills the whole
struct,
Prevent all of the above stack info leaks by properly initializing the
buffers/structures involved.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide 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 *create_directory_config(apr_pool_t *mp, char *path)
{
directory_config *dcfg = (directory_config *)apr_pcalloc(mp, sizeof(directory_config));
if (dcfg == NULL) return NULL;
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Created directory config %pp path %s", dcfg, path);
#endif
dcfg->mp = mp;
dcfg->is_enabled = NOT_SET;
dcfg->reqbody_access = NOT_SET;
dcfg->reqintercept_oe = NOT_SET;
dcfg->reqbody_buffering = NOT_SET;
dcfg->reqbody_inmemory_limit = NOT_SET;
dcfg->reqbody_limit = NOT_SET;
dcfg->reqbody_no_files_limit = NOT_SET;
dcfg->resbody_access = NOT_SET;
dcfg->debuglog_name = NOT_SET_P;
dcfg->debuglog_level = NOT_SET;
dcfg->debuglog_fd = NOT_SET_P;
dcfg->of_limit = NOT_SET;
dcfg->if_limit_action = NOT_SET;
dcfg->of_limit_action = NOT_SET;
dcfg->of_mime_types = NOT_SET_P;
dcfg->of_mime_types_cleared = NOT_SET;
dcfg->cookie_format = NOT_SET;
dcfg->argument_separator = NOT_SET;
dcfg->cookiev0_separator = NOT_SET_P;
dcfg->rule_inheritance = NOT_SET;
dcfg->rule_exceptions = apr_array_make(mp, 16, sizeof(rule_exception *));
dcfg->hash_method = apr_array_make(mp, 16, sizeof(hash_method *));
/* audit log variables */
dcfg->auditlog_flag = NOT_SET;
dcfg->auditlog_type = NOT_SET;
dcfg->max_rule_time = NOT_SET;
dcfg->auditlog_dirperms = NOT_SET;
dcfg->auditlog_fileperms = NOT_SET;
dcfg->auditlog_name = NOT_SET_P;
dcfg->auditlog2_name = NOT_SET_P;
dcfg->auditlog_fd = NOT_SET_P;
dcfg->auditlog2_fd = NOT_SET_P;
dcfg->auditlog_storage_dir = NOT_SET_P;
dcfg->auditlog_parts = NOT_SET_P;
dcfg->auditlog_relevant_regex = NOT_SET_P;
dcfg->ruleset = NULL;
/* Upload */
dcfg->tmp_dir = NOT_SET_P;
dcfg->upload_dir = NOT_SET_P;
dcfg->upload_keep_files = NOT_SET;
dcfg->upload_validates_files = NOT_SET;
dcfg->upload_filemode = NOT_SET;
dcfg->upload_file_limit = NOT_SET;
/* These are only used during the configuration process. */
dcfg->tmp_chain_starter = NULL;
dcfg->tmp_default_actionset = NULL;
dcfg->tmp_rule_placeholders = NULL;
/* Misc */
dcfg->data_dir = NOT_SET_P;
dcfg->webappid = NOT_SET_P;
dcfg->sensor_id = NOT_SET_P;
dcfg->httpBlkey = NOT_SET_P;
/* Content injection. */
dcfg->content_injection_enabled = NOT_SET;
/* Stream inspection */
dcfg->stream_inbody_inspection = NOT_SET;
dcfg->stream_outbody_inspection = NOT_SET;
/* Geo Lookups */
dcfg->geo = NOT_SET_P;
/* Gsb Lookups */
dcfg->gsb = NOT_SET_P;
/* Unicode Map */
dcfg->u_map = NOT_SET_P;
/* Cache */
dcfg->cache_trans = NOT_SET;
dcfg->cache_trans_incremental = NOT_SET;
dcfg->cache_trans_min = NOT_SET;
dcfg->cache_trans_max = NOT_SET;
dcfg->cache_trans_maxitems = NOT_SET;
/* Rule ids */
dcfg->rule_id_htab = apr_hash_make(mp);
dcfg->component_signatures = apr_array_make(mp, 16, sizeof(char *));
dcfg->request_encoding = NOT_SET_P;
dcfg->disable_backend_compression = NOT_SET;
/* Collection timeout */
dcfg->col_timeout = NOT_SET;
dcfg->crypto_key = NOT_SET_P;
dcfg->crypto_key_len = NOT_SET;
dcfg->crypto_key_add = NOT_SET;
dcfg->crypto_param_name = NOT_SET_P;
dcfg->hash_is_enabled = NOT_SET;
dcfg->hash_enforcement = NOT_SET;
dcfg->crypto_hash_href_rx = NOT_SET;
dcfg->crypto_hash_faction_rx = NOT_SET;
dcfg->crypto_hash_location_rx = NOT_SET;
dcfg->crypto_hash_iframesrc_rx = NOT_SET;
dcfg->crypto_hash_framesrc_rx = NOT_SET;
dcfg->crypto_hash_href_pm = NOT_SET;
dcfg->crypto_hash_faction_pm = NOT_SET;
dcfg->crypto_hash_location_pm = NOT_SET;
dcfg->crypto_hash_iframesrc_pm = NOT_SET;
dcfg->crypto_hash_framesrc_pm = NOT_SET;
return dcfg;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-611'], 'message': 'Added SecXmlExternalEntity'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE, mem->userspace_addr, mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = &kvm->memslots->memslots[mem->slot];
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
}
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
slots->memslots[mem->slot] = new;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'KVM: add missing void __user * cast to access_ok() call
fa3d315a "KVM: Validate userspace_addr of memslot when registered" introduced
this new warning onn s390:
kvm_main.c: In function '__kvm_set_memory_region':
kvm_main.c:654:7: warning: passing argument 1 of '__access_ok' makes pointer from integer without a cast
arch/s390/include/asm/uaccess.h:53:19: note: expected 'const void *' but argument is of type '__u64'
Add the missing cast to get rid of it again...
Cc: Takuya Yoshikawa <yoshikawa.takuya@oss.ntt.co.jp>
Signed-off-by: Heiko Carstens <heiko.carstens@de.ibm.com>
Signed-off-by: Avi Kivity <avi@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide 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 pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj)
{
char fullname[NAME_MAX + 1];
int fout;
off_t sum = 0;
int rc = CL_SUCCESS;
char *ascii_decoded = NULL;
int dump = 1;
/* TODO: call bytecode hook here, allow override dumpability */
if ((!(obj->flags & (1 << OBJ_STREAM)) ||
(obj->flags & (1 << OBJ_HASFILTERS)))
&& !(obj->flags & DUMP_MASK)) {
/* don't dump all streams */
dump = 0;
}
if ((obj->flags & (1 << OBJ_IMAGE)) &&
!(obj->flags & (1 << OBJ_FILTER_DCT))) {
/* don't dump / scan non-JPG images */
dump = 0;
}
if (obj->flags & (1 << OBJ_FORCEDUMP)) {
/* bytecode can force dump by setting this flag */
dump = 1;
}
if (!dump)
return CL_CLEAN;
cli_dbgmsg("cli_pdf: dumping obj %u %u\n", obj->id>>8, obj->id);
snprintf(fullname, sizeof(fullname), "%s"PATHSEP"pdf%02u", pdf->dir, pdf->files++);
fout = open(fullname,O_RDWR|O_CREAT|O_EXCL|O_TRUNC|O_BINARY, 0600);
if (fout < 0) {
char err[128];
cli_errmsg("cli_pdf: can't create temporary file %s: %s\n", fullname, cli_strerror(errno, err, sizeof(err)));
free(ascii_decoded);
return CL_ETMPFILE;
}
do {
if (obj->flags & (1 << OBJ_STREAM)) {
const char *start = pdf->map + obj->start;
off_t p_stream = 0, p_endstream = 0;
off_t length;
find_stream_bounds(start, pdf->size - obj->start,
pdf->size - obj->start,
&p_stream, &p_endstream);
if (p_stream && p_endstream) {
const char *flate_in;
long ascii_decoded_size = 0;
size_t size = p_endstream - p_stream;
off_t orig_length;
length = find_length(pdf, obj, start, p_stream);
if (length < 0)
length = 0;
orig_length = length;
if (length > pdf->size || obj->start + p_stream + length > pdf->size) {
cli_dbgmsg("cli_pdf: length out of file: %ld + %ld > %ld\n",
p_stream, length, pdf->size);
length = pdf->size - (obj->start + p_stream);
}
if (!(obj->flags & (1 << OBJ_FILTER_FLATE)) && length <= 0) {
const char *q = start + p_endstream;
length = size;
q--;
if (*q == '\n') {
q--;
length--;
if (*q == '\r')
length--;
} else if (*q == '\r') {
length--;
}
if (length < 0)
length = 0;
cli_dbgmsg("cli_pdf: calculated length %ld\n", length);
} else {
if (size > length+2) {
cli_dbgmsg("cli_pdf: calculated length %ld < %ld\n",
length, size);
length = size;
}
}
if (orig_length && size > orig_length + 20) {
cli_dbgmsg("cli_pdf: orig length: %ld, length: %ld, size: %ld\n",
orig_length, length, size);
pdfobj_flag(pdf, obj, BAD_STREAMLEN);
}
if (!length)
length = size;
if (obj->flags & (1 << OBJ_FILTER_AH)) {
ascii_decoded = cli_malloc(length/2 + 1);
if (!ascii_decoded) {
cli_errmsg("Cannot allocate memory for asciidecode\n");
rc = CL_EMEM;
break;
}
ascii_decoded_size = asciihexdecode(start + p_stream,
length,
ascii_decoded);
} else if (obj->flags & (1 << OBJ_FILTER_A85)) {
ascii_decoded = cli_malloc(length*5);
if (!ascii_decoded) {
cli_errmsg("Cannot allocate memory for asciidecode\n");
rc = CL_EMEM;
break;
}
ascii_decoded_size = ascii85decode(start+p_stream,
length,
(unsigned char*)ascii_decoded);
}
if (ascii_decoded_size < 0) {
/* don't flag for images or truncated objs*/
if (!(obj->flags &
((1 << OBJ_IMAGE) | (1 << OBJ_TRUNCATED))))
pdfobj_flag(pdf, obj, BAD_ASCIIDECODE);
cli_dbgmsg("cli_pdf: failed to asciidecode in %u %u obj\n", obj->id>>8,obj->id&0xff);
free(ascii_decoded);
ascii_decoded = NULL;
/* attempt to directly flatedecode it */
}
/* either direct or ascii-decoded input */
if (!ascii_decoded)
ascii_decoded_size = length;
flate_in = ascii_decoded ? ascii_decoded : start+p_stream;
if (obj->flags & (1 << OBJ_FILTER_FLATE)) {
cli_dbgmsg("cli_pdf: deflate len %ld (orig %ld)\n", ascii_decoded_size, (long)orig_length);
rc = filter_flatedecode(pdf, obj, flate_in, ascii_decoded_size, fout, &sum);
} else {
if (filter_writen(pdf, obj, fout, flate_in, ascii_decoded_size, &sum) != ascii_decoded_size)
rc = CL_EWRITE;
}
}
} else if (obj->flags & (1 << OBJ_JAVASCRIPT)) {
const char *q2;
const char *q = pdf->map+obj->start;
/* TODO: get obj-endobj size */
off_t bytesleft = obj_size(pdf, obj, 0);
if (bytesleft < 0)
break;
q2 = cli_memstr(q, bytesleft, "/JavaScript", 11);
if (!q2)
break;
bytesleft -= q2 - q;
do {
q2++;
bytesleft--;
q = pdf_nextobject(q2, bytesleft);
if (!q)
break;
bytesleft -= q - q2;
q2 = q;
} while (*q == '/');
if (!q)
break;
if (*q == '(') {
if (filter_writen(pdf, obj, fout, q+1, bytesleft-1, &sum) != (bytesleft-1)) {
rc = CL_EWRITE;
break;
}
} else if (*q == '<') {
char *decoded;
q2 = memchr(q+1, '>', bytesleft);
if (!q2) q2 = q + bytesleft;
decoded = cli_malloc(q2 - q);
if (!decoded) {
rc = CL_EMEM;
break;
}
cli_hex2str_to(q2, decoded, q2-q-1);
decoded[q2-q-1] = '\0';
cli_dbgmsg("cli_pdf: found hexadecimal encoded javascript in %u %u obj\n",
obj->id>>8, obj->id&0xff);
pdfobj_flag(pdf, obj, HEX_JAVASCRIPT);
filter_writen(pdf, obj, fout, decoded, q2-q-1, &sum);
free(decoded);
}
} else {
off_t bytesleft = obj_size(pdf, obj, 0);
if (filter_writen(pdf, obj, fout , pdf->map + obj->start, bytesleft,&sum) != bytesleft)
rc = CL_EWRITE;
}
} while (0);
cli_dbgmsg("cli_pdf: extracted %ld bytes %u %u obj to %s\n", sum, obj->id>>8, obj->id&0xff, fullname);
if (sum) {
int rc2;
cli_updatelimits(pdf->ctx, sum);
/* TODO: invoke bytecode on this pdf obj with metainformation associated
* */
lseek(fout, 0, SEEK_SET);
rc2 = cli_magic_scandesc(fout, pdf->ctx);
if (rc2 == CL_VIRUS || rc == CL_SUCCESS)
rc = rc2;
if (rc == CL_CLEAN) {
rc2 = run_pdf_hooks(pdf, PDF_PHASE_POSTDUMP, fout, obj - pdf->objs);
if (rc2 == CL_VIRUS)
rc = rc2;
}
}
close(fout);
free(ascii_decoded);
if (!pdf->ctx->engine->keeptmp)
if (cli_unlink(fullname) && rc != CL_VIRUS)
rc = CL_EUNLINK;
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-189', 'CWE-79'], 'message': 'pdf: bb #7053'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag)
{
rb_encoding *enc;
VALUE w;
long width, len, flen = 1, fclen = 1;
VALUE res;
char *p;
const char *f = " ";
long n, llen, rlen;
volatile VALUE pad;
int singlebyte = 1, cr;
rb_scan_args(argc, argv, "11", &w, &pad);
enc = STR_ENC_GET(str);
width = NUM2LONG(w);
if (argc == 2) {
StringValue(pad);
enc = rb_enc_check(str, pad);
f = RSTRING_PTR(pad);
flen = RSTRING_LEN(pad);
fclen = str_strlen(pad, enc);
singlebyte = single_byte_optimizable(pad);
if (flen == 0 || fclen == 0) {
rb_raise(rb_eArgError, "zero width padding");
}
}
len = str_strlen(str, enc);
if (width < 0 || len >= width) return rb_str_dup(str);
n = width - len;
llen = (jflag == 'l') ? 0 : ((jflag == 'r') ? n : n/2);
rlen = n - llen;
cr = ENC_CODERANGE(str);
res = rb_str_new5(str, 0, RSTRING_LEN(str)+n*flen/fclen+2);
p = RSTRING_PTR(res);
while (llen) {
if (flen <= 1) {
*p++ = *f;
llen--;
}
else if (llen > fclen) {
memcpy(p,f,flen);
p += flen;
llen -= fclen;
}
else {
char *fp = str_nth(f, f+flen, llen, enc, singlebyte);
n = fp - f;
memcpy(p,f,n);
p+=n;
break;
}
}
memcpy(p, RSTRING_PTR(str), RSTRING_LEN(str));
p+=RSTRING_LEN(str);
while (rlen) {
if (flen <= 1) {
*p++ = *f;
rlen--;
}
else if (rlen > fclen) {
memcpy(p,f,flen);
p += flen;
rlen -= fclen;
}
else {
char *fp = str_nth(f, f+flen, rlen, enc, singlebyte);
n = fp - f;
memcpy(p,f,n);
p+=n;
break;
}
}
*p = '\0';
STR_SET_LEN(res, p-RSTRING_PTR(res));
OBJ_INFECT(res, str);
if (!NIL_P(pad)) OBJ_INFECT(res, pad);
rb_enc_associate(res, enc);
if (argc == 2)
cr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad));
if (cr != ENC_CODERANGE_BROKEN)
ENC_CODERANGE_SET(res, cr);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': '* string.c (rb_str_justify): CVE-2009-4124.
Fixes a bug reported by
Emmanouel Kellinis <Emmanouel.Kellinis AT kpmg.co.uk>, KPMG London;
Patch by nobu.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@26038 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: guestfs___first_line_of_file (guestfs_h *g, const char *filename)
{
CLEANUP_FREE char **lines = NULL; /* sic: not CLEANUP_FREE_STRING_LIST */
int64_t size;
char *ret;
/* Don't trust guestfs_head_n not to break with very large files.
* Check the file size is something reasonable first.
*/
size = guestfs_filesize (g, filename);
if (size == -1)
/* guestfs_filesize failed and has already set error in handle */
return NULL;
if (size > MAX_SMALL_FILE_SIZE) {
error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
filename, size);
return NULL;
}
lines = guestfs_head_n (g, 1, filename);
if (lines == NULL)
return NULL;
if (lines[0] == NULL) {
guestfs___free_string_list (lines);
/* Empty file: Return an empty string as explained above. */
return safe_strdup (g, "");
}
/* lines[1] should be NULL because of '1' argument above ... */
ret = lines[0]; /* caller frees */
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'inspection: Fix double-free when certain guest files are empty.
The following commit:
commit 5a3da366268825b26b470cde35658b67c1d11cd4
Author: Richard W.M. Jones <rjones@redhat.com>
Date: Thu Jan 24 17:07:38 2013 +0000
inspect: Use CLEANUP_* macros in inspection code.
can cause a double-free along an error path when certain guest files
are empty where we expected those files to contain at least one line.
This causes virt-inspector to crash when run on these guests.
The following is a test case which demonstrates the crash.
`f20rawhidex64' is a Fedora guest, but with small adjustments to the
test you could use any Linux guest for this test.
$ qemu-img create -f qcow2 -b f20rawhidex64 /tmp/test.qcow2
Formatting '/tmp/test.qcow2', fmt=qcow2 size=21474836480 backing_file='f20rawhidex64' encryption=off cluster_size=65536 lazy_refcounts=off
$ guestfish -i -a /tmp/test.qcow2 -- rm /etc/redhat-release : touch /etc/redhat-release
$ virt-inspector /tmp/test.qcow2
*** glibc detected *** virt-inspector: double free or corruption (fasttop): 0x00007f18bc9925a0 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x34ecc7ca8e)[0x7f18b8e64a8e]
/lib64/libguestfs.so.0(+0x3f91898078)[0x7f18ba13c078]
/lib64/libguestfs.so.0(+0x3f91899761)[0x7f18ba13d761]
/lib64/libguestfs.so.0(+0x3f91896d12)[0x7f18ba13ad12]
/lib64/libguestfs.so.0(+0x3f91894140)[0x7f18ba138140]
/lib64/libguestfs.so.0(guestfs_inspect_os+0x35)[0x7f18ba0bcc35]
virt-inspector(main+0x547)[0x7f18ba7c57d7]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f18b8e09a05]
virt-inspector(+0x6665)[0x7f18ba7c7665]
This is a denial of service, but not likely to be exploitable.
(Found by Coverity)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result==1) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'fix bug #64660 - yyparse can return 2, not only 1'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void ZrtpStateClass::processEvent(Event_t *ev) {
char *msg, first, middle, last;
uint8_t *pkt;
parent->synchEnter();
event = ev;
if (event->type == ZrtpPacket) {
pkt = event->packet;
msg = (char *)pkt + 4;
first = tolower(*msg);
middle = tolower(*(msg+4));
last = tolower(*(msg+7));
// Sanity check of packet size for all states except WaitErrorAck.
if (!inState(WaitErrorAck)) {
uint16_t totalLength = *(uint16_t*)(pkt+2);
totalLength = zrtpNtohs(totalLength) * ZRTP_WORD_SIZE;
totalLength += 12 + sizeof(uint32_t); // 12 bytes is fixed header, uint32_t is CRC
if (totalLength != ev->length) {
fprintf(stderr, "Total length does not match received length: %d - %ld\n", totalLength, ev->length);
sendErrorPacket(MalformedPacket);
parent->synchLeave();
return;
}
}
// Check if this is an Error packet.
if (first == 'e' && middle =='r' && last == ' ') {
/*
* Process a received Error packet.
*
* In any case stop timer to prevent resending packets.
* Use callback method to prepare and get an ErrorAck packet.
* Modify event type to "ErrorPkt" and hand it over to current
* state for further processing.
*/
cancelTimer();
ZrtpPacketError epkt(pkt);
ZrtpPacketErrorAck* eapkt = parent->prepareErrorAck(&epkt);
parent->sendPacketZRTP(static_cast<ZrtpPacketBase *>(eapkt));
event->type = ErrorPkt;
}
else if (first == 'p' && middle == ' ' && last == ' ') {
ZrtpPacketPing ppkt(pkt);
ZrtpPacketPingAck* ppktAck = parent->preparePingAck(&ppkt);
parent->sendPacketZRTP(static_cast<ZrtpPacketBase *>(ppktAck));
parent->synchLeave();
return;
}
else if (first == 's' && last == 'y') {
uint32_t errorCode = 0;
ZrtpPacketSASrelay* srly = new ZrtpPacketSASrelay(pkt);
ZrtpPacketRelayAck* rapkt = parent->prepareRelayAck(srly, &errorCode);
parent->sendPacketZRTP(static_cast<ZrtpPacketBase *>(rapkt));
parent->synchLeave();
return;
}
}
/*
* Shut down protocol state engine: cancel outstanding timer, further
* processing in current state.
*/
else if (event->type == ZrtpClose) {
cancelTimer();
}
engine->processEvent(*this);
parent->synchLeave();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd
- limit length of memcpy
- limit number of offered algorithms in Hello packet
- length check in PING packet
- fix a small coding error'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Status AuthorizationSession::acquirePrivilegesFromPrivilegeDocument(
const std::string& dbname, const UserName& user, const BSONObj& privilegeDocument) {
if (!_authenticatedPrincipals.lookup(user)) {
return Status(ErrorCodes::UserNotFound,
mongoutils::str::stream()
<< "No authenticated principle found with name: "
<< user.getUser()
<< " from database "
<< user.getDB(),
0);
}
if (user.getUser() == internalSecurity.user) {
// Grant full access to internal user
ActionSet allActions;
allActions.addAllActions();
return acquirePrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE, allActions), user);
}
return _externalState->getAuthorizationManager().buildPrivilegeSet(dbname,
user,
privilegeDocument,
&_acquiredPrivileges);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user.
Uncorrected, this can cause replica set heartbeats to stall behind operations
that hold the read lock for a long time.'</s> |