instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void __exit pf_exit(void)
{
struct pf_unit *pf;
int unit;
unregister_blkdev(major, name);
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
if (pf->present)
del_gendisk(pf->disk);
blk_cleanup_queue(pf->disk->queue);
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
if (pf->present)
pi_release(pf->pi);
}
}
Commit Message: paride/pf: Fix potential NULL pointer dereference
Syzkaller report this:
pf: pf version 1.04, major 47, cluster 64, nice 0
pf: No ATAPI disk detected
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pf_init+0x7af/0x1000 [pf]
Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34
RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788
RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59
R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000
R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020
FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1e50000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp
c
ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp
td
glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace 7a818cf5f210d79e ]---
If alloc_disk fails in pf_init_units, pf->disk will be
NULL, however in pf_detect and pf_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-476 | static void __exit pf_exit(void)
{
struct pf_unit *pf;
int unit;
unregister_blkdev(major, name);
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
if (!pf->disk)
continue;
if (pf->present)
del_gendisk(pf->disk);
blk_cleanup_queue(pf->disk->queue);
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
if (pf->present)
pi_release(pf->pi);
}
}
| 169,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NavigateToAboutBlank() {
GURL about_blank(url::kAboutBlankURL);
content::NavigationController::LoadURLParams params(about_blank);
params.frame_tree_node_id = frame_tree_node_id_;
params.source_site_instance = parent_site_instance_;
params.is_renderer_initiated = true;
web_contents()->GetController().LoadURLWithParams(params);
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | NavigateToAboutBlank() {
| 173,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Bug: 12394
Change-Id: Ifa023ce70f7a2697bf151009b035a6e6cf8d5d90
Reviewed-on: https://code.wireshark.org/review/15169
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
| 169,967 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst,
const xmlChar *propName,
int mandatory,
int *hasProp, const xmlChar **nsName,
const xmlChar** localName)
{
const xmlChar *prop;
if (nsName)
*nsName = NULL;
if (localName)
*localName = NULL;
if (hasProp)
*hasProp = 0;
prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE);
if (prop == NULL) {
if (mandatory) {
xsltTransformError(NULL, style, inst,
"The attribute '%s' is missing.\n", propName);
style->errors++;
return;
}
} else {
const xmlChar *URI;
if (xmlValidateQName(prop, 0)) {
xsltTransformError(NULL, style, inst,
"The value '%s' of the attribute "
"'%s' is not a valid QName.\n", prop, propName);
style->errors++;
return;
} else {
/*
* @prop will be in the string dict afterwards, @URI not.
*/
URI = xsltGetQNameURI2(style, inst, &prop);
if (prop == NULL) {
style->errors++;
} else {
*localName = prop;
if (hasProp)
*hasProp = 1;
if (URI != NULL) {
/*
* Fixes bug #308441: Put the ns-name in the dict
* in order to pointer compare names during XPath's
* variable lookup.
*/
if (nsName)
*nsName = xmlDictLookup(style->dict, URI, -1);
/* comp->has_ns = 1; */
}
}
}
}
return;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst,
const xmlChar *propName,
int mandatory,
int *hasProp, const xmlChar **nsName,
const xmlChar** localName)
{
const xmlChar *prop;
if (nsName)
*nsName = NULL;
if (localName)
*localName = NULL;
if (hasProp)
*hasProp = 0;
prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE);
if (prop == NULL) {
if (mandatory) {
xsltTransformError(NULL, style, inst,
"The attribute '%s' is missing.\n", propName);
style->errors++;
return;
}
} else {
const xmlChar *URI;
if (xmlValidateQName(prop, 0)) {
xsltTransformError(NULL, style, inst,
"The value '%s' of the attribute "
"'%s' is not a valid QName.\n", prop, propName);
style->errors++;
return;
} else {
/*
* @prop will be in the string dict afterwards, @URI not.
*/
URI = xsltGetQNameURI2(style, inst, &prop);
if (prop == NULL) {
style->errors++;
} else {
if (localName)
*localName = prop;
if (hasProp)
*hasProp = 1;
if (URI != NULL) {
/*
* Fixes bug #308441: Put the ns-name in the dict
* in order to pointer compare names during XPath's
* variable lookup.
*/
if (nsName)
*nsName = xmlDictLookup(style->dict, URI, -1);
/* comp->has_ns = 1; */
}
}
}
}
return;
}
| 173,317 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXObject::isMultiline() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLTextAreaElement(*node))
return true;
if (hasEditableStyle(*node))
return true;
if (!isNativeTextControl() && !isNonNativeTextControl())
return false;
return equalIgnoringCase(getAttribute(aria_multilineAttr), "true");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXObject::isMultiline() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLTextAreaElement(*node))
return true;
if (hasEditableStyle(*node))
return true;
if (!isNativeTextControl() && !isNonNativeTextControl())
return false;
return equalIgnoringASCIICase(getAttribute(aria_multilineAttr), "true");
}
| 171,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GesturePoint::IsInsideManhattanSquare(const TouchEvent& event) const {
int manhattanDistance = abs(event.x() - first_touch_position_.x()) +
abs(event.y() - first_touch_position_.y());
return manhattanDistance < kMaximumTouchMoveInPixelsForClick;
}
Commit Message: Add setters for the aura gesture recognizer constants.
BUG=113227
TEST=none
Review URL: http://codereview.chromium.org/9372040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool GesturePoint::IsInsideManhattanSquare(const TouchEvent& event) const {
int manhattanDistance = abs(event.x() - first_touch_position_.x()) +
abs(event.y() - first_touch_position_.y());
return manhattanDistance <
GestureConfiguration::max_touch_move_in_pixels_for_click();
}
| 171,044 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) {
int i;
memset(cfg, 0, sizeof(cfg_t));
cfg->debug_file = stderr;
for (i = 0; i < argc; i++) {
if (strncmp(argv[i], "max_devices=", 12) == 0)
sscanf(argv[i], "max_devices=%u", &cfg->max_devs);
if (strcmp(argv[i], "manual") == 0)
cfg->manual = 1;
if (strcmp(argv[i], "debug") == 0)
cfg->debug = 1;
if (strcmp(argv[i], "nouserok") == 0)
cfg->nouserok = 1;
if (strcmp(argv[i], "openasuser") == 0)
cfg->openasuser = 1;
if (strcmp(argv[i], "alwaysok") == 0)
cfg->alwaysok = 1;
if (strcmp(argv[i], "interactive") == 0)
cfg->interactive = 1;
if (strcmp(argv[i], "cue") == 0)
cfg->cue = 1;
if (strcmp(argv[i], "nodetect") == 0)
cfg->nodetect = 1;
if (strncmp(argv[i], "authfile=", 9) == 0)
cfg->auth_file = argv[i] + 9;
if (strncmp(argv[i], "authpending_file=", 17) == 0)
cfg->authpending_file = argv[i] + 17;
if (strncmp(argv[i], "origin=", 7) == 0)
cfg->origin = argv[i] + 7;
if (strncmp(argv[i], "appid=", 6) == 0)
cfg->appid = argv[i] + 6;
if (strncmp(argv[i], "prompt=", 7) == 0)
cfg->prompt = argv[i] + 7;
if (strncmp (argv[i], "debug_file=", 11) == 0) {
const char *filename = argv[i] + 11;
if(strncmp (filename, "stdout", 6) == 0) {
cfg->debug_file = stdout;
}
else if(strncmp (filename, "stderr", 6) == 0) {
cfg->debug_file = stderr;
}
else if( strncmp (filename, "syslog", 6) == 0) {
cfg->debug_file = (FILE *)-1;
}
else {
struct stat st;
FILE *file;
if(lstat(filename, &st) == 0) {
if(S_ISREG(st.st_mode)) {
file = fopen(filename, "a");
if(file != NULL) {
cfg->debug_file = file;
}
}
}
}
}
}
if (cfg->debug) {
D(cfg->debug_file, "called.");
D(cfg->debug_file, "flags %d argc %d", flags, argc);
for (i = 0; i < argc; i++) {
D(cfg->debug_file, "argv[%d]=%s", i, argv[i]);
}
D(cfg->debug_file, "max_devices=%d", cfg->max_devs);
D(cfg->debug_file, "debug=%d", cfg->debug);
D(cfg->debug_file, "interactive=%d", cfg->interactive);
D(cfg->debug_file, "cue=%d", cfg->cue);
D(cfg->debug_file, "nodetect=%d", cfg->nodetect);
D(cfg->debug_file, "manual=%d", cfg->manual);
D(cfg->debug_file, "nouserok=%d", cfg->nouserok);
D(cfg->debug_file, "openasuser=%d", cfg->openasuser);
D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok);
D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)");
D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)");
D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)");
D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)");
D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)");
}
}
Commit Message: Do not leak file descriptor when doing exec
When opening a custom debug file, the descriptor would stay
open when calling exec and leak to the child process.
Make sure all files are opened with close-on-exec.
This fixes CVE-2019-12210.
Thanks to Matthias Gerstner of the SUSE Security Team for reporting
the issue.
CWE ID: CWE-200 | static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) {
struct stat st;
FILE *file = NULL;
int fd = -1;
int i;
memset(cfg, 0, sizeof(cfg_t));
cfg->debug_file = stderr;
for (i = 0; i < argc; i++) {
if (strncmp(argv[i], "max_devices=", 12) == 0)
sscanf(argv[i], "max_devices=%u", &cfg->max_devs);
if (strcmp(argv[i], "manual") == 0)
cfg->manual = 1;
if (strcmp(argv[i], "debug") == 0)
cfg->debug = 1;
if (strcmp(argv[i], "nouserok") == 0)
cfg->nouserok = 1;
if (strcmp(argv[i], "openasuser") == 0)
cfg->openasuser = 1;
if (strcmp(argv[i], "alwaysok") == 0)
cfg->alwaysok = 1;
if (strcmp(argv[i], "interactive") == 0)
cfg->interactive = 1;
if (strcmp(argv[i], "cue") == 0)
cfg->cue = 1;
if (strcmp(argv[i], "nodetect") == 0)
cfg->nodetect = 1;
if (strncmp(argv[i], "authfile=", 9) == 0)
cfg->auth_file = argv[i] + 9;
if (strncmp(argv[i], "authpending_file=", 17) == 0)
cfg->authpending_file = argv[i] + 17;
if (strncmp(argv[i], "origin=", 7) == 0)
cfg->origin = argv[i] + 7;
if (strncmp(argv[i], "appid=", 6) == 0)
cfg->appid = argv[i] + 6;
if (strncmp(argv[i], "prompt=", 7) == 0)
cfg->prompt = argv[i] + 7;
if (strncmp (argv[i], "debug_file=", 11) == 0) {
const char *filename = argv[i] + 11;
if(strncmp (filename, "stdout", 6) == 0) {
cfg->debug_file = stdout;
}
else if(strncmp (filename, "stderr", 6) == 0) {
cfg->debug_file = stderr;
}
else if( strncmp (filename, "syslog", 6) == 0) {
cfg->debug_file = (FILE *)-1;
}
else {
fd = open(filename, O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW | O_NOCTTY);
if (fd >= 0 && (fstat(fd, &st) == 0) && S_ISREG(st.st_mode)) {
file = fdopen(fd, "a");
if(file != NULL) {
cfg->debug_file = file;
cfg->is_custom_debug_file = 1;
file = NULL;
fd = -1;
}
}
}
}
}
if (cfg->debug) {
D(cfg->debug_file, "called.");
D(cfg->debug_file, "flags %d argc %d", flags, argc);
for (i = 0; i < argc; i++) {
D(cfg->debug_file, "argv[%d]=%s", i, argv[i]);
}
D(cfg->debug_file, "max_devices=%d", cfg->max_devs);
D(cfg->debug_file, "debug=%d", cfg->debug);
D(cfg->debug_file, "interactive=%d", cfg->interactive);
D(cfg->debug_file, "cue=%d", cfg->cue);
D(cfg->debug_file, "nodetect=%d", cfg->nodetect);
D(cfg->debug_file, "manual=%d", cfg->manual);
D(cfg->debug_file, "nouserok=%d", cfg->nouserok);
D(cfg->debug_file, "openasuser=%d", cfg->openasuser);
D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok);
D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)");
D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)");
D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)");
D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)");
D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)");
}
if (fd != -1)
close(fd);
if (file != NULL)
fclose(file);
}
| 169,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t ib_uverbs_write(struct file *filp, const char __user *buf,
size_t count, loff_t *pos)
{
struct ib_uverbs_file *file = filp->private_data;
struct ib_device *ib_dev;
struct ib_uverbs_cmd_hdr hdr;
__u32 command;
__u32 flags;
int srcu_key;
ssize_t ret;
if (count < sizeof hdr)
return -EINVAL;
if (copy_from_user(&hdr, buf, sizeof hdr))
return -EFAULT;
srcu_key = srcu_read_lock(&file->device->disassociate_srcu);
ib_dev = srcu_dereference(file->device->ib_dev,
&file->device->disassociate_srcu);
if (!ib_dev) {
ret = -EIO;
goto out;
}
if (hdr.command & ~(__u32)(IB_USER_VERBS_CMD_FLAGS_MASK |
IB_USER_VERBS_CMD_COMMAND_MASK)) {
ret = -EINVAL;
goto out;
}
command = hdr.command & IB_USER_VERBS_CMD_COMMAND_MASK;
if (verify_command_mask(ib_dev, command)) {
ret = -EOPNOTSUPP;
goto out;
}
if (!file->ucontext &&
command != IB_USER_VERBS_CMD_GET_CONTEXT) {
ret = -EINVAL;
goto out;
}
flags = (hdr.command &
IB_USER_VERBS_CMD_FLAGS_MASK) >> IB_USER_VERBS_CMD_FLAGS_SHIFT;
if (!flags) {
if (command >= ARRAY_SIZE(uverbs_cmd_table) ||
!uverbs_cmd_table[command]) {
ret = -EINVAL;
goto out;
}
if (hdr.in_words * 4 != count) {
ret = -EINVAL;
goto out;
}
ret = uverbs_cmd_table[command](file, ib_dev,
buf + sizeof(hdr),
hdr.in_words * 4,
hdr.out_words * 4);
} else if (flags == IB_USER_VERBS_CMD_FLAG_EXTENDED) {
struct ib_uverbs_ex_cmd_hdr ex_hdr;
struct ib_udata ucore;
struct ib_udata uhw;
size_t written_count = count;
if (command >= ARRAY_SIZE(uverbs_ex_cmd_table) ||
!uverbs_ex_cmd_table[command]) {
ret = -ENOSYS;
goto out;
}
if (!file->ucontext) {
ret = -EINVAL;
goto out;
}
if (count < (sizeof(hdr) + sizeof(ex_hdr))) {
ret = -EINVAL;
goto out;
}
if (copy_from_user(&ex_hdr, buf + sizeof(hdr), sizeof(ex_hdr))) {
ret = -EFAULT;
goto out;
}
count -= sizeof(hdr) + sizeof(ex_hdr);
buf += sizeof(hdr) + sizeof(ex_hdr);
if ((hdr.in_words + ex_hdr.provider_in_words) * 8 != count) {
ret = -EINVAL;
goto out;
}
if (ex_hdr.cmd_hdr_reserved) {
ret = -EINVAL;
goto out;
}
if (ex_hdr.response) {
if (!hdr.out_words && !ex_hdr.provider_out_words) {
ret = -EINVAL;
goto out;
}
if (!access_ok(VERIFY_WRITE,
(void __user *) (unsigned long) ex_hdr.response,
(hdr.out_words + ex_hdr.provider_out_words) * 8)) {
ret = -EFAULT;
goto out;
}
} else {
if (hdr.out_words || ex_hdr.provider_out_words) {
ret = -EINVAL;
goto out;
}
}
INIT_UDATA_BUF_OR_NULL(&ucore, buf, (unsigned long) ex_hdr.response,
hdr.in_words * 8, hdr.out_words * 8);
INIT_UDATA_BUF_OR_NULL(&uhw,
buf + ucore.inlen,
(unsigned long) ex_hdr.response + ucore.outlen,
ex_hdr.provider_in_words * 8,
ex_hdr.provider_out_words * 8);
ret = uverbs_ex_cmd_table[command](file,
ib_dev,
&ucore,
&uhw);
if (!ret)
ret = written_count;
} else {
ret = -ENOSYS;
}
out:
srcu_read_unlock(&file->device->disassociate_srcu, srcu_key);
return ret;
}
Commit Message: IB/security: Restrict use of the write() interface
The drivers/infiniband stack uses write() as a replacement for
bi-directional ioctl(). This is not safe. There are ways to
trigger write calls that result in the return structure that
is normally written to user space being shunted off to user
specified kernel memory instead.
For the immediate repair, detect and deny suspicious accesses to
the write API.
For long term, update the user space libraries and the kernel API
to something that doesn't present the same security vulnerabilities
(likely a structured ioctl() interface).
The impacted uAPI interfaces are generally only available if
hardware from drivers/infiniband is installed in the system.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
[ Expanded check to all known write() entry points ]
Cc: [email protected]
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-264 | static ssize_t ib_uverbs_write(struct file *filp, const char __user *buf,
size_t count, loff_t *pos)
{
struct ib_uverbs_file *file = filp->private_data;
struct ib_device *ib_dev;
struct ib_uverbs_cmd_hdr hdr;
__u32 command;
__u32 flags;
int srcu_key;
ssize_t ret;
if (WARN_ON_ONCE(!ib_safe_file_access(filp)))
return -EACCES;
if (count < sizeof hdr)
return -EINVAL;
if (copy_from_user(&hdr, buf, sizeof hdr))
return -EFAULT;
srcu_key = srcu_read_lock(&file->device->disassociate_srcu);
ib_dev = srcu_dereference(file->device->ib_dev,
&file->device->disassociate_srcu);
if (!ib_dev) {
ret = -EIO;
goto out;
}
if (hdr.command & ~(__u32)(IB_USER_VERBS_CMD_FLAGS_MASK |
IB_USER_VERBS_CMD_COMMAND_MASK)) {
ret = -EINVAL;
goto out;
}
command = hdr.command & IB_USER_VERBS_CMD_COMMAND_MASK;
if (verify_command_mask(ib_dev, command)) {
ret = -EOPNOTSUPP;
goto out;
}
if (!file->ucontext &&
command != IB_USER_VERBS_CMD_GET_CONTEXT) {
ret = -EINVAL;
goto out;
}
flags = (hdr.command &
IB_USER_VERBS_CMD_FLAGS_MASK) >> IB_USER_VERBS_CMD_FLAGS_SHIFT;
if (!flags) {
if (command >= ARRAY_SIZE(uverbs_cmd_table) ||
!uverbs_cmd_table[command]) {
ret = -EINVAL;
goto out;
}
if (hdr.in_words * 4 != count) {
ret = -EINVAL;
goto out;
}
ret = uverbs_cmd_table[command](file, ib_dev,
buf + sizeof(hdr),
hdr.in_words * 4,
hdr.out_words * 4);
} else if (flags == IB_USER_VERBS_CMD_FLAG_EXTENDED) {
struct ib_uverbs_ex_cmd_hdr ex_hdr;
struct ib_udata ucore;
struct ib_udata uhw;
size_t written_count = count;
if (command >= ARRAY_SIZE(uverbs_ex_cmd_table) ||
!uverbs_ex_cmd_table[command]) {
ret = -ENOSYS;
goto out;
}
if (!file->ucontext) {
ret = -EINVAL;
goto out;
}
if (count < (sizeof(hdr) + sizeof(ex_hdr))) {
ret = -EINVAL;
goto out;
}
if (copy_from_user(&ex_hdr, buf + sizeof(hdr), sizeof(ex_hdr))) {
ret = -EFAULT;
goto out;
}
count -= sizeof(hdr) + sizeof(ex_hdr);
buf += sizeof(hdr) + sizeof(ex_hdr);
if ((hdr.in_words + ex_hdr.provider_in_words) * 8 != count) {
ret = -EINVAL;
goto out;
}
if (ex_hdr.cmd_hdr_reserved) {
ret = -EINVAL;
goto out;
}
if (ex_hdr.response) {
if (!hdr.out_words && !ex_hdr.provider_out_words) {
ret = -EINVAL;
goto out;
}
if (!access_ok(VERIFY_WRITE,
(void __user *) (unsigned long) ex_hdr.response,
(hdr.out_words + ex_hdr.provider_out_words) * 8)) {
ret = -EFAULT;
goto out;
}
} else {
if (hdr.out_words || ex_hdr.provider_out_words) {
ret = -EINVAL;
goto out;
}
}
INIT_UDATA_BUF_OR_NULL(&ucore, buf, (unsigned long) ex_hdr.response,
hdr.in_words * 8, hdr.out_words * 8);
INIT_UDATA_BUF_OR_NULL(&uhw,
buf + ucore.inlen,
(unsigned long) ex_hdr.response + ucore.outlen,
ex_hdr.provider_in_words * 8,
ex_hdr.provider_out_words * 8);
ret = uverbs_ex_cmd_table[command](file,
ib_dev,
&ucore,
&uhw);
if (!ret)
ret = written_count;
} else {
ret = -ENOSYS;
}
out:
srcu_read_unlock(&file->device->disassociate_srcu, srcu_key);
return ret;
}
| 167,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct nfs4_state *state;
struct rpc_cred *cred;
int status = 0;
cred = rpc_lookup_cred();
if (IS_ERR(cred)) {
status = PTR_ERR(cred);
goto out;
}
state = nfs4_do_open(dir, &path, flags, sattr, cred);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out_putcred;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
if (flags & O_EXCL) {
struct nfs_fattr fattr;
status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, &fattr);
}
if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)
status = nfs4_intent_set_file(nd, &path, state);
else
nfs4_close_sync(&path, state, flags);
out_putcred:
put_rpccred(cred);
out:
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct nfs4_state *state;
struct rpc_cred *cred;
fmode_t fmode = flags & (FMODE_READ | FMODE_WRITE);
int status = 0;
cred = rpc_lookup_cred();
if (IS_ERR(cred)) {
status = PTR_ERR(cred);
goto out;
}
state = nfs4_do_open(dir, &path, fmode, flags, sattr, cred);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out_putcred;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
if (flags & O_EXCL) {
struct nfs_fattr fattr;
status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, &fattr);
}
if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)
status = nfs4_intent_set_file(nd, &path, state, fmode);
else
nfs4_close_sync(&path, state, fmode);
out_putcred:
put_rpccred(cred);
out:
return status;
}
| 165,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SpdyWriteQueue::Clear() {
CHECK(!removing_writes_);
removing_writes_ = true;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
for (std::deque<PendingWrite>::iterator it = queue_[i].begin();
it != queue_[i].end(); ++it) {
delete it->frame_producer;
}
queue_[i].clear();
}
removing_writes_ = false;
}
Commit Message: These can post callbacks which re-enter into SpdyWriteQueue.
BUG=369539
Review URL: https://codereview.chromium.org/265933007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void SpdyWriteQueue::Clear() {
CHECK(!removing_writes_);
removing_writes_ = true;
std::vector<SpdyBufferProducer*> erased_buffer_producers;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
for (std::deque<PendingWrite>::iterator it = queue_[i].begin();
it != queue_[i].end(); ++it) {
erased_buffer_producers.push_back(it->frame_producer);
}
queue_[i].clear();
}
removing_writes_ = false;
STLDeleteElements(&erased_buffer_producers); // Invokes callbacks.
}
| 171,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GLES2DecoderImpl::SimulateFixedAttribs(
const char* function_name,
GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
if (!vertex_attrib_manager_->HaveFixedAttribs()) {
return true;
}
PerformanceWarning(
"GL_FIXED attributes have a signficant performance penalty");
GLuint elements_needed = 0;
const VertexAttribManager::VertexAttribInfoList& infos =
vertex_attrib_manager_->GetEnabledVertexAttribInfos();
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
GLuint max_accessed = info->MaxVertexAccessed(primcount,
max_vertex_accessed);
GLuint num_vertices = max_accessed + 1;
if (num_vertices == 0) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
if (attrib_info &&
info->CanAccess(max_accessed) &&
info->type() == GL_FIXED) {
GLuint elements_used = 0;
if (!SafeMultiply(num_vertices,
static_cast<GLuint>(info->size()), &elements_used) ||
!SafeAdd(elements_needed, elements_used, &elements_needed)) {
SetGLError(
GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
}
}
const GLuint kSizeOfFloat = sizeof(float); // NOLINT
GLuint size_needed = 0;
if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_);
if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(
GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
}
GLintptr offset = 0;
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
GLuint max_accessed = info->MaxVertexAccessed(primcount,
max_vertex_accessed);
GLuint num_vertices = max_accessed + 1;
if (num_vertices == 0) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
if (attrib_info &&
info->CanAccess(max_accessed) &&
info->type() == GL_FIXED) {
int num_elements = info->size() * kSizeOfFloat;
int size = num_elements * num_vertices;
scoped_array<float> data(new float[size]);
const int32* src = reinterpret_cast<const int32 *>(
info->buffer()->GetRange(info->offset(), size));
const int32* end = src + num_elements;
float* dst = data.get();
while (src != end) {
*dst++ = static_cast<float>(*src++) / 65536.0f;
}
glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get());
glVertexAttribPointer(
info->index(), info->size(), GL_FLOAT, false, 0,
reinterpret_cast<GLvoid*>(offset));
offset += size;
}
}
*simulated = true;
return true;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | bool GLES2DecoderImpl::SimulateFixedAttribs(
const char* function_name,
GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
if (!vertex_attrib_manager_->HaveFixedAttribs()) {
return true;
}
PerformanceWarning(
"GL_FIXED attributes have a signficant performance penalty");
GLuint elements_needed = 0;
const VertexAttribManager::VertexAttribInfoList& infos =
vertex_attrib_manager_->GetEnabledVertexAttribInfos();
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
GLuint max_accessed = info->MaxVertexAccessed(primcount,
max_vertex_accessed);
GLuint num_vertices = max_accessed + 1;
if (num_vertices == 0) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
if (attrib_info &&
info->CanAccess(max_accessed) &&
info->type() == GL_FIXED) {
uint32 elements_used = 0;
if (!SafeMultiplyUint32(num_vertices, info->size(), &elements_used) ||
!SafeAddUint32(elements_needed, elements_used, &elements_needed)) {
SetGLError(
GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
}
}
const uint32 kSizeOfFloat = sizeof(float); // NOLINT
uint32 size_needed = 0;
if (!SafeMultiplyUint32(elements_needed, kSizeOfFloat, &size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_);
if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(
GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs");
return false;
}
}
GLintptr offset = 0;
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
GLuint max_accessed = info->MaxVertexAccessed(primcount,
max_vertex_accessed);
GLuint num_vertices = max_accessed + 1;
if (num_vertices == 0) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
if (attrib_info &&
info->CanAccess(max_accessed) &&
info->type() == GL_FIXED) {
int num_elements = info->size() * kSizeOfFloat;
int size = num_elements * num_vertices;
scoped_array<float> data(new float[size]);
const int32* src = reinterpret_cast<const int32 *>(
info->buffer()->GetRange(info->offset(), size));
const int32* end = src + num_elements;
float* dst = data.get();
while (src != end) {
*dst++ = static_cast<float>(*src++) / 65536.0f;
}
glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get());
glVertexAttribPointer(
info->index(), info->size(), GL_FLOAT, false, 0,
reinterpret_cast<GLvoid*>(offset));
offset += size;
}
}
*simulated = true;
return true;
}
| 170,751 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_group_prop_ntr_selection_method(struct ofpbuf *payload,
enum ofp11_group_type group_type,
enum ofp15_group_mod_command group_cmd,
struct ofputil_group_props *gp)
{
struct ntr_group_prop_selection_method *prop = payload->data;
size_t fields_len, method_len;
enum ofperr error;
switch (group_type) {
case OFPGT11_SELECT:
break;
case OFPGT11_ALL:
case OFPGT11_INDIRECT:
case OFPGT11_FF:
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
"only allowed for select groups");
return OFPERR_OFPBPC_BAD_VALUE;
default:
OVS_NOT_REACHED();
}
switch (group_cmd) {
case OFPGC15_ADD:
case OFPGC15_MODIFY:
case OFPGC15_ADD_OR_MOD:
break;
case OFPGC15_DELETE:
case OFPGC15_INSERT_BUCKET:
case OFPGC15_REMOVE_BUCKET:
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
"only allowed for add and delete group modifications");
return OFPERR_OFPBPC_BAD_VALUE;
default:
OVS_NOT_REACHED();
}
if (payload->size < sizeof *prop) {
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property "
"length %u is not valid", payload->size);
return OFPERR_OFPBPC_BAD_LEN;
}
method_len = strnlen(prop->selection_method, NTR_MAX_SELECTION_METHOD_LEN);
if (method_len == NTR_MAX_SELECTION_METHOD_LEN) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method is not null terminated");
return OFPERR_OFPBPC_BAD_VALUE;
}
if (strcmp("hash", prop->selection_method)
&& strcmp("dp_hash", prop->selection_method)) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method '%s' is not supported",
prop->selection_method);
return OFPERR_OFPBPC_BAD_VALUE;
}
/* 'method_len' is now non-zero. */
strcpy(gp->selection_method, prop->selection_method);
gp->selection_method_param = ntohll(prop->selection_method_param);
ofpbuf_pull(payload, sizeof *prop);
fields_len = ntohs(prop->length) - sizeof *prop;
if (fields_len && strcmp("hash", gp->selection_method)) {
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method %s "
"does not support fields", gp->selection_method);
return OFPERR_OFPBPC_BAD_VALUE;
}
error = oxm_pull_field_array(payload->data, fields_len,
&gp->fields);
if (error) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method fields are invalid");
return error;
}
return 0;
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617 | parse_group_prop_ntr_selection_method(struct ofpbuf *payload,
enum ofp11_group_type group_type,
enum ofp15_group_mod_command group_cmd,
struct ofputil_group_props *gp)
{
struct ntr_group_prop_selection_method *prop = payload->data;
size_t fields_len, method_len;
enum ofperr error;
switch (group_type) {
case OFPGT11_SELECT:
break;
case OFPGT11_ALL:
case OFPGT11_INDIRECT:
case OFPGT11_FF:
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
"only allowed for select groups");
return OFPERR_OFPBPC_BAD_VALUE;
default:
return OFPERR_OFPGMFC_BAD_TYPE;
}
switch (group_cmd) {
case OFPGC15_ADD:
case OFPGC15_MODIFY:
case OFPGC15_ADD_OR_MOD:
break;
case OFPGC15_DELETE:
case OFPGC15_INSERT_BUCKET:
case OFPGC15_REMOVE_BUCKET:
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
"only allowed for add and delete group modifications");
return OFPERR_OFPBPC_BAD_VALUE;
default:
return OFPERR_OFPGMFC_BAD_COMMAND;
}
if (payload->size < sizeof *prop) {
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property "
"length %u is not valid", payload->size);
return OFPERR_OFPBPC_BAD_LEN;
}
method_len = strnlen(prop->selection_method, NTR_MAX_SELECTION_METHOD_LEN);
if (method_len == NTR_MAX_SELECTION_METHOD_LEN) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method is not null terminated");
return OFPERR_OFPBPC_BAD_VALUE;
}
if (strcmp("hash", prop->selection_method)
&& strcmp("dp_hash", prop->selection_method)) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method '%s' is not supported",
prop->selection_method);
return OFPERR_OFPBPC_BAD_VALUE;
}
/* 'method_len' is now non-zero. */
strcpy(gp->selection_method, prop->selection_method);
gp->selection_method_param = ntohll(prop->selection_method_param);
ofpbuf_pull(payload, sizeof *prop);
fields_len = ntohs(prop->length) - sizeof *prop;
if (fields_len && strcmp("hash", gp->selection_method)) {
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method %s "
"does not support fields", gp->selection_method);
return OFPERR_OFPBPC_BAD_VALUE;
}
error = oxm_pull_field_array(payload->data, fields_len,
&gp->fields);
if (error) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method fields are invalid");
return error;
}
return 0;
}
| 169,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InitializeOriginStatFromOriginRequestSummary(
OriginStat* origin,
const OriginRequestSummary& summary) {
origin->set_origin(summary.origin.spec());
origin->set_number_of_hits(1);
origin->set_average_position(summary.first_occurrence + 1);
origin->set_always_access_network(summary.always_access_network);
origin->set_accessed_network(summary.accessed_network);
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | void InitializeOriginStatFromOriginRequestSummary(
OriginStat* origin,
const OriginRequestSummary& summary) {
origin->set_origin(summary.origin.GetURL().spec());
origin->set_number_of_hits(1);
origin->set_average_position(summary.first_occurrence + 1);
origin->set_always_access_network(summary.always_access_network);
origin->set_accessed_network(summary.accessed_network);
}
| 172,379 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_throw_error (MyObject *obj, GError **error)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"this method always loses");
return FALSE;
}
Commit Message:
CWE ID: CWE-264 | my_object_throw_error (MyObject *obj, GError **error)
| 165,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_)
{
PCNetState *s = qemu_get_nic_opaque(nc);
int is_padr = 0, is_bcast = 0, is_ladr = 0;
uint8_t buf1[60];
int remaining;
int crc_err = 0;
int size = size_;
if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size ||
(CSR_LOOP(s) && !s->looptest)) {
return -1;
}
#ifdef PCNET_DEBUG
printf("pcnet_receive size=%d\n", size);
#endif
/* if too small buffer, then expand it */
if (size < MIN_BUF_SIZE) {
memcpy(buf1, buf, size);
memset(buf1 + size, 0, MIN_BUF_SIZE - size);
buf = buf1;
size = MIN_BUF_SIZE;
}
if (CSR_PROM(s)
|| (is_padr=padr_match(s, buf, size))
|| (is_bcast=padr_bcast(s, buf, size))
|| (is_ladr=ladr_match(s, buf, size))) {
pcnet_rdte_poll(s);
if (!(CSR_CRST(s) & 0x8000) && s->rdra) {
struct pcnet_RMD rmd;
int rcvrc = CSR_RCVRC(s)-1,i;
hwaddr nrda;
for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) {
if (rcvrc <= 1)
rcvrc = CSR_RCVRL(s);
nrda = s->rdra +
(CSR_RCVRL(s) - rcvrc) *
(BCR_SWSTYLE(s) ? 16 : 8 );
RMDLOAD(&rmd, nrda);
if (GET_FIELD(rmd.status, RMDS, OWN)) {
#ifdef PCNET_DEBUG_RMD
printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n",
rcvrc, CSR_RCVRC(s));
#endif
CSR_RCVRC(s) = rcvrc;
pcnet_rdte_poll(s);
break;
}
}
}
if (!(CSR_CRST(s) & 0x8000)) {
#ifdef PCNET_DEBUG_RMD
printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s));
#endif
s->csr[0] |= 0x1000; /* Set MISS flag */
CSR_MISSC(s)++;
} else {
uint8_t *src = s->buffer;
hwaddr crda = CSR_CRDA(s);
struct pcnet_RMD rmd;
int pktcount = 0;
if (!s->looptest) {
memcpy(src, buf, size);
/* no need to compute the CRC */
src[size] = 0;
uint32_t fcs = ~0;
uint8_t *p = src;
while (p != &src[size])
CRC(fcs, *p++);
*(uint32_t *)p = htonl(fcs);
size += 4;
} else {
uint32_t fcs = ~0;
uint8_t *p = src;
while (p != &src[size])
CRC(fcs, *p++);
crc_err = (*(uint32_t *)p != htonl(fcs));
}
#ifdef PCNET_DEBUG_MATCH
PRINT_PKTHDR(buf);
#endif
RMDLOAD(&rmd, PHYSADDR(s,crda));
/*if (!CSR_LAPPEN(s))*/
SET_FIELD(&rmd.status, RMDS, STP, 1);
#define PCNET_RECV_STORE() do { \
int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \
hwaddr rbadr = PHYSADDR(s, rmd.rbadr); \
s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \
src += count; remaining -= count; \
SET_FIELD(&rmd.status, RMDS, OWN, 0); \
RMDSTORE(&rmd, PHYSADDR(s,crda)); \
pktcount++; \
} while (0)
remaining = size;
PCNET_RECV_STORE();
if ((remaining > 0) && CSR_NRDA(s)) {
hwaddr nrda = CSR_NRDA(s);
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
RMDLOAD(&rmd, PHYSADDR(s,nrda));
if (GET_FIELD(rmd.status, RMDS, OWN)) {
crda = nrda;
PCNET_RECV_STORE();
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
if ((remaining > 0) && (nrda=CSR_NNRD(s))) {
RMDLOAD(&rmd, PHYSADDR(s,nrda));
if (GET_FIELD(rmd.status, RMDS, OWN)) {
crda = nrda;
PCNET_RECV_STORE();
}
}
}
}
#undef PCNET_RECV_STORE
RMDLOAD(&rmd, PHYSADDR(s,crda));
if (remaining == 0) {
SET_FIELD(&rmd.msg_length, RMDM, MCNT, size);
SET_FIELD(&rmd.status, RMDS, ENP, 1);
SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr);
SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr);
SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast);
if (crc_err) {
SET_FIELD(&rmd.status, RMDS, CRC, 1);
SET_FIELD(&rmd.status, RMDS, ERR, 1);
}
} else {
SET_FIELD(&rmd.status, RMDS, OFLO, 1);
SET_FIELD(&rmd.status, RMDS, BUFF, 1);
SET_FIELD(&rmd.status, RMDS, ERR, 1);
}
RMDSTORE(&rmd, PHYSADDR(s,crda));
s->csr[0] |= 0x0400;
#ifdef PCNET_DEBUG
printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n",
CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount);
#endif
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
while (pktcount--) {
if (CSR_RCVRC(s) <= 1)
CSR_RCVRC(s) = CSR_RCVRL(s);
else
CSR_RCVRC(s)--;
}
pcnet_rdte_poll(s);
}
}
pcnet_poll(s);
pcnet_update_irq(s);
return size_;
}
Commit Message:
CWE ID: CWE-119 | ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_)
{
PCNetState *s = qemu_get_nic_opaque(nc);
int is_padr = 0, is_bcast = 0, is_ladr = 0;
uint8_t buf1[60];
int remaining;
int crc_err = 0;
int size = size_;
if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size ||
(CSR_LOOP(s) && !s->looptest)) {
return -1;
}
#ifdef PCNET_DEBUG
printf("pcnet_receive size=%d\n", size);
#endif
/* if too small buffer, then expand it */
if (size < MIN_BUF_SIZE) {
memcpy(buf1, buf, size);
memset(buf1 + size, 0, MIN_BUF_SIZE - size);
buf = buf1;
size = MIN_BUF_SIZE;
}
if (CSR_PROM(s)
|| (is_padr=padr_match(s, buf, size))
|| (is_bcast=padr_bcast(s, buf, size))
|| (is_ladr=ladr_match(s, buf, size))) {
pcnet_rdte_poll(s);
if (!(CSR_CRST(s) & 0x8000) && s->rdra) {
struct pcnet_RMD rmd;
int rcvrc = CSR_RCVRC(s)-1,i;
hwaddr nrda;
for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) {
if (rcvrc <= 1)
rcvrc = CSR_RCVRL(s);
nrda = s->rdra +
(CSR_RCVRL(s) - rcvrc) *
(BCR_SWSTYLE(s) ? 16 : 8 );
RMDLOAD(&rmd, nrda);
if (GET_FIELD(rmd.status, RMDS, OWN)) {
#ifdef PCNET_DEBUG_RMD
printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n",
rcvrc, CSR_RCVRC(s));
#endif
CSR_RCVRC(s) = rcvrc;
pcnet_rdte_poll(s);
break;
}
}
}
if (!(CSR_CRST(s) & 0x8000)) {
#ifdef PCNET_DEBUG_RMD
printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s));
#endif
s->csr[0] |= 0x1000; /* Set MISS flag */
CSR_MISSC(s)++;
} else {
uint8_t *src = s->buffer;
hwaddr crda = CSR_CRDA(s);
struct pcnet_RMD rmd;
int pktcount = 0;
if (!s->looptest) {
if (size > 4092) {
#ifdef PCNET_DEBUG_RMD
fprintf(stderr, "pcnet: truncates rx packet.\n");
#endif
size = 4092;
}
memcpy(src, buf, size);
/* no need to compute the CRC */
src[size] = 0;
uint32_t fcs = ~0;
uint8_t *p = src;
while (p != &src[size])
CRC(fcs, *p++);
*(uint32_t *)p = htonl(fcs);
size += 4;
} else {
uint32_t fcs = ~0;
uint8_t *p = src;
while (p != &src[size])
CRC(fcs, *p++);
crc_err = (*(uint32_t *)p != htonl(fcs));
}
#ifdef PCNET_DEBUG_MATCH
PRINT_PKTHDR(buf);
#endif
RMDLOAD(&rmd, PHYSADDR(s,crda));
/*if (!CSR_LAPPEN(s))*/
SET_FIELD(&rmd.status, RMDS, STP, 1);
#define PCNET_RECV_STORE() do { \
int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \
hwaddr rbadr = PHYSADDR(s, rmd.rbadr); \
s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \
src += count; remaining -= count; \
SET_FIELD(&rmd.status, RMDS, OWN, 0); \
RMDSTORE(&rmd, PHYSADDR(s,crda)); \
pktcount++; \
} while (0)
remaining = size;
PCNET_RECV_STORE();
if ((remaining > 0) && CSR_NRDA(s)) {
hwaddr nrda = CSR_NRDA(s);
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
RMDLOAD(&rmd, PHYSADDR(s,nrda));
if (GET_FIELD(rmd.status, RMDS, OWN)) {
crda = nrda;
PCNET_RECV_STORE();
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
if ((remaining > 0) && (nrda=CSR_NNRD(s))) {
RMDLOAD(&rmd, PHYSADDR(s,nrda));
if (GET_FIELD(rmd.status, RMDS, OWN)) {
crda = nrda;
PCNET_RECV_STORE();
}
}
}
}
#undef PCNET_RECV_STORE
RMDLOAD(&rmd, PHYSADDR(s,crda));
if (remaining == 0) {
SET_FIELD(&rmd.msg_length, RMDM, MCNT, size);
SET_FIELD(&rmd.status, RMDS, ENP, 1);
SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr);
SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr);
SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast);
if (crc_err) {
SET_FIELD(&rmd.status, RMDS, CRC, 1);
SET_FIELD(&rmd.status, RMDS, ERR, 1);
}
} else {
SET_FIELD(&rmd.status, RMDS, OFLO, 1);
SET_FIELD(&rmd.status, RMDS, BUFF, 1);
SET_FIELD(&rmd.status, RMDS, ERR, 1);
}
RMDSTORE(&rmd, PHYSADDR(s,crda));
s->csr[0] |= 0x0400;
#ifdef PCNET_DEBUG
printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n",
CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount);
#endif
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
while (pktcount--) {
if (CSR_RCVRC(s) <= 1)
CSR_RCVRC(s) = CSR_RCVRL(s);
else
CSR_RCVRC(s)--;
}
pcnet_rdte_poll(s);
}
}
pcnet_poll(s);
pcnet_update_irq(s);
return size_;
}
| 165,286 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
PassRefPtr<CallbackWrapper> callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
CallbackWrapper* callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
| 171,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid = fs->cache.array[x].objectId.id;
if (bufLen < 2)
break;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count += 2;
bufLen -= 2;
}
}
return count;
}
| 169,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned long lh_char_hash(const void *k)
{
unsigned int h = 0;
const char* data = (const char*)k;
while( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME;
return h;
}
Commit Message: Patch to address the following issues:
* CVE-2013-6371: hash collision denial of service
* CVE-2013-6370: buffer overflow if size_t is larger than int
CWE ID: CWE-310 | unsigned long lh_char_hash(const void *k)
{
static volatile int random_seed = -1;
if (random_seed == -1) {
int seed;
/* we can't use -1 as it is the unitialized sentinel */
while ((seed = json_c_get_random_seed()) == -1);
#if defined __GNUC__
__sync_val_compare_and_swap(&random_seed, -1, seed);
#elif defined _MSC_VER
InterlockedCompareExchange(&random_seed, seed, -1);
#else
#warning "racy random seed initializtion if used by multiple threads"
random_seed = seed; /* potentially racy */
#endif
}
return hashlittle((const char*)k, strlen((const char*)k), random_seed);
}
| 166,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: kg_unseal(minor_status, context_handle, input_token_buffer,
message_buffer, conf_state, qop_state, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_token_buffer;
gss_buffer_t message_buffer;
int *conf_state;
gss_qop_t *qop_state;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
unsigned char *ptr;
unsigned int bodysize;
int err;
int toktype2;
int vfyflags = 0;
OM_uint32 ret;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
/* parse the token, leave the data in message_buffer, setting conf_state */
/* verify the header */
ptr = (unsigned char *) input_token_buffer->value;
err = g_verify_token_header(ctx->mech_used,
&bodysize, &ptr, -1,
input_token_buffer->length,
vfyflags);
if (err) {
*minor_status = err;
return GSS_S_DEFECTIVE_TOKEN;
}
if (bodysize < 2) {
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
return GSS_S_DEFECTIVE_TOKEN;
}
toktype2 = load_16_be(ptr);
ptr += 2;
bodysize -= 2;
switch (toktype2) {
case KG2_TOK_MIC_MSG:
case KG2_TOK_WRAP_MSG:
case KG2_TOK_DEL_CTX:
ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx,
ptr, bodysize, message_buffer,
conf_state, qop_state, toktype);
break;
case KG_TOK_MIC_MSG:
case KG_TOK_WRAP_MSG:
case KG_TOK_DEL_CTX:
ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize,
message_buffer, conf_state, qop_state,
toktype);
break;
default:
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
ret = GSS_S_DEFECTIVE_TOKEN;
break;
}
if (ret != 0)
save_error_info (*minor_status, ctx->k5_context);
return ret;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | kg_unseal(minor_status, context_handle, input_token_buffer,
message_buffer, conf_state, qop_state, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_token_buffer;
gss_buffer_t message_buffer;
int *conf_state;
gss_qop_t *qop_state;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
unsigned char *ptr;
unsigned int bodysize;
int err;
int toktype2;
int vfyflags = 0;
OM_uint32 ret;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
/* parse the token, leave the data in message_buffer, setting conf_state */
/* verify the header */
ptr = (unsigned char *) input_token_buffer->value;
err = g_verify_token_header(ctx->mech_used,
&bodysize, &ptr, -1,
input_token_buffer->length,
vfyflags);
if (err) {
*minor_status = err;
return GSS_S_DEFECTIVE_TOKEN;
}
if (bodysize < 2) {
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
return GSS_S_DEFECTIVE_TOKEN;
}
toktype2 = load_16_be(ptr);
ptr += 2;
bodysize -= 2;
switch (toktype2) {
case KG2_TOK_MIC_MSG:
case KG2_TOK_WRAP_MSG:
case KG2_TOK_DEL_CTX:
ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx,
ptr, bodysize, message_buffer,
conf_state, qop_state, toktype);
break;
case KG_TOK_MIC_MSG:
case KG_TOK_WRAP_MSG:
case KG_TOK_DEL_CTX:
ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize,
message_buffer, conf_state, qop_state,
toktype);
break;
default:
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
ret = GSS_S_DEFECTIVE_TOKEN;
break;
}
if (ret != 0)
save_error_info (*minor_status, ctx->k5_context);
return ret;
}
| 166,819 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void f_parser (lua_State *L, void *ud) {
int i;
Proto *tf;
Closure *cl;
struct SParser *p = cast(struct SParser *, ud);
int c = luaZ_lookahead(p->z);
luaC_checkGC(L);
tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z,
&p->buff, p->name);
cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
cl->l.p = tf;
for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */
cl->l.upvals[i] = luaF_newupval(L);
setclvalue(L, L->top, cl);
incr_top(L);
}
Commit Message: disable loading lua bytecode
CWE ID: CWE-17 | static void f_parser (lua_State *L, void *ud) {
int i;
Proto *tf;
Closure *cl;
struct SParser *p = cast(struct SParser *, ud);
int c = luaZ_lookahead(p->z);
luaC_checkGC(L);
tf = (luaY_parser)(L, p->z,
&p->buff, p->name);
cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
cl->l.p = tf;
for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */
cl->l.upvals[i] = luaF_newupval(L);
setclvalue(L, L->top, cl);
incr_top(L);
}
| 166,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
{
int totlen;
uint32_t t;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)
{
int totlen;
uint32_t t;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
| 167,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Error: invalid .Xauthority file\n");
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) == -1)
errExit("fchown");
if (chmod(dest, 0600) == -1)
errExit("fchmod");
return 1; // file copied
}
return 0;
}
Commit Message: security fix
CWE ID: CWE-269 | static int store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600); // regular user
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
| 170,100 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_text_compress(png_structp png_ptr,
png_charp text, png_size_t text_len, int compression,
compression_state *comp)
{
int ret;
comp->num_output_ptr = 0;
comp->max_output_ptr = 0;
comp->output_ptr = NULL;
comp->input = NULL;
comp->input_len = 0;
/* We may just want to pass the text right through */
if (compression == PNG_TEXT_COMPRESSION_NONE)
{
comp->input = text;
comp->input_len = text_len;
return((int)text_len);
}
if (compression >= PNG_TEXT_COMPRESSION_LAST)
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char msg[50];
png_snprintf(msg, 50, "Unknown compression type %d", compression);
png_warning(png_ptr, msg);
#else
png_warning(png_ptr, "Unknown compression type");
#endif
}
/* We can't write the chunk until we find out how much data we have,
* which means we need to run the compressor first and save the
* output. This shouldn't be a problem, as the vast majority of
* comments should be reasonable, but we will set up an array of
* malloc'd pointers to be sure.
*
* If we knew the application was well behaved, we could simplify this
* greatly by assuming we can always malloc an output buffer large
* enough to hold the compressed text ((1001 * text_len / 1000) + 12)
* and malloc this directly. The only time this would be a bad idea is
* if we can't malloc more than 64K and we have 64K of random input
* data, or if the input string is incredibly large (although this
* wouldn't cause a failure, just a slowdown due to swapping).
*/
/* Set up the compression buffers */
png_ptr->zstream.avail_in = (uInt)text_len;
png_ptr->zstream.next_in = (Bytef *)text;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
/* This is the same compression loop as in png_write_row() */
do
{
/* Compress the data */
ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
if (ret != Z_OK)
{
/* Error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Make sure the output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charpp)));
png_memcpy(comp->output_ptr, old_ptr, old_max
* png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
/* Continue until we don't have any more to compress */
} while (png_ptr->zstream.avail_in);
/* Finish the compression */
do
{
/* Tell zlib we are finished */
ret = deflate(&png_ptr->zstream, Z_FINISH);
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Check to make sure our output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
/* This could be optimized to realloc() */
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
png_memcpy(comp->output_ptr, old_ptr,
old_max * png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer pointers */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
}
else if (ret != Z_STREAM_END)
{
/* We got an error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Text length is number of buffers plus last buffer */
text_len = png_ptr->zbuf_size * comp->num_output_ptr;
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
return((int)text_len);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_text_compress(png_structp png_ptr,
png_charp text, png_size_t text_len, int compression,
compression_state *comp)
{
int ret;
comp->num_output_ptr = 0;
comp->max_output_ptr = 0;
comp->output_ptr = NULL;
comp->input = NULL;
comp->input_len = 0;
/* We may just want to pass the text right through */
if (compression == PNG_TEXT_COMPRESSION_NONE)
{
comp->input = text;
comp->input_len = text_len;
return((int)text_len);
}
if (compression >= PNG_TEXT_COMPRESSION_LAST)
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char msg[50];
png_snprintf(msg, 50, "Unknown compression type %d", compression);
png_warning(png_ptr, msg);
#else
png_warning(png_ptr, "Unknown compression type");
#endif
}
/* We can't write the chunk until we find out how much data we have,
* which means we need to run the compressor first and save the
* output. This shouldn't be a problem, as the vast majority of
* comments should be reasonable, but we will set up an array of
* malloc'd pointers to be sure.
*
* If we knew the application was well behaved, we could simplify this
* greatly by assuming we can always malloc an output buffer large
* enough to hold the compressed text ((1001 * text_len / 1000) + 12)
* and malloc this directly. The only time this would be a bad idea is
* if we can't malloc more than 64K and we have 64K of random input
* data, or if the input string is incredibly large (although this
* wouldn't cause a failure, just a slowdown due to swapping).
*/
/* Set up the compression buffers */
png_ptr->zstream.avail_in = (uInt)text_len;
png_ptr->zstream.next_in = (Bytef *)text;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
/* This is the same compression loop as in png_write_row() */
do
{
/* Compress the data */
ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
if (ret != Z_OK)
{
/* Error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Make sure the output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charp)));
png_memcpy(comp->output_ptr, old_ptr, old_max
* png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
/* Continue until we don't have any more to compress */
} while (png_ptr->zstream.avail_in);
/* Finish the compression */
do
{
/* Tell zlib we are finished */
ret = deflate(&png_ptr->zstream, Z_FINISH);
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Check to make sure our output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
/* This could be optimized to realloc() */
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
png_memcpy(comp->output_ptr, old_ptr,
old_max * png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer pointers */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
}
else if (ret != Z_STREAM_END)
{
/* We got an error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Text length is number of buffers plus last buffer */
text_len = png_ptr->zbuf_size * comp->num_output_ptr;
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
return((int)text_len);
}
| 172,192 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int airspy_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct airspy *s;
int ret;
u8 u8tmp, buf[BUF_SIZE];
s = kzalloc(sizeof(struct airspy), GFP_KERNEL);
if (s == NULL) {
dev_err(&intf->dev, "Could not allocate memory for state\n");
return -ENOMEM;
}
mutex_init(&s->v4l2_lock);
mutex_init(&s->vb_queue_lock);
spin_lock_init(&s->queued_bufs_lock);
INIT_LIST_HEAD(&s->queued_bufs);
s->dev = &intf->dev;
s->udev = interface_to_usbdev(intf);
s->f_adc = bands[0].rangelow;
s->f_rf = bands_rf[0].rangelow;
s->pixelformat = formats[0].pixelformat;
s->buffersize = formats[0].buffersize;
/* Detect device */
ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
if (ret == 0)
ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0,
buf, BUF_SIZE);
if (ret) {
dev_err(s->dev, "Could not detect board\n");
goto err_free_mem;
}
buf[BUF_SIZE - 1] = '\0';
dev_info(s->dev, "Board ID: %02x\n", u8tmp);
dev_info(s->dev, "Firmware version: %s\n", buf);
/* Init videobuf2 queue structure */
s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
s->vb_queue.drv_priv = s;
s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf);
s->vb_queue.ops = &airspy_vb2_ops;
s->vb_queue.mem_ops = &vb2_vmalloc_memops;
s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
ret = vb2_queue_init(&s->vb_queue);
if (ret) {
dev_err(s->dev, "Could not initialize vb2 queue\n");
goto err_free_mem;
}
/* Init video_device structure */
s->vdev = airspy_template;
s->vdev.queue = &s->vb_queue;
s->vdev.queue->lock = &s->vb_queue_lock;
video_set_drvdata(&s->vdev, s);
/* Register the v4l2_device structure */
s->v4l2_dev.release = airspy_video_release;
ret = v4l2_device_register(&intf->dev, &s->v4l2_dev);
if (ret) {
dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret);
goto err_free_mem;
}
/* Register controls */
v4l2_ctrl_handler_init(&s->hdl, 5);
s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0);
s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8);
v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false);
s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0);
s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8);
v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false);
s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0);
if (s->hdl.error) {
ret = s->hdl.error;
dev_err(s->dev, "Could not initialize controls\n");
goto err_free_controls;
}
v4l2_ctrl_handler_setup(&s->hdl);
s->v4l2_dev.ctrl_handler = &s->hdl;
s->vdev.v4l2_dev = &s->v4l2_dev;
s->vdev.lock = &s->v4l2_lock;
ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1);
if (ret) {
dev_err(s->dev, "Failed to register as video device (%d)\n",
ret);
goto err_unregister_v4l2_dev;
}
dev_info(s->dev, "Registered as %s\n",
video_device_node_name(&s->vdev));
dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
return 0;
err_free_controls:
v4l2_ctrl_handler_free(&s->hdl);
err_unregister_v4l2_dev:
v4l2_device_unregister(&s->v4l2_dev);
err_free_mem:
kfree(s);
return ret;
}
Commit Message: media: fix airspy usb probe error path
Fix a memory leak on probe error of the airspy usb device driver.
The problem is triggered when more than 64 usb devices register with
v4l2 of type VFL_TYPE_SDR or VFL_TYPE_SUBDEV.
The memory leak is caused by the probe function of the airspy driver
mishandeling errors and not freeing the corresponding control structures
when an error occours registering the device to v4l2 core.
A badusb device can emulate 64 of these devices, and then through
continual emulated connect/disconnect of the 65th device, cause the
kernel to run out of RAM and crash the kernel, thus causing a local DOS
vulnerability.
Fixes CVE-2016-5400
Signed-off-by: James Patrick-Evans <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Cc: [email protected] # 3.17+
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119 | static int airspy_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct airspy *s;
int ret;
u8 u8tmp, buf[BUF_SIZE];
s = kzalloc(sizeof(struct airspy), GFP_KERNEL);
if (s == NULL) {
dev_err(&intf->dev, "Could not allocate memory for state\n");
return -ENOMEM;
}
mutex_init(&s->v4l2_lock);
mutex_init(&s->vb_queue_lock);
spin_lock_init(&s->queued_bufs_lock);
INIT_LIST_HEAD(&s->queued_bufs);
s->dev = &intf->dev;
s->udev = interface_to_usbdev(intf);
s->f_adc = bands[0].rangelow;
s->f_rf = bands_rf[0].rangelow;
s->pixelformat = formats[0].pixelformat;
s->buffersize = formats[0].buffersize;
/* Detect device */
ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
if (ret == 0)
ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0,
buf, BUF_SIZE);
if (ret) {
dev_err(s->dev, "Could not detect board\n");
goto err_free_mem;
}
buf[BUF_SIZE - 1] = '\0';
dev_info(s->dev, "Board ID: %02x\n", u8tmp);
dev_info(s->dev, "Firmware version: %s\n", buf);
/* Init videobuf2 queue structure */
s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
s->vb_queue.drv_priv = s;
s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf);
s->vb_queue.ops = &airspy_vb2_ops;
s->vb_queue.mem_ops = &vb2_vmalloc_memops;
s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
ret = vb2_queue_init(&s->vb_queue);
if (ret) {
dev_err(s->dev, "Could not initialize vb2 queue\n");
goto err_free_mem;
}
/* Init video_device structure */
s->vdev = airspy_template;
s->vdev.queue = &s->vb_queue;
s->vdev.queue->lock = &s->vb_queue_lock;
video_set_drvdata(&s->vdev, s);
/* Register the v4l2_device structure */
s->v4l2_dev.release = airspy_video_release;
ret = v4l2_device_register(&intf->dev, &s->v4l2_dev);
if (ret) {
dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret);
goto err_free_mem;
}
/* Register controls */
v4l2_ctrl_handler_init(&s->hdl, 5);
s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0);
s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8);
v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false);
s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0);
s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8);
v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false);
s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0);
if (s->hdl.error) {
ret = s->hdl.error;
dev_err(s->dev, "Could not initialize controls\n");
goto err_free_controls;
}
v4l2_ctrl_handler_setup(&s->hdl);
s->v4l2_dev.ctrl_handler = &s->hdl;
s->vdev.v4l2_dev = &s->v4l2_dev;
s->vdev.lock = &s->v4l2_lock;
ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1);
if (ret) {
dev_err(s->dev, "Failed to register as video device (%d)\n",
ret);
goto err_free_controls;
}
dev_info(s->dev, "Registered as %s\n",
video_device_node_name(&s->vdev));
dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
return 0;
err_free_controls:
v4l2_ctrl_handler_free(&s->hdl);
v4l2_device_unregister(&s->v4l2_dev);
err_free_mem:
kfree(s);
return ret;
}
| 167,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProcessRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
timer.Stop(); // Erase reference to self.
WallpaperManager* manager = WallpaperManager::Get();
if (manager->pending_inactive_ == this)
manager->pending_inactive_ = NULL;
started_load_at_ = base::Time::Now();
if (default_) {
manager->DoSetDefaultWallpaper(account_id_, std::move(on_finish_));
} else if (!user_wallpaper_.isNull()) {
SetWallpaper(user_wallpaper_, info_);
} else if (!wallpaper_path_.empty()) {
manager->task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&WallpaperManager::GetCustomWallpaperInternal,
account_id_, info_, wallpaper_path_,
true /* update wallpaper */,
base::ThreadTaskRunnerHandle::Get(),
base::Passed(std::move(on_finish_)),
manager->weak_factory_.GetWeakPtr()));
} else if (!info_.location.empty()) {
manager->LoadWallpaper(account_id_, info_, true, std::move(on_finish_));
} else {
NOTREACHED();
started_load_at_ = base::Time();
}
on_finish_.reset();
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200 | void ProcessRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
timer.Stop(); // Erase reference to self.
WallpaperManager* manager = WallpaperManager::Get();
if (manager->pending_inactive_ == this)
manager->pending_inactive_ = NULL;
started_load_at_ = base::Time::Now();
if (default_) {
manager->DoSetDefaultWallpaper(account_id_, true /* update_wallpaper */,
std::move(on_finish_));
} else if (!user_wallpaper_.isNull()) {
SetWallpaper(user_wallpaper_, info_);
} else if (!wallpaper_path_.empty()) {
manager->task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&WallpaperManager::GetCustomWallpaperInternal,
account_id_, info_, wallpaper_path_,
true /* update wallpaper */,
base::ThreadTaskRunnerHandle::Get(),
base::Passed(std::move(on_finish_)),
manager->weak_factory_.GetWeakPtr()));
} else if (!info_.location.empty()) {
manager->LoadWallpaper(account_id_, info_, true /* update_wallpaper */,
std::move(on_finish_));
} else {
NOTREACHED();
started_load_at_ = base::Time();
}
on_finish_.reset();
}
| 171,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::GetType() const
{
return m_info.type;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Track::GetType() const
| 174,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int propagate_mnt(struct mount *dest_mnt, struct dentry *dest_dentry,
struct mount *source_mnt, struct list_head *tree_list)
{
struct mount *m, *child;
int ret = 0;
struct mount *prev_dest_mnt = dest_mnt;
struct mount *prev_src_mnt = source_mnt;
LIST_HEAD(tmp_list);
LIST_HEAD(umount_list);
for (m = propagation_next(dest_mnt, dest_mnt); m;
m = propagation_next(m, dest_mnt)) {
int type;
struct mount *source;
if (IS_MNT_NEW(m))
continue;
source = get_source(m, prev_dest_mnt, prev_src_mnt, &type);
child = copy_tree(source, source->mnt.mnt_root, type);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
list_splice(tree_list, tmp_list.prev);
goto out;
}
if (is_subdir(dest_dentry, m->mnt.mnt_root)) {
mnt_set_mountpoint(m, dest_dentry, child);
list_add_tail(&child->mnt_hash, tree_list);
} else {
/*
* This can happen if the parent mount was bind mounted
* on some subdirectory of a shared/slave mount.
*/
list_add_tail(&child->mnt_hash, &tmp_list);
}
prev_dest_mnt = m;
prev_src_mnt = child;
}
out:
br_write_lock(&vfsmount_lock);
while (!list_empty(&tmp_list)) {
child = list_first_entry(&tmp_list, struct mount, mnt_hash);
umount_tree(child, 0, &umount_list);
}
br_write_unlock(&vfsmount_lock);
release_mounts(&umount_list);
return ret;
}
Commit Message: vfs: Carefully propogate mounts across user namespaces
As a matter of policy MNT_READONLY should not be changable if the
original mounter had more privileges than creator of the mount
namespace.
Add the flag CL_UNPRIVILEGED to note when we are copying a mount from
a mount namespace that requires more privileges to a mount namespace
that requires fewer privileges.
When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT
if any of the mnt flags that should never be changed are set.
This protects both mount propagation and the initial creation of a less
privileged mount namespace.
Cc: [email protected]
Acked-by: Serge Hallyn <[email protected]>
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264 | int propagate_mnt(struct mount *dest_mnt, struct dentry *dest_dentry,
struct mount *source_mnt, struct list_head *tree_list)
{
struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
struct mount *m, *child;
int ret = 0;
struct mount *prev_dest_mnt = dest_mnt;
struct mount *prev_src_mnt = source_mnt;
LIST_HEAD(tmp_list);
LIST_HEAD(umount_list);
for (m = propagation_next(dest_mnt, dest_mnt); m;
m = propagation_next(m, dest_mnt)) {
int type;
struct mount *source;
if (IS_MNT_NEW(m))
continue;
source = get_source(m, prev_dest_mnt, prev_src_mnt, &type);
/* Notice when we are propagating across user namespaces */
if (m->mnt_ns->user_ns != user_ns)
type |= CL_UNPRIVILEGED;
child = copy_tree(source, source->mnt.mnt_root, type);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
list_splice(tree_list, tmp_list.prev);
goto out;
}
if (is_subdir(dest_dentry, m->mnt.mnt_root)) {
mnt_set_mountpoint(m, dest_dentry, child);
list_add_tail(&child->mnt_hash, tree_list);
} else {
/*
* This can happen if the parent mount was bind mounted
* on some subdirectory of a shared/slave mount.
*/
list_add_tail(&child->mnt_hash, &tmp_list);
}
prev_dest_mnt = m;
prev_src_mnt = child;
}
out:
br_write_lock(&vfsmount_lock);
while (!list_empty(&tmp_list)) {
child = list_first_entry(&tmp_list, struct mount, mnt_hash);
umount_tree(child, 0, &umount_list);
}
br_write_unlock(&vfsmount_lock);
release_mounts(&umount_list);
return ret;
}
| 166,096 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const char* Track::GetLanguage() const
{
return m_info.language;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const char* Track::GetLanguage() const
| 174,337 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
uint8_t i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %d, RES: %d, Sel: %d",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07)));
ND_PRINT((ndo, "Protocol ID: %d", EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-12997/LLDP: Don't use an 8-bit loop counter.
If you have a
for (i = 0; i < N; i++)
loop, you'd better make sure that i is big enough to hold N - not N-1,
N.
The TLV length here is 9 bits long, not 8 bits long, so an 8-bit loop
counter will overflow and you can loop infinitely.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s).
Clean up the output a bit while we're at it.
CWE ID: CWE-835 | lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
u_int i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07),
EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
| 167,910 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FaviconSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
FaviconService* favicon_service =
profile_->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (favicon_service) {
FaviconService::Handle handle;
if (path.empty()) {
SendDefaultResponse(request_id);
return;
}
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = favicon_service->GetFavicon(
GURL(path.substr(8)),
history::FAVICON,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
} else {
handle = favicon_service->GetFaviconForURL(
GURL(path),
icon_types_,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
}
cancelable_consumer_.SetClientData(favicon_service, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void FaviconSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
FaviconService* favicon_service =
profile_->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (favicon_service) {
if (path.empty()) {
SendDefaultResponse(request_id);
return;
}
FaviconService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = favicon_service->GetFavicon(
GURL(path.substr(8)),
history::FAVICON,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
} else {
GURL url;
if (path.size() > 5 && path.substr(0, 5) == "size/") {
size_t slash = path.find("/", 5);
std::string size = path.substr(5, slash - 5);
int pixel_size = atoi(size.c_str());
CHECK(pixel_size == 32 || pixel_size == 16) <<
"only 32x32 and 16x16 icons are supported";
request_size_map_[request_id] = pixel_size;
url = GURL(path.substr(slash + 1));
} else {
request_size_map_[request_id] = 16;
url = GURL(path);
}
// TODO(estade): fetch the requested size.
handle = favicon_service->GetFaviconForURL(
url,
icon_types_,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
}
cancelable_consumer_.SetClientData(favicon_service, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
| 170,368 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)
{
struct srpt_device *sdev;
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *target;
int ret, i;
ret = -EINVAL;
ch = ioctx->ch;
BUG_ON(!ch);
BUG_ON(!ch->sport);
sdev = ch->sport->sdev;
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
for (i = 0; i < ch->rq_size; ++i) {
target = ch->ioctx_ring[i];
if (target->cmd.se_lun == ioctx->cmd.se_lun &&
target->cmd.tag == tag &&
srpt_get_cmd_state(target) != SRPT_STATE_DONE) {
ret = 0;
/* now let the target core abort &target->cmd; */
break;
}
}
spin_unlock_irq(&sdev->spinlock);
return ret;
}
Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt()
Let the target core check task existence instead of the SRP target
driver. Additionally, let the target core check the validity of the
task management request instead of the ib_srpt driver.
This patch fixes the following kernel crash:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000001
IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt]
Oops: 0002 [#1] SMP
Call Trace:
[<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt]
[<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt]
[<ffffffff8109726f>] kthread+0xcf/0xe0
[<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0
Signed-off-by: Bart Van Assche <[email protected]>
Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr")
Tested-by: Alex Estrin <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Cc: Nicholas Bellinger <[email protected]>
Cc: Sagi Grimberg <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-476 | static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)
| 167,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OffscreenCanvas::Dispose() {
if (context_) {
context_->DetachHost();
context_ = nullptr;
}
if (HasPlaceholderCanvas() && GetTopExecutionContext() &&
GetTopExecutionContext()->IsWorkerGlobalScope()) {
WorkerAnimationFrameProvider* animation_frame_provider =
To<WorkerGlobalScope>(GetTopExecutionContext())
->GetAnimationFrameProvider();
if (animation_frame_provider)
animation_frame_provider->DeregisterOffscreenCanvas(this);
}
}
Commit Message: Clean up CanvasResourceDispatcher on finalizer
We may have pending mojo messages after GC, so we want to drop the
dispatcher as soon as possible.
Bug: 929757,913964
Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0
Reviewed-on: https://chromium-review.googlesource.com/c/1489175
Reviewed-by: Ken Rockot <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Auto-Submit: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#635833}
CWE ID: CWE-416 | void OffscreenCanvas::Dispose() {
// We need to drop frame dispatcher, to prevent mojo calls from completing.
frame_dispatcher_ = nullptr;
if (context_) {
context_->DetachHost();
context_ = nullptr;
}
if (HasPlaceholderCanvas() && GetTopExecutionContext() &&
GetTopExecutionContext()->IsWorkerGlobalScope()) {
WorkerAnimationFrameProvider* animation_frame_provider =
To<WorkerGlobalScope>(GetTopExecutionContext())
->GetAnimationFrameProvider();
if (animation_frame_provider)
animation_frame_provider->DeregisterOffscreenCanvas(this);
}
}
| 173,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void XMLHttpRequest::didFailRedirectCheck()
{
networkError();
}
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void XMLHttpRequest::didFailRedirectCheck()
{
handleNetworkError();
}
| 171,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int c;
int x, y;
int tox, toy;
int ydest;
int i;
int colorMap[gdMaxColors];
/* Stretch vectors */
int *stx, *sty;
if (overflow2(sizeof(int), srcW)) {
return;
}
if (overflow2(sizeof(int), srcH)) {
return;
}
stx = (int *) gdMalloc (sizeof (int) * srcW);
sty = (int *) gdMalloc (sizeof (int) * srcH);
/* Fixed by Mao Morimoto 2.0.16 */
for (i = 0; (i < srcW); i++) {
stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;
}
for (i = 0; (i < srcH); i++) {
sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;
}
for (i = 0; (i < gdMaxColors); i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; (y < (srcY + srcH)); y++) {
for (ydest = 0; (ydest < sty[y - srcY]); ydest++) {
tox = dstX;
for (x = srcX; (x < (srcX + srcW)); x++) {
int nc = 0;
int mapTo;
if (!stx[x - srcX]) {
continue;
}
if (dst->trueColor) {
/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */
if (!src->trueColor) {
int tmp = gdImageGetPixel (src, x, y);
mapTo = gdImageGetTrueColorPixel (src, x, y);
if (gdImageGetTransparent (src) == tmp) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
} else {
/* TK: old code follows */
mapTo = gdImageGetTrueColorPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == mapTo) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
}
} else {
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox += stx[x - srcX];
continue;
}
if (src->trueColor) {
/* Remap to the palette available in the destination image. This is slow and works badly. */
mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),
gdTrueColorGetGreen(c),
gdTrueColorGetBlue(c),
gdTrueColorGetAlpha (c));
} else {
/* Have we established a mapping for this color? */
if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Find or create the best match */
/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */
nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),
gdImageGreen(src, c),
gdImageBlue(src, c),
gdImageAlpha(src, c));
}
colorMap[c] = nc;
}
mapTo = colorMap[c];
}
}
for (i = 0; (i < stx[x - srcX]); i++) {
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
}
toy++;
}
}
gdFree (stx);
gdFree (sty);
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190 | void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int c;
int x, y;
int tox, toy;
int ydest;
int i;
int colorMap[gdMaxColors];
/* Stretch vectors */
int *stx, *sty;
if (overflow2(sizeof(int), srcW)) {
return;
}
if (overflow2(sizeof(int), srcH)) {
return;
}
stx = (int *) gdMalloc (sizeof (int) * srcW);
sty = (int *) gdMalloc (sizeof (int) * srcH);
/* Fixed by Mao Morimoto 2.0.16 */
for (i = 0; (i < srcW); i++) {
stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;
}
for (i = 0; (i < srcH); i++) {
sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;
}
for (i = 0; (i < gdMaxColors); i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; (y < (srcY + srcH)); y++) {
for (ydest = 0; (ydest < sty[y - srcY]); ydest++) {
tox = dstX;
for (x = srcX; (x < (srcX + srcW)); x++) {
int nc = 0;
int mapTo;
if (!stx[x - srcX]) {
continue;
}
if (dst->trueColor) {
/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */
if (!src->trueColor) {
int tmp = gdImageGetPixel (src, x, y);
mapTo = gdImageGetTrueColorPixel (src, x, y);
if (gdImageGetTransparent (src) == tmp) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
} else {
/* TK: old code follows */
mapTo = gdImageGetTrueColorPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == mapTo) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
}
} else {
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox += stx[x - srcX];
continue;
}
if (src->trueColor) {
/* Remap to the palette available in the destination image. This is slow and works badly. */
mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),
gdTrueColorGetGreen(c),
gdTrueColorGetBlue(c),
gdTrueColorGetAlpha (c));
} else {
/* Have we established a mapping for this color? */
if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Find or create the best match */
/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */
nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),
gdImageGreen(src, c),
gdImageBlue(src, c),
gdImageAlpha(src, c));
}
colorMap[c] = nc;
}
mapTo = colorMap[c];
}
}
for (i = 0; (i < stx[x - srcX]); i++) {
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
}
toy++;
}
}
gdFree (stx);
gdFree (sty);
}
| 167,126 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
{
char *cipher_dir_string;
char *module_dir_string;
int block_size, max_key_length, use_key_length, i, count, iv_size;
unsigned long int data_size;
int *key_length_sizes;
char *key_s = NULL, *iv_s;
char *data_s;
MCRYPT td;
MCRYPT_GET_INI
td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
/* Checking for key-length */
max_key_length = mcrypt_enc_get_key_size(td);
if (key_len > max_key_length) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm");
}
key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */
use_key_length = key_len;
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, use_key_length);
} else if (count == 1) { /* only m_k_l = OK */
key_s = emalloc(key_length_sizes[0]);
memset(key_s, 0, key_length_sizes[0]);
memcpy(key_s, key, MIN(key_len, key_length_sizes[0]));
use_key_length = key_length_sizes[0];
} else { /* dertermine smallest supported key > length of requested key */
use_key_length = max_key_length; /* start with max key length */
for (i = 0; i < count; i++) {
if (key_length_sizes[i] >= key_len &&
key_length_sizes[i] < use_key_length)
{
use_key_length = key_length_sizes[i];
}
}
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, MIN(key_len, use_key_length));
}
mcrypt_free (key_length_sizes);
/* Check IV */
iv_s = NULL;
iv_size = mcrypt_enc_get_iv_size (td);
/* IV is required */
if (mcrypt_enc_mode_has_iv(td) == 1) {
if (argc == 5) {
if (iv_size != iv_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE);
} else {
iv_s = emalloc(iv_size + 1);
memcpy(iv_s, iv, iv_size);
}
} else if (argc == 4) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend");
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
}
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
RETURN_FALSE;
}
if (dencrypt == MCRYPT_ENCRYPT) {
mcrypt_generic(td, data_s, data_size);
} else {
mdecrypt_generic(td, data_s, data_size);
}
RETVAL_STRINGL(data_s, data_size, 1);
/* freeing vars */
mcrypt_generic_end(td);
if (key_s != NULL) {
efree (key_s);
}
if (iv_s != NULL) {
efree (iv_s);
}
efree (data_s);
}
/* }}} */
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
{
char *cipher_dir_string;
char *module_dir_string;
int block_size, max_key_length, use_key_length, i, count, iv_size;
unsigned long int data_size;
int *key_length_sizes;
char *key_s = NULL, *iv_s;
char *data_s;
MCRYPT td;
MCRYPT_GET_INI
td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
/* Checking for key-length */
max_key_length = mcrypt_enc_get_key_size(td);
if (key_len > max_key_length) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm");
}
key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */
use_key_length = key_len;
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, use_key_length);
} else if (count == 1) { /* only m_k_l = OK */
key_s = emalloc(key_length_sizes[0]);
memset(key_s, 0, key_length_sizes[0]);
memcpy(key_s, key, MIN(key_len, key_length_sizes[0]));
use_key_length = key_length_sizes[0];
} else { /* dertermine smallest supported key > length of requested key */
use_key_length = max_key_length; /* start with max key length */
for (i = 0; i < count; i++) {
if (key_length_sizes[i] >= key_len &&
key_length_sizes[i] < use_key_length)
{
use_key_length = key_length_sizes[i];
}
}
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, MIN(key_len, use_key_length));
}
mcrypt_free (key_length_sizes);
/* Check IV */
iv_s = NULL;
iv_size = mcrypt_enc_get_iv_size (td);
/* IV is required */
if (mcrypt_enc_mode_has_iv(td) == 1) {
if (argc == 5) {
if (iv_size != iv_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE);
} else {
iv_s = emalloc(iv_size + 1);
memcpy(iv_s, iv, iv_size);
}
} else if (argc == 4) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend");
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
}
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
RETURN_FALSE;
}
if (dencrypt == MCRYPT_ENCRYPT) {
mcrypt_generic(td, data_s, data_size);
} else {
mdecrypt_generic(td, data_s, data_size);
}
RETVAL_STRINGL(data_s, data_size, 1);
/* freeing vars */
mcrypt_generic_end(td);
if (key_s != NULL) {
efree (key_s);
}
if (iv_s != NULL) {
efree (iv_s);
}
efree (data_s);
}
/* }}} */
| 167,113 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
print_preview_context_.OnPrintPreview();
UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
if (!print_preview_context_.source_frame()) {
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!UpdatePrintSettings(print_preview_context_.source_frame(),
print_preview_context_.source_node(), settings)) {
if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(), print_pages_params_
? print_pages_params_->params.document_cookie
: 0));
notify_browser_of_print_failure_ = false; // Already sent.
}
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (print_pages_params_->params.is_first_request &&
!print_preview_context_.IsModifiable()) {
PrintHostMsg_SetOptionsFromDocument_Params options;
if (SetOptionsFromPdfDocument(&options))
Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options));
}
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(kSettingGenerateDraftData, &generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
PrepareFrameForPreviewDocument();
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID: | void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
CHECK_LE(ipc_nesting_level_, 1);
print_preview_context_.OnPrintPreview();
UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
if (!print_preview_context_.source_frame()) {
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!UpdatePrintSettings(print_preview_context_.source_frame(),
print_preview_context_.source_node(), settings)) {
if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(), print_pages_params_
? print_pages_params_->params.document_cookie
: 0));
notify_browser_of_print_failure_ = false; // Already sent.
}
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (print_pages_params_->params.is_first_request &&
!print_preview_context_.IsModifiable()) {
PrintHostMsg_SetOptionsFromDocument_Params options;
if (SetOptionsFromPdfDocument(&options))
Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options));
}
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(kSettingGenerateDraftData, &generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
PrepareFrameForPreviewDocument();
}
| 171,876 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth,
int out_depth)
{
if (out_depth == 16 && in_depth != 16 &&
pm->calculations_use_input_precision)
return 257;
else
return 1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static int output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth,
static int output_quantization_factor(const png_modifier *pm, int in_depth,
int out_depth)
{
if (out_depth == 16 && in_depth != 16 &&
pm->calculations_use_input_precision)
return 257;
else
return 1;
}
| 173,676 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CleanUp(DownloadId id) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Cancel());
download_file_manager_->CancelDownload(id);
EXPECT_TRUE(NULL == download_file_manager_->GetDownloadFile(id));
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void CleanUp(DownloadId id) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Cancel());
download_file_manager_->CancelDownload(id);
EXPECT_EQ(NULL, download_file_manager_->GetDownloadFile(id));
}
| 170,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual uint8_t* GetReference(int block_idx) {
return reference_data_ + block_idx * kDataBlockSize;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual uint8_t* GetReference(int block_idx) {
virtual uint8_t *GetReference(int block_idx) {
#if CONFIG_VP9_HIGHBITDEPTH
if (use_high_bit_depth_)
return CONVERT_TO_BYTEPTR(CONVERT_TO_SHORTPTR(reference_data_) +
block_idx * kDataBlockSize);
#endif // CONFIG_VP9_HIGHBITDEPTH
return reference_data_ + block_idx * kDataBlockSize;
}
| 174,573 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xlate_to_uni(const unsigned char *name, int len, unsigned char *outname,
int *longlen, int *outlen, int escape, int utf8,
struct nls_table *nls)
{
const unsigned char *ip;
unsigned char nc;
unsigned char *op;
unsigned int ec;
int i, k, fill;
int charlen;
if (utf8) {
*outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname);
if (*outlen < 0)
return *outlen;
else if (*outlen > FAT_LFN_LEN)
return -ENAMETOOLONG;
op = &outname[*outlen * sizeof(wchar_t)];
} else {
if (nls) {
for (i = 0, ip = name, op = outname, *outlen = 0;
i < len && *outlen <= FAT_LFN_LEN;
*outlen += 1)
{
if (escape && (*ip == ':')) {
if (i > len - 5)
return -EINVAL;
ec = 0;
for (k = 1; k < 5; k++) {
nc = ip[k];
ec <<= 4;
if (nc >= '0' && nc <= '9') {
ec |= nc - '0';
continue;
}
if (nc >= 'a' && nc <= 'f') {
ec |= nc - ('a' - 10);
continue;
}
if (nc >= 'A' && nc <= 'F') {
ec |= nc - ('A' - 10);
continue;
}
return -EINVAL;
}
*op++ = ec & 0xFF;
*op++ = ec >> 8;
ip += 5;
i += 5;
} else {
if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0)
return -EINVAL;
ip += charlen;
i += charlen;
op += 2;
}
}
if (i < len)
return -ENAMETOOLONG;
} else {
for (i = 0, ip = name, op = outname, *outlen = 0;
i < len && *outlen <= FAT_LFN_LEN;
i++, *outlen += 1)
{
*op++ = *ip++;
*op++ = 0;
}
if (i < len)
return -ENAMETOOLONG;
}
}
*longlen = *outlen;
if (*outlen % 13) {
*op++ = 0;
*op++ = 0;
*outlen += 1;
if (*outlen % 13) {
fill = 13 - (*outlen % 13);
for (i = 0; i < fill; i++) {
*op++ = 0xff;
*op++ = 0xff;
}
*outlen += fill;
}
}
return 0;
}
Commit Message: NLS: improve UTF8 -> UTF16 string conversion routine
The utf8s_to_utf16s conversion routine needs to be improved. Unlike
its utf16s_to_utf8s sibling, it doesn't accept arguments specifying
the maximum length of the output buffer or the endianness of its
16-bit output.
This patch (as1501) adds the two missing arguments, and adjusts the
only two places in the kernel where the function is called. A
follow-on patch will add a third caller that does utilize the new
capabilities.
The two conversion routines are still annoyingly inconsistent in the
way they handle invalid byte combinations. But that's a subject for a
different patch.
Signed-off-by: Alan Stern <[email protected]>
CC: Clemens Ladisch <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | xlate_to_uni(const unsigned char *name, int len, unsigned char *outname,
int *longlen, int *outlen, int escape, int utf8,
struct nls_table *nls)
{
const unsigned char *ip;
unsigned char nc;
unsigned char *op;
unsigned int ec;
int i, k, fill;
int charlen;
if (utf8) {
*outlen = utf8s_to_utf16s(name, len, UTF16_HOST_ENDIAN,
(wchar_t *) outname, FAT_LFN_LEN + 2);
if (*outlen < 0)
return *outlen;
else if (*outlen > FAT_LFN_LEN)
return -ENAMETOOLONG;
op = &outname[*outlen * sizeof(wchar_t)];
} else {
if (nls) {
for (i = 0, ip = name, op = outname, *outlen = 0;
i < len && *outlen <= FAT_LFN_LEN;
*outlen += 1)
{
if (escape && (*ip == ':')) {
if (i > len - 5)
return -EINVAL;
ec = 0;
for (k = 1; k < 5; k++) {
nc = ip[k];
ec <<= 4;
if (nc >= '0' && nc <= '9') {
ec |= nc - '0';
continue;
}
if (nc >= 'a' && nc <= 'f') {
ec |= nc - ('a' - 10);
continue;
}
if (nc >= 'A' && nc <= 'F') {
ec |= nc - ('A' - 10);
continue;
}
return -EINVAL;
}
*op++ = ec & 0xFF;
*op++ = ec >> 8;
ip += 5;
i += 5;
} else {
if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0)
return -EINVAL;
ip += charlen;
i += charlen;
op += 2;
}
}
if (i < len)
return -ENAMETOOLONG;
} else {
for (i = 0, ip = name, op = outname, *outlen = 0;
i < len && *outlen <= FAT_LFN_LEN;
i++, *outlen += 1)
{
*op++ = *ip++;
*op++ = 0;
}
if (i < len)
return -ENAMETOOLONG;
}
}
*longlen = *outlen;
if (*outlen % 13) {
*op++ = 0;
*op++ = 0;
*outlen += 1;
if (*outlen % 13) {
fill = 13 - (*outlen % 13);
for (i = 0; i < fill; i++) {
*op++ = 0xff;
*op++ = 0xff;
}
*outlen += fill;
}
}
return 0;
}
| 166,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const char *string_of_NPNVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPNVxDisplay);
_(NPNVxtAppContext);
_(NPNVnetscapeWindow);
_(NPNVjavascriptEnabledBool);
_(NPNVasdEnabledBool);
_(NPNVisOfflineBool);
_(NPNVserviceManager);
_(NPNVDOMElement);
_(NPNVDOMWindow);
_(NPNVToolkit);
_(NPNVSupportsXEmbedBool);
_(NPNVWindowNPObject);
_(NPNVPluginElementNPObject);
_(NPNVSupportsWindowless);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPNVserviceManager);
_(11, NPNVDOMElement);
_(12, NPNVDOMWindow);
_(13, NPNVToolkit);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264 | const char *string_of_NPNVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPNVxDisplay);
_(NPNVxtAppContext);
_(NPNVnetscapeWindow);
_(NPNVjavascriptEnabledBool);
_(NPNVasdEnabledBool);
_(NPNVisOfflineBool);
_(NPNVserviceManager);
_(NPNVDOMElement);
_(NPNVDOMWindow);
_(NPNVToolkit);
_(NPNVSupportsXEmbedBool);
_(NPNVWindowNPObject);
_(NPNVPluginElementNPObject);
_(NPNVSupportsWindowless);
_(NPNVprivateModeBool);
_(NPNVsupportsAdvancedKeyHandling);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPNVserviceManager);
_(11, NPNVDOMElement);
_(12, NPNVDOMWindow);
_(13, NPNVToolkit);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
| 165,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateStringArray( const char **strings, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateString( strings[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateStringArray( const char **strings, int count )
cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int64_t)num;}return item;}
cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);if(!item->valuestring){cJSON_Delete(item);return 0;}}return item;}
cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
/* Create Arrays: */
cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
/* Duplication */
cJSON *cJSON_Duplicate(cJSON *item,int recurse)
{
cJSON *newitem,*cptr,*nptr=0,*newchild;
/* Bail on bad ptr */
if (!item) return 0;
/* Create new item */
newitem=cJSON_New_Item();
if (!newitem) return 0;
/* Copy over all vars */
newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble;
if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}}
if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}}
/* If non-recursive, then we're done! */
if (!recurse) return newitem;
/* Walk the ->next chain for the child. */
cptr=item->child;
while (cptr)
{
newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild) {cJSON_Delete(newitem);return 0;}
if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */
cptr=cptr->next;
}
return newitem;
}
void cJSON_Minify(char *json)
{
char *into=json;
while (*json)
{
if (*json==' ') json++;
else if (*json=='\t') json++; /* Whitespace characters. */
else if (*json=='\r') json++;
else if (*json=='\n') json++;
else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */
else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */
else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */
else *into++=*json++; /* All other characters. */
}
*into=0; /* and null-terminate. */
}
| 167,279 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostViewAura::OnLostResources() {
image_transport_clients_.clear();
current_surface_ = 0;
protection_state_id_ = 0;
current_surface_is_protected_ = true;
current_surface_in_use_by_compositor_ = true;
surface_route_id_ = 0;
UpdateExternalTexture();
locks_pending_commit_.clear();
DCHECK(!shared_surface_handle_.is_null());
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
factory->DestroySharedSurfaceHandle(shared_surface_handle_);
shared_surface_handle_ = factory->CreateSharedSurfaceHandle();
host_->CompositingSurfaceUpdated();
host_->ScheduleComposite();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostViewAura::OnLostResources() {
image_transport_clients_.clear();
current_surface_ = 0;
UpdateExternalTexture();
locks_pending_commit_.clear();
DCHECK(!shared_surface_handle_.is_null());
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
factory->DestroySharedSurfaceHandle(shared_surface_handle_);
shared_surface_handle_ = factory->CreateSharedSurfaceHandle();
host_->CompositingSurfaceUpdated();
host_->ScheduleComposite();
}
| 171,381 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int lz4_uncompress(const char *source, char *dest, int osize)
{
const BYTE *ip = (const BYTE *) source;
const BYTE *ref;
BYTE *op = (BYTE *) dest;
BYTE * const oend = op + osize;
BYTE *cpy;
unsigned token;
size_t length;
size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
#endif
while (1) {
/* get runlength */
token = *ip++;
length = (token >> ML_BITS);
if (length == RUN_MASK) {
size_t len;
len = *ip++;
for (; len == 255; length += 255)
len = *ip++;
length += len;
}
/* copy literals */
cpy = op + length;
if (unlikely(cpy > oend - COPYLENGTH)) {
/*
* Error: not enough place for another match
* (min 4) + 5 literals
*/
if (cpy != oend)
goto _output_error;
memcpy(op, ip, length);
ip += length;
break; /* EOF */
}
LZ4_WILDCOPY(ip, op, cpy);
ip -= (op - cpy);
op = cpy;
/* get offset */
LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip);
ip += 2;
/* Error: offset create reference outside destination buffer */
if (unlikely(ref < (BYTE *const) dest))
goto _output_error;
/* get matchlength */
length = token & ML_MASK;
if (length == ML_MASK) {
for (; *ip == 255; length += 255)
ip++;
length += *ip++;
}
/* copy repeated sequence */
if (unlikely((op - ref) < STEPSIZE)) {
#if LZ4_ARCH64
size_t dec64 = dec64table[op - ref];
#else
const int dec64 = 0;
#endif
op[0] = ref[0];
op[1] = ref[1];
op[2] = ref[2];
op[3] = ref[3];
op += 4;
ref += 4;
ref -= dec32table[op-ref];
PUT4(ref, op);
op += STEPSIZE - 4;
ref -= dec64;
} else {
LZ4_COPYSTEP(ref, op);
}
cpy = op + length - (STEPSIZE - 4);
if (cpy > (oend - COPYLENGTH)) {
/* Error: request to write beyond destination buffer */
if (cpy > oend)
goto _output_error;
LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH));
while (op < cpy)
*op++ = *ref++;
op = cpy;
/*
* Check EOF (should never happen, since last 5 bytes
* are supposed to be literals)
*/
if (op == oend)
goto _output_error;
continue;
}
LZ4_SECURECOPY(ref, op, cpy);
op = cpy; /* correction */
}
/* end of decoding */
return (int) (((char *)ip) - source);
/* write overflow error detected */
_output_error:
return (int) (-(((char *)ip) - source));
}
Commit Message: lz4: ensure length does not wrap
Given some pathologically compressed data, lz4 could possibly decide to
wrap a few internal variables, causing unknown things to happen. Catch
this before the wrapping happens and abort the decompression.
Reported-by: "Don A. Bailey" <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-20 | static int lz4_uncompress(const char *source, char *dest, int osize)
{
const BYTE *ip = (const BYTE *) source;
const BYTE *ref;
BYTE *op = (BYTE *) dest;
BYTE * const oend = op + osize;
BYTE *cpy;
unsigned token;
size_t length;
size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
#endif
while (1) {
/* get runlength */
token = *ip++;
length = (token >> ML_BITS);
if (length == RUN_MASK) {
size_t len;
len = *ip++;
for (; len == 255; length += 255)
len = *ip++;
if (unlikely(length > (size_t)(length + len)))
goto _output_error;
length += len;
}
/* copy literals */
cpy = op + length;
if (unlikely(cpy > oend - COPYLENGTH)) {
/*
* Error: not enough place for another match
* (min 4) + 5 literals
*/
if (cpy != oend)
goto _output_error;
memcpy(op, ip, length);
ip += length;
break; /* EOF */
}
LZ4_WILDCOPY(ip, op, cpy);
ip -= (op - cpy);
op = cpy;
/* get offset */
LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip);
ip += 2;
/* Error: offset create reference outside destination buffer */
if (unlikely(ref < (BYTE *const) dest))
goto _output_error;
/* get matchlength */
length = token & ML_MASK;
if (length == ML_MASK) {
for (; *ip == 255; length += 255)
ip++;
length += *ip++;
}
/* copy repeated sequence */
if (unlikely((op - ref) < STEPSIZE)) {
#if LZ4_ARCH64
size_t dec64 = dec64table[op - ref];
#else
const int dec64 = 0;
#endif
op[0] = ref[0];
op[1] = ref[1];
op[2] = ref[2];
op[3] = ref[3];
op += 4;
ref += 4;
ref -= dec32table[op-ref];
PUT4(ref, op);
op += STEPSIZE - 4;
ref -= dec64;
} else {
LZ4_COPYSTEP(ref, op);
}
cpy = op + length - (STEPSIZE - 4);
if (cpy > (oend - COPYLENGTH)) {
/* Error: request to write beyond destination buffer */
if (cpy > oend)
goto _output_error;
LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH));
while (op < cpy)
*op++ = *ref++;
op = cpy;
/*
* Check EOF (should never happen, since last 5 bytes
* are supposed to be literals)
*/
if (op == oend)
goto _output_error;
continue;
}
LZ4_SECURECOPY(ref, op, cpy);
op = cpy; /* correction */
}
/* end of decoding */
return (int) (((char *)ip) - source);
/* write overflow error detected */
_output_error:
return (int) (-(((char *)ip) - source));
}
| 166,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct kioctx *ioctx_alloc(unsigned nr_events)
{
struct mm_struct *mm = current->mm;
struct kioctx *ctx;
int err = -ENOMEM;
/*
* We keep track of the number of available ringbuffer slots, to prevent
* overflow (reqs_available), and we also use percpu counters for this.
*
* So since up to half the slots might be on other cpu's percpu counters
* and unavailable, double nr_events so userspace sees what they
* expected: additionally, we move req_batch slots to/from percpu
* counters at a time, so make sure that isn't 0:
*/
nr_events = max(nr_events, num_possible_cpus() * 4);
nr_events *= 2;
/* Prevent overflows */
if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
(nr_events > (0x10000000U / sizeof(struct kiocb)))) {
pr_debug("ENOMEM: nr_events too high\n");
return ERR_PTR(-EINVAL);
}
if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
return ERR_PTR(-EAGAIN);
ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
if (!ctx)
return ERR_PTR(-ENOMEM);
ctx->max_reqs = nr_events;
if (percpu_ref_init(&ctx->users, free_ioctx_users))
goto err;
if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs))
goto err;
spin_lock_init(&ctx->ctx_lock);
spin_lock_init(&ctx->completion_lock);
mutex_init(&ctx->ring_lock);
init_waitqueue_head(&ctx->wait);
INIT_LIST_HEAD(&ctx->active_reqs);
ctx->cpu = alloc_percpu(struct kioctx_cpu);
if (!ctx->cpu)
goto err;
if (aio_setup_ring(ctx) < 0)
goto err;
atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
if (ctx->req_batch < 1)
ctx->req_batch = 1;
/* limit the number of system wide aios */
spin_lock(&aio_nr_lock);
if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
aio_nr + nr_events < aio_nr) {
spin_unlock(&aio_nr_lock);
err = -EAGAIN;
goto err;
}
aio_nr += ctx->max_reqs;
spin_unlock(&aio_nr_lock);
percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
err = ioctx_add_table(ctx, mm);
if (err)
goto err_cleanup;
pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
ctx, ctx->user_id, mm, ctx->nr_events);
return ctx;
err_cleanup:
aio_nr_sub(ctx->max_reqs);
err:
aio_free_ring(ctx);
free_percpu(ctx->cpu);
free_percpu(ctx->reqs.pcpu_count);
free_percpu(ctx->users.pcpu_count);
kmem_cache_free(kioctx_cachep, ctx);
pr_debug("error allocating ioctx %d\n", err);
return ERR_PTR(err);
}
Commit Message: aio: prevent double free in ioctx_alloc
ioctx_alloc() calls aio_setup_ring() to allocate a ring. If aio_setup_ring()
fails to do so it would call aio_free_ring() before returning, but
ioctx_alloc() would call aio_free_ring() again causing a double free of
the ring.
This is easily reproducible from userspace.
Signed-off-by: Sasha Levin <[email protected]>
Signed-off-by: Benjamin LaHaise <[email protected]>
CWE ID: CWE-399 | static struct kioctx *ioctx_alloc(unsigned nr_events)
{
struct mm_struct *mm = current->mm;
struct kioctx *ctx;
int err = -ENOMEM;
/*
* We keep track of the number of available ringbuffer slots, to prevent
* overflow (reqs_available), and we also use percpu counters for this.
*
* So since up to half the slots might be on other cpu's percpu counters
* and unavailable, double nr_events so userspace sees what they
* expected: additionally, we move req_batch slots to/from percpu
* counters at a time, so make sure that isn't 0:
*/
nr_events = max(nr_events, num_possible_cpus() * 4);
nr_events *= 2;
/* Prevent overflows */
if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
(nr_events > (0x10000000U / sizeof(struct kiocb)))) {
pr_debug("ENOMEM: nr_events too high\n");
return ERR_PTR(-EINVAL);
}
if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
return ERR_PTR(-EAGAIN);
ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
if (!ctx)
return ERR_PTR(-ENOMEM);
ctx->max_reqs = nr_events;
if (percpu_ref_init(&ctx->users, free_ioctx_users))
goto err;
if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs))
goto err;
spin_lock_init(&ctx->ctx_lock);
spin_lock_init(&ctx->completion_lock);
mutex_init(&ctx->ring_lock);
init_waitqueue_head(&ctx->wait);
INIT_LIST_HEAD(&ctx->active_reqs);
ctx->cpu = alloc_percpu(struct kioctx_cpu);
if (!ctx->cpu)
goto err;
if (aio_setup_ring(ctx) < 0)
goto err;
atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
if (ctx->req_batch < 1)
ctx->req_batch = 1;
/* limit the number of system wide aios */
spin_lock(&aio_nr_lock);
if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
aio_nr + nr_events < aio_nr) {
spin_unlock(&aio_nr_lock);
err = -EAGAIN;
goto err;
}
aio_nr += ctx->max_reqs;
spin_unlock(&aio_nr_lock);
percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
err = ioctx_add_table(ctx, mm);
if (err)
goto err_cleanup;
pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
ctx, ctx->user_id, mm, ctx->nr_events);
return ctx;
err_cleanup:
aio_nr_sub(ctx->max_reqs);
err:
free_percpu(ctx->cpu);
free_percpu(ctx->reqs.pcpu_count);
free_percpu(ctx->users.pcpu_count);
kmem_cache_free(kioctx_cachep, ctx);
pr_debug("error allocating ioctx %d\n", err);
return ERR_PTR(err);
}
| 166,468 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static const char *parse_object( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '{' ) {
/* Not an object! */
ep = value;
return 0;
}
item->type = cJSON_Object;
value =skip( value + 1 );
if ( *value == '}' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0;
if ( ! ( value = skip( parse_string( child, skip( value ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_string( child, skip( value + 1 ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
}
if ( *value == '}' )
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static const char *parse_object( cJSON *item, const char *value )
static const char *parse_object(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='{') {*ep=value;return 0;} /* not an object! */
item->type=cJSON_Object;
value=skip(value+1);
if (*value=='}') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0;
value=skip(parse_string(child,skip(value),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_string(child,skip(value+1),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
}
| 167,303 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods());
return descriptors->size();
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual size_t GetNumActiveInputMethods() {
scoped_ptr<input_method::InputMethodDescriptors> descriptors(
GetActiveInputMethods());
return descriptors->size();
}
| 170,491 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01 && i < gemsafe_cert_max) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
| 169,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
assert((cc0%rowsize)==0);
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
if((cc0%rowsize)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
"%s", "(cc0%rowsize)!=0");
return 0;
}
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
| 166,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int BlobURLRequestJob::ComputeBytesToRead() const {
int64 current_item_remaining_bytes =
item_length_list_[current_item_index_] - current_item_offset_;
int64 remaining_bytes = std::min(current_item_remaining_bytes,
remaining_bytes_);
return static_cast<int>(std::min(
static_cast<int64>(read_buf_->BytesRemaining()),
remaining_bytes));
}
Commit Message: Avoid integer overflows in BlobURLRequestJob.
BUG=169685
Review URL: https://chromiumcodereview.appspot.com/12047012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | int BlobURLRequestJob::ComputeBytesToRead() const {
int64 current_item_length = item_length_list_[current_item_index_];
int64 item_remaining = current_item_length - current_item_offset_;
int64 buf_remaining = read_buf_->BytesRemaining();
int64 max_remaining = std::numeric_limits<int>::max();
int64 min = std::min(std::min(std::min(item_remaining,
buf_remaining),
remaining_bytes_),
max_remaining);
return static_cast<int>(min);
}
| 171,397 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Verify_StoreExistingGroup() {
EXPECT_TRUE(delegate()->stored_group_success_);
EXPECT_EQ(group_.get(), delegate()->stored_group_.get());
EXPECT_EQ(cache2_.get(), group_->newest_complete_cache());
EXPECT_TRUE(cache2_->is_complete());
AppCacheDatabase::GroupRecord group_record;
AppCacheDatabase::CacheRecord cache_record;
EXPECT_TRUE(database()->FindGroup(1, &group_record));
EXPECT_TRUE(database()->FindCache(2, &cache_record));
EXPECT_FALSE(database()->FindCache(1, &cache_record));
EXPECT_EQ(kDefaultEntrySize + 100, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void Verify_StoreExistingGroup() {
EXPECT_TRUE(delegate()->stored_group_success_);
EXPECT_EQ(group_.get(), delegate()->stored_group_.get());
EXPECT_EQ(cache2_.get(), group_->newest_complete_cache());
EXPECT_TRUE(cache2_->is_complete());
AppCacheDatabase::GroupRecord group_record;
AppCacheDatabase::CacheRecord cache_record;
EXPECT_TRUE(database()->FindGroup(1, &group_record));
EXPECT_TRUE(database()->FindCache(2, &cache_record));
EXPECT_FALSE(database()->FindCache(1, &cache_record));
EXPECT_EQ(kDefaultEntrySize + 100 + kDefaultEntryPadding + 1000,
storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100 + 1000, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
| 172,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,
u64 param3, u64 param4)
{
int rc;
u64 base_addr, size;
/* If user manually set "flags", make sure it is legal */
if (flags && (flags &
~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))
return -EINVAL;
/*
* We need extra sanity checks for memory errors.
* Other types leap directly to injection.
*/
/* ensure param1/param2 existed */
if (!(param_extension || acpi5))
goto inject;
/* ensure injection is memory related */
if (type & ACPI5_VENDOR_BIT) {
if (vendor_flags != SETWA_FLAGS_MEM)
goto inject;
} else if (!(type & MEM_ERROR_MASK) && !(flags & SETWA_FLAGS_MEM))
goto inject;
/*
* Disallow crazy address masks that give BIOS leeway to pick
* injection address almost anywhere. Insist on page or
* better granularity and that target address is normal RAM or
* NVDIMM.
*/
base_addr = param1 & param2;
size = ~param2 + 1;
if (((param2 & PAGE_MASK) != PAGE_MASK) ||
((region_intersects(base_addr, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE)
!= REGION_INTERSECTS) &&
(region_intersects(base_addr, size, IORESOURCE_MEM, IORES_DESC_PERSISTENT_MEMORY)
!= REGION_INTERSECTS)))
return -EINVAL;
inject:
mutex_lock(&einj_mutex);
rc = __einj_error_inject(type, flags, param1, param2, param3, param4);
mutex_unlock(&einj_mutex);
return rc;
}
Commit Message: acpi: Disable APEI error injection if securelevel is set
ACPI provides an error injection mechanism, EINJ, for debugging and testing
the ACPI Platform Error Interface (APEI) and other RAS features. If
supported by the firmware, ACPI specification 5.0 and later provide for a
way to specify a physical memory address to which to inject the error.
Injecting errors through EINJ can produce errors which to the platform are
indistinguishable from real hardware errors. This can have undesirable
side-effects, such as causing the platform to mark hardware as needing
replacement.
While it does not provide a method to load unauthenticated privileged code,
the effect of these errors may persist across reboots and affect trust in
the underlying hardware, so disable error injection through EINJ if
securelevel is set.
Signed-off-by: Linn Crosetto <[email protected]>
CWE ID: CWE-74 | static int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,
u64 param3, u64 param4)
{
int rc;
u64 base_addr, size;
if (get_securelevel() > 0)
return -EPERM;
/* If user manually set "flags", make sure it is legal */
if (flags && (flags &
~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))
return -EINVAL;
/*
* We need extra sanity checks for memory errors.
* Other types leap directly to injection.
*/
/* ensure param1/param2 existed */
if (!(param_extension || acpi5))
goto inject;
/* ensure injection is memory related */
if (type & ACPI5_VENDOR_BIT) {
if (vendor_flags != SETWA_FLAGS_MEM)
goto inject;
} else if (!(type & MEM_ERROR_MASK) && !(flags & SETWA_FLAGS_MEM))
goto inject;
/*
* Disallow crazy address masks that give BIOS leeway to pick
* injection address almost anywhere. Insist on page or
* better granularity and that target address is normal RAM or
* NVDIMM.
*/
base_addr = param1 & param2;
size = ~param2 + 1;
if (((param2 & PAGE_MASK) != PAGE_MASK) ||
((region_intersects(base_addr, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE)
!= REGION_INTERSECTS) &&
(region_intersects(base_addr, size, IORESOURCE_MEM, IORES_DESC_PERSISTENT_MEMORY)
!= REGION_INTERSECTS)))
return -EINVAL;
inject:
mutex_lock(&einj_mutex);
rc = __einj_error_inject(type, flags, param1, param2, param3, param4);
mutex_unlock(&einj_mutex);
return rc;
}
| 168,837 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1608
CWE ID: CWE-125 | MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
| 170,207 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists(
int32 download_id,
const FilePath& unverified_path,
bool should_prompt,
bool is_forced_path,
content::DownloadDangerType danger_type,
const FilePath& default_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
FilePath target_path(unverified_path);
file_util::CreateDirectory(default_path);
FilePath dir = target_path.DirName();
FilePath filename = target_path.BaseName();
if (!file_util::PathIsWritable(dir)) {
VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
should_prompt = true;
PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir);
target_path = dir.Append(filename);
}
bool should_uniquify =
(!is_forced_path &&
(danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS ||
should_prompt));
bool should_overwrite =
(should_uniquify || is_forced_path);
bool should_create_marker = (should_uniquify && !should_prompt);
if (should_uniquify) {
int uniquifier =
download_util::GetUniquePathNumberWithCrDownload(target_path);
if (uniquifier > 0) {
target_path = target_path.InsertBeforeExtensionASCII(
StringPrintf(" (%d)", uniquifier));
} else if (uniquifier == -1) {
VLOG(1) << "Unable to find a unique path for suggested path \""
<< target_path.value() << "\"";
should_prompt = true;
}
}
if (should_create_marker)
file_util::WriteFile(download_util::GetCrDownloadPath(target_path), "", 0);
DownloadItem::TargetDisposition disposition;
if (should_prompt)
disposition = DownloadItem::TARGET_DISPOSITION_PROMPT;
else if (should_overwrite)
disposition = DownloadItem::TARGET_DISPOSITION_OVERWRITE;
else
disposition = DownloadItem::TARGET_DISPOSITION_UNIQUIFY;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&ChromeDownloadManagerDelegate::OnPathExistenceAvailable,
this, download_id, target_path, disposition, danger_type));
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists(
int32 download_id,
const FilePath& unverified_path,
bool should_prompt,
bool is_forced_path,
content::DownloadDangerType danger_type,
const FilePath& default_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
FilePath target_path(unverified_path);
file_util::CreateDirectory(default_path);
FilePath dir = target_path.DirName();
FilePath filename = target_path.BaseName();
if (!file_util::PathIsWritable(dir)) {
VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
should_prompt = true;
PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir);
target_path = dir.Append(filename);
}
bool should_uniquify =
(!is_forced_path &&
(danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS ||
should_prompt));
bool should_overwrite =
(should_uniquify || is_forced_path);
bool should_create_marker = (should_uniquify && !should_prompt);
if (should_uniquify) {
// the in-progress rename. Ditto for "Forced" downloads. None of the
int uniquifier =
download_util::GetUniquePathNumberWithCrDownload(target_path);
if (uniquifier > 0) {
target_path = target_path.InsertBeforeExtensionASCII(
StringPrintf(" (%d)", uniquifier));
} else if (uniquifier == -1) {
VLOG(1) << "Unable to find a unique path for suggested path \""
<< target_path.value() << "\"";
should_prompt = true;
}
}
if (should_create_marker)
file_util::WriteFile(download_util::GetCrDownloadPath(target_path), "", 0);
DownloadItem::TargetDisposition disposition;
if (should_prompt)
disposition = DownloadItem::TARGET_DISPOSITION_PROMPT;
else if (should_overwrite)
disposition = DownloadItem::TARGET_DISPOSITION_OVERWRITE;
else
disposition = DownloadItem::TARGET_DISPOSITION_UNIQUIFY;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&ChromeDownloadManagerDelegate::OnPathExistenceAvailable,
this, download_id, target_path, disposition, danger_type));
}
| 170,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
Commit Message: Fix for bug #72790 and bug #72799
CWE ID: CWE-476 | int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
if(ent->data == NULL) {
retval = FAILURE;
} else {
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
}
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
| 166,948 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void finalizeStreamTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().finalizeStream(blobRegistryContext->url);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static void finalizeStreamTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
if (WebBlobRegistry* registry = blobRegistry())
registry->finalizeStream(blobRegistryContext->url);
}
| 170,683 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const
{
if (m_allowStar)
return true;
KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL))
return true;
for (size_t i = 0; i < m_list.size(); ++i) {
if (m_list[i].matches(effectiveURL, redirectStatus))
return true;
}
return false;
}
Commit Message: Disallow CSP source * matching of data:, blob:, and filesystem: URLs
The CSP spec specifically excludes matching of data:, blob:, and
filesystem: URLs with the source '*' wildcard. This adds checks to make
sure that doesn't happen, along with tests.
BUG=534570
[email protected]
Review URL: https://codereview.chromium.org/1361763005
Cr-Commit-Position: refs/heads/master@{#350950}
CWE ID: CWE-264 | bool CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const
{
// The CSP spec specifically states that data:, blob:, and filesystem URLs
// should not be captured by a '*" source
// (http://www.w3.org/TR/CSP2/#source-list-guid-matching). Thus, in the
// case of a full wildcard, data:, blob:, and filesystem: URLs are
// explicitly checked for in the source list before allowing them through.
if (m_allowStar) {
if (url.protocolIs("blob") || url.protocolIs("data") || url.protocolIs("filesystem"))
return hasSourceMatchInList(url, redirectStatus);
return true;
}
KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL))
return true;
return hasSourceMatchInList(effectiveURL, redirectStatus);
}
| 171,789 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Horizontal_Sweep_Span( RAS_ARGS Short y,
FT_F26Dot6 x1,
FT_F26Dot6 x2,
PProfile left,
PProfile right )
{
FT_UNUSED( left );
FT_UNUSED( right );
if ( x2 - x1 < ras.precision )
{
Long e1, e2;
e1 = CEILING( x1 );
e2 = FLOOR ( x2 );
if ( e1 == e2 )
{
Byte f1;
PByte bits;
bits = ras.bTarget + ( y >> 3 );
f1 = (Byte)( 0x80 >> ( y & 7 ) );
e1 = TRUNC( e1 );
if ( e1 >= 0 && e1 < ras.target.rows )
{
PByte p;
p = bits - e1 * ras.target.pitch;
if ( ras.target.pitch > 0 )
p += ( ras.target.rows - 1 ) * ras.target.pitch;
p[0] |= f1;
}
}
}
}
Commit Message:
CWE ID: CWE-119 | Horizontal_Sweep_Span( RAS_ARGS Short y,
FT_F26Dot6 x1,
FT_F26Dot6 x2,
PProfile left,
PProfile right )
{
FT_UNUSED( left );
FT_UNUSED( right );
if ( x2 - x1 < ras.precision )
{
Long e1, e2;
e1 = CEILING( x1 );
e2 = FLOOR ( x2 );
if ( e1 == e2 )
{
Byte f1;
PByte bits;
bits = ras.bTarget + ( y >> 3 );
f1 = (Byte)( 0x80 >> ( y & 7 ) );
e1 = TRUNC( e1 );
if ( e1 >= 0 && (ULong)e1 < ras.target.rows )
{
PByte p;
p = bits - e1 * ras.target.pitch;
if ( ras.target.pitch > 0 )
p += ( ras.target.rows - 1 ) * ras.target.pitch;
p[0] |= f1;
}
}
}
}
| 164,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool WorkerProcessLauncherTest::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid())
return false;
channel_name_ = GenerateIpcChannelName(this);
if (!CreateIpcChannel(channel_name_, kIpcSecurityDescriptor, task_runner_,
delegate, &channel_server_)) {
return false;
}
exit_code_ = STILL_ACTIVE;
return DuplicateHandle(GetCurrentProcess(),
process_exit_event_,
GetCurrentProcess(),
process_exit_event_out->Receive(),
0,
FALSE,
DUPLICATE_SAME_ACCESS) != FALSE;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool WorkerProcessLauncherTest::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid())
return false;
channel_name_ = GenerateIpcChannelName(this);
ScopedHandle pipe;
if (!CreateIpcChannel(channel_name_, kIpcSecurityDescriptor, &pipe)) {
return false;
}
// Wrap the pipe into an IPC channel.
channel_server_.reset(new IPC::ChannelProxy(
IPC::ChannelHandle(pipe),
IPC::Channel::MODE_SERVER,
delegate,
task_runner_));
return DuplicateHandle(GetCurrentProcess(),
process_exit_event_,
GetCurrentProcess(),
process_exit_event_out->Receive(),
0,
FALSE,
DUPLICATE_SAME_ACCESS) != FALSE;
}
| 171,551 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PageHandler::PageHandler(EmulationHandler* emulation_handler)
: DevToolsDomainHandler(Page::Metainfo::domainName),
enabled_(false),
screencast_enabled_(false),
screencast_quality_(kDefaultScreenshotQuality),
screencast_max_width_(-1),
screencast_max_height_(-1),
capture_every_nth_frame_(1),
capture_retry_count_(0),
has_compositor_frame_metadata_(false),
session_id_(0),
frame_counter_(0),
frames_in_flight_(0),
video_consumer_(nullptr),
last_surface_size_(gfx::Size()),
host_(nullptr),
emulation_handler_(emulation_handler),
observer_(this),
weak_factory_(this) {
bool create_video_consumer = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
create_video_consumer = false;
#endif
if (create_video_consumer) {
video_consumer_ = std::make_unique<DevToolsVideoConsumer>(
base::BindRepeating(&PageHandler::OnFrameFromVideoConsumer,
weak_factory_.GetWeakPtr()));
}
DCHECK(emulation_handler_);
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20 | PageHandler::PageHandler(EmulationHandler* emulation_handler)
PageHandler::PageHandler(EmulationHandler* emulation_handler,
bool allow_set_download_behavior)
: DevToolsDomainHandler(Page::Metainfo::domainName),
enabled_(false),
screencast_enabled_(false),
screencast_quality_(kDefaultScreenshotQuality),
screencast_max_width_(-1),
screencast_max_height_(-1),
capture_every_nth_frame_(1),
capture_retry_count_(0),
has_compositor_frame_metadata_(false),
session_id_(0),
frame_counter_(0),
frames_in_flight_(0),
video_consumer_(nullptr),
last_surface_size_(gfx::Size()),
host_(nullptr),
emulation_handler_(emulation_handler),
allow_set_download_behavior_(allow_set_download_behavior),
observer_(this),
weak_factory_(this) {
bool create_video_consumer = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
create_video_consumer = false;
#endif
if (create_video_consumer) {
video_consumer_ = std::make_unique<DevToolsVideoConsumer>(
base::BindRepeating(&PageHandler::OnFrameFromVideoConsumer,
weak_factory_.GetWeakPtr()));
}
DCHECK(emulation_handler_);
}
| 172,607 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static zval *_xml_xmlchar_zval(const XML_Char *s, int len, const XML_Char *encoding)
{
zval *ret;
MAKE_STD_ZVAL(ret);
if (s == NULL) {
ZVAL_FALSE(ret);
return ret;
}
if (len == 0) {
len = _xml_xmlcharlen(s);
}
Z_TYPE_P(ret) = IS_STRING;
Z_STRVAL_P(ret) = xml_utf8_decode(s, len, &Z_STRLEN_P(ret), encoding);
return ret;
}
Commit Message:
CWE ID: CWE-119 | static zval *_xml_xmlchar_zval(const XML_Char *s, int len, const XML_Char *encoding)
{
zval *ret;
MAKE_STD_ZVAL(ret);
if (s == NULL) {
ZVAL_FALSE(ret);
return ret;
}
if (len == 0) {
len = _xml_xmlcharlen(s);
}
Z_TYPE_P(ret) = IS_STRING;
Z_STRVAL_P(ret) = xml_utf8_decode(s, len, &Z_STRLEN_P(ret), encoding);
return ret;
}
| 165,044 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
Commit Message: userns: Check uid_map's opener's fsuid, not the current fsuid
Signed-off-by: Andy Lutomirski <[email protected]>
CWE ID: CWE-264 | static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, file->f_cred->fsuid))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, file->f_cred->fsgid))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
| 169,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
Commit Message: Use strncmp when checking for large ascii multigets.
CWE ID: CWE-20 | static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (ptr - c->rcurr > 100 ||
(strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
| 165,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GpuChannelHost* BrowserGpuChannelHostFactory::EstablishGpuChannelSync(
CauseForGpuLaunch cause_for_gpu_launch) {
if (gpu_channel_.get()) {
if (gpu_channel_->state() == GpuChannelHost::kLost)
gpu_channel_ = NULL;
else
return gpu_channel_.get();
}
GpuDataManagerImpl::GetInstance();
EstablishRequest request;
GetIOLoopProxy()->PostTask(
FROM_HERE,
base::Bind(
&BrowserGpuChannelHostFactory::EstablishGpuChannelOnIO,
base::Unretained(this),
&request,
cause_for_gpu_launch));
request.event.Wait();
if (request.channel_handle.name.empty() ||
request.gpu_process_handle == base::kNullProcessHandle)
return NULL;
base::ProcessHandle browser_process_for_gpu;
#if defined(OS_WIN)
DuplicateHandle(base::GetCurrentProcessHandle(),
base::GetCurrentProcessHandle(),
request.gpu_process_handle,
&browser_process_for_gpu,
PROCESS_DUP_HANDLE,
FALSE,
0);
#else
browser_process_for_gpu = base::GetCurrentProcessHandle();
#endif
gpu_channel_ = new GpuChannelHost(this, gpu_host_id_, gpu_client_id_);
gpu_channel_->set_gpu_info(request.gpu_info);
content::GetContentClient()->SetGpuInfo(request.gpu_info);
gpu_channel_->Connect(request.channel_handle, browser_process_for_gpu);
return gpu_channel_.get();
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | GpuChannelHost* BrowserGpuChannelHostFactory::EstablishGpuChannelSync(
CauseForGpuLaunch cause_for_gpu_launch) {
if (gpu_channel_.get()) {
if (gpu_channel_->state() == GpuChannelHost::kLost)
gpu_channel_ = NULL;
else
return gpu_channel_.get();
}
GpuDataManagerImpl::GetInstance();
EstablishRequest request;
GetIOLoopProxy()->PostTask(
FROM_HERE,
base::Bind(
&BrowserGpuChannelHostFactory::EstablishGpuChannelOnIO,
base::Unretained(this),
&request,
cause_for_gpu_launch));
request.event.Wait();
if (request.channel_handle.name.empty())
return NULL;
gpu_channel_ = new GpuChannelHost(this, gpu_host_id_, gpu_client_id_);
gpu_channel_->set_gpu_info(request.gpu_info);
content::GetContentClient()->SetGpuInfo(request.gpu_info);
gpu_channel_->Connect(request.channel_handle);
return gpu_channel_.get();
}
| 170,917 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED,
int argc, const char **argv)
{
void *cookiefile;
int i, debug = 0;
const char* user;
struct passwd *tpwd = NULL;
uid_t unlinkuid, fsuid;
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS)
pam_syslog(pamh, LOG_ERR, "error determining target user's name");
else {
tpwd = pam_modutil_getpwnam(pamh, user);
if (!tpwd)
pam_syslog(pamh, LOG_ERR, "error determining target user's UID");
else
unlinkuid = tpwd->pw_uid;
}
/* Parse arguments. We don't understand many, so no sense in breaking
* this into a separate function. */
for (i = 0; i < argc; i++) {
if (strcmp(argv[i], "debug") == 0) {
debug = 1;
continue;
}
if (strncmp(argv[i], "xauthpath=", 10) == 0) {
continue;
}
if (strncmp(argv[i], "systemuser=", 11) == 0) {
continue;
}
if (strncmp(argv[i], "targetuser=", 11) == 0) {
continue;
}
pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'",
argv[i]);
}
/* Try to retrieve the name of a file we created when the session was
* opened. */
if (pam_get_data(pamh, DATANAME, (const void**) &cookiefile) == PAM_SUCCESS) {
/* We'll only try to remove the file once. */
if (strlen((char*)cookiefile) > 0) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG, "removing `%s'",
(char*)cookiefile);
}
/* NFS with root_squash requires non-root user */
if (tpwd)
fsuid = setfsuid(unlinkuid);
unlink((char*)cookiefile);
if (tpwd)
setfsuid(fsuid);
*((char*)cookiefile) = '\0';
}
}
return PAM_SUCCESS;
}
Commit Message:
CWE ID: | pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED,
int argc, const char **argv)
{
int i, debug = 0;
const char *user;
const void *data;
const char *cookiefile;
struct passwd *tpwd;
uid_t fsuid;
/* Try to retrieve the name of a file we created when
* the session was opened. */
if (pam_get_data(pamh, DATANAME, &data) != PAM_SUCCESS)
return PAM_SUCCESS;
cookiefile = data;
/* Parse arguments. We don't understand many, so
* no sense in breaking this into a separate function. */
for (i = 0; i < argc; i++) {
if (strcmp(argv[i], "debug") == 0) {
debug = 1;
continue;
}
if (strncmp(argv[i], "xauthpath=", 10) == 0)
continue;
if (strncmp(argv[i], "systemuser=", 11) == 0)
continue;
if (strncmp(argv[i], "targetuser=", 11) == 0)
continue;
pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'",
argv[i]);
}
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) {
pam_syslog(pamh, LOG_ERR,
"error determining target user's name");
return PAM_SESSION_ERR;
}
if (!(tpwd = pam_modutil_getpwnam(pamh, user))) {
pam_syslog(pamh, LOG_ERR,
"error determining target user's UID");
return PAM_SESSION_ERR;
}
if (debug)
pam_syslog(pamh, LOG_DEBUG, "removing `%s'", cookiefile);
fsuid = setfsuid(tpwd->pw_uid);
unlink(cookiefile);
setfsuid(fsuid);
return PAM_SUCCESS;
}
| 164,789 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestOpenCallback()
: callback_(
base::Bind(&TestOpenCallback::SetResult, base::Unretained(this))) {}
Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback
Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback
migration, as they are copied and passed to others.
This CL updates them to pass new callbacks for each use to avoid the
copy of callbacks.
Bug: 714018
Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0
Reviewed-on: https://chromium-review.googlesource.com/527549
Reviewed-by: Ken Rockot <[email protected]>
Commit-Queue: Taiju Tsuiki <[email protected]>
Cr-Commit-Position: refs/heads/master@{#478549}
CWE ID: | TestOpenCallback()
| 171,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)));
}
Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas
BUG=354356
Review URL: https://codereview.chromium.org/211313003
git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), canvas->buffer() ? ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)) : nullptr);
}
| 171,394 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParsePI(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
const xmlChar *target;
xmlParserInputState state;
int count = 0;
if ((RAW == '<') && (NXT(1) == '?')) {
xmlParserInputPtr input = ctxt->input;
state = ctxt->instate;
ctxt->instate = XML_PARSER_PI;
/*
* this is a Processing Instruction.
*/
SKIP(2);
SHRINK;
/*
* Parse the target name and check for special support like
* namespace.
*/
target = xmlParsePITarget(ctxt);
if (target != NULL) {
if ((RAW == '?') && (NXT(1) == '>')) {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, NULL);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
cur = CUR;
if (!IS_BLANK(cur)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
"ParsePI: PI %s space expected\n", target);
}
SKIP_BLANKS;
cur = CUR_CHAR(l);
while (IS_CHAR(cur) && /* checked */
((cur != '?') || (NXT(1) != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
ctxt->instate = state;
return;
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
count = 0;
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (cur != '?') {
xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
"ParsePI: PI %s never end ...\n", target);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
#ifdef LIBXML_CATALOG_ENABLED
if (((state == XML_PARSER_MISC) ||
(state == XML_PARSER_START)) &&
(xmlStrEqual(target, XML_CATALOG_PI))) {
xmlCatalogAllow allow = xmlCatalogGetDefaults();
if ((allow == XML_CATA_ALLOW_DOCUMENT) ||
(allow == XML_CATA_ALLOW_ALL))
xmlParseCatalogPI(ctxt, buf);
}
#endif
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, buf);
}
xmlFree(buf);
} else {
xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);
}
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParsePI(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
const xmlChar *target;
xmlParserInputState state;
int count = 0;
if ((RAW == '<') && (NXT(1) == '?')) {
xmlParserInputPtr input = ctxt->input;
state = ctxt->instate;
ctxt->instate = XML_PARSER_PI;
/*
* this is a Processing Instruction.
*/
SKIP(2);
SHRINK;
/*
* Parse the target name and check for special support like
* namespace.
*/
target = xmlParsePITarget(ctxt);
if (target != NULL) {
if ((RAW == '?') && (NXT(1) == '>')) {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, NULL);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
cur = CUR;
if (!IS_BLANK(cur)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
"ParsePI: PI %s space expected\n", target);
}
SKIP_BLANKS;
cur = CUR_CHAR(l);
while (IS_CHAR(cur) && /* checked */
((cur != '?') || (NXT(1) != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
ctxt->instate = state;
return;
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
count = 0;
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (cur != '?') {
xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
"ParsePI: PI %s never end ...\n", target);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
#ifdef LIBXML_CATALOG_ENABLED
if (((state == XML_PARSER_MISC) ||
(state == XML_PARSER_START)) &&
(xmlStrEqual(target, XML_CATALOG_PI))) {
xmlCatalogAllow allow = xmlCatalogGetDefaults();
if ((allow == XML_CATA_ALLOW_DOCUMENT) ||
(allow == XML_CATA_ALLOW_ALL))
xmlParseCatalogPI(ctxt, buf);
}
#endif
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, buf);
}
xmlFree(buf);
} else {
xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);
}
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
}
}
| 171,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
size_t max_mem;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
#endif
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_MAXMEM:
max_mem = strtoull(jas_optarg, 0, 10);
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
jas_set_max_mem_usage(max_mem);
#endif
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
if (!(numcmpts = jas_image_numcmpts(image))) {
fprintf(stderr, "warning: image has no components\n");
}
if (numcmpts) {
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
} else {
width = 0;
height = 0;
depth = 0;
}
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
size_t max_mem;
size_t max_samples;
char optstr[32];
if (jas_init()) {
abort();
}
cmdname = argv[0];
max_samples = 64 * JAS_MEBI;
infile = 0;
verbose = 0;
debug = 0;
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
#endif
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_MAXSAMPLES:
max_samples = strtoull(jas_optarg, 0, 10);
break;
case OPT_MAXMEM:
max_mem = strtoull(jas_optarg, 0, 10);
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
jas_set_max_mem_usage(max_mem);
#endif
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
snprintf(optstr, sizeof(optstr), "max_samples=%-zu", max_samples);
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, optstr))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
if (!(fmtname = jas_image_fmttostr(fmtid))) {
jas_eprintf("format name lookup failed\n");
return EXIT_FAILURE;
}
if (!(numcmpts = jas_image_numcmpts(image))) {
fprintf(stderr, "warning: image has no components\n");
}
if (numcmpts) {
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
} else {
width = 0;
height = 0;
depth = 0;
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth,
JAS_CAST(long, jas_image_rawsize(image)));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
| 168,681 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebDevToolsAgentImpl::clearBrowserCookies()
{
m_client->clearBrowserCookies();
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void WebDevToolsAgentImpl::clearBrowserCookies()
| 171,349 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long restore_tm_user_regs(struct pt_regs *regs,
struct mcontext __user *sr,
struct mcontext __user *tm_sr)
{
long err;
unsigned long msr, msr_hi;
#ifdef CONFIG_VSX
int i;
#endif
/*
* restore general registers but not including MSR or SOFTE. Also
* take care of keeping r2 (TLS) intact if not a signal.
* See comment in signal_64.c:restore_tm_sigcontexts();
* TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR
* were set by the signal delivery.
*/
err = restore_general_regs(regs, tm_sr);
err |= restore_general_regs(¤t->thread.ckpt_regs, sr);
err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]);
err |= __get_user(msr, &sr->mc_gregs[PT_MSR]);
if (err)
return 1;
/* Restore the previous little-endian mode */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr/evr. That way, if we get preempted
* and another task grabs the FPU/Altivec/SPE, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
#ifdef CONFIG_ALTIVEC
regs->msr &= ~MSR_VEC;
if (msr & MSR_VEC) {
/* restore altivec registers from the stack */
if (__copy_from_user(¤t->thread.vr_state, &sr->mc_vregs,
sizeof(sr->mc_vregs)) ||
__copy_from_user(¤t->thread.transact_vr,
&tm_sr->mc_vregs,
sizeof(sr->mc_vregs)))
return 1;
} else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0,
ELF_NVRREG * sizeof(vector128));
memset(¤t->thread.transact_vr, 0,
ELF_NVRREG * sizeof(vector128));
}
/* Always get VRSAVE back */
if (__get_user(current->thread.vrsave,
(u32 __user *)&sr->mc_vregs[32]) ||
__get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_sr->mc_vregs[32]))
return 1;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1);
if (copy_fpr_from_user(current, &sr->mc_fregs) ||
copy_transact_fpr_from_user(current, &tm_sr->mc_fregs))
return 1;
#ifdef CONFIG_VSX
regs->msr &= ~MSR_VSX;
if (msr & MSR_VSX) {
/*
* Restore altivec registers from the stack to a local
* buffer, then write this out to the thread_struct
*/
if (copy_vsx_from_user(current, &sr->mc_vsregs) ||
copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs))
return 1;
} else if (current->thread.used_vsr)
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
#endif /* CONFIG_VSX */
#ifdef CONFIG_SPE
/* SPE regs are not checkpointed with TM, so this section is
* simply the same as in restore_user_regs().
*/
regs->msr &= ~MSR_SPE;
if (msr & MSR_SPE) {
if (__copy_from_user(current->thread.evr, &sr->mc_vregs,
ELF_NEVRREG * sizeof(u32)))
return 1;
} else if (current->thread.used_spe)
memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32));
/* Always get SPEFSCR back */
if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs
+ ELF_NEVRREG))
return 1;
#endif /* CONFIG_SPE */
/* Now, recheckpoint. This loads up all of the checkpointed (older)
* registers, including FP and V[S]Rs. After recheckpointing, the
* transactional versions should be loaded.
*/
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* Get the top half of the MSR */
if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR]))
return 1;
/* Pull in MSR TM from user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | ((msr_hi<<32) & MSR_TS_MASK);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return 0;
}
Commit Message: powerpc/tm: Block signal return setting invalid MSR state
Currently we allow both the MSR T and S bits to be set by userspace on
a signal return. Unfortunately this is a reserved configuration and
will cause a TM Bad Thing exception if attempted (via rfid).
This patch checks for this case in both the 32 and 64 bit signals
code. If both T and S are set, we mark the context as invalid.
Found using a syscall fuzzer.
Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context")
Cc: [email protected] # v3.9+
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
CWE ID: CWE-20 | static long restore_tm_user_regs(struct pt_regs *regs,
struct mcontext __user *sr,
struct mcontext __user *tm_sr)
{
long err;
unsigned long msr, msr_hi;
#ifdef CONFIG_VSX
int i;
#endif
/*
* restore general registers but not including MSR or SOFTE. Also
* take care of keeping r2 (TLS) intact if not a signal.
* See comment in signal_64.c:restore_tm_sigcontexts();
* TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR
* were set by the signal delivery.
*/
err = restore_general_regs(regs, tm_sr);
err |= restore_general_regs(¤t->thread.ckpt_regs, sr);
err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]);
err |= __get_user(msr, &sr->mc_gregs[PT_MSR]);
if (err)
return 1;
/* Restore the previous little-endian mode */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr/evr. That way, if we get preempted
* and another task grabs the FPU/Altivec/SPE, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
#ifdef CONFIG_ALTIVEC
regs->msr &= ~MSR_VEC;
if (msr & MSR_VEC) {
/* restore altivec registers from the stack */
if (__copy_from_user(¤t->thread.vr_state, &sr->mc_vregs,
sizeof(sr->mc_vregs)) ||
__copy_from_user(¤t->thread.transact_vr,
&tm_sr->mc_vregs,
sizeof(sr->mc_vregs)))
return 1;
} else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0,
ELF_NVRREG * sizeof(vector128));
memset(¤t->thread.transact_vr, 0,
ELF_NVRREG * sizeof(vector128));
}
/* Always get VRSAVE back */
if (__get_user(current->thread.vrsave,
(u32 __user *)&sr->mc_vregs[32]) ||
__get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_sr->mc_vregs[32]))
return 1;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1);
if (copy_fpr_from_user(current, &sr->mc_fregs) ||
copy_transact_fpr_from_user(current, &tm_sr->mc_fregs))
return 1;
#ifdef CONFIG_VSX
regs->msr &= ~MSR_VSX;
if (msr & MSR_VSX) {
/*
* Restore altivec registers from the stack to a local
* buffer, then write this out to the thread_struct
*/
if (copy_vsx_from_user(current, &sr->mc_vsregs) ||
copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs))
return 1;
} else if (current->thread.used_vsr)
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
#endif /* CONFIG_VSX */
#ifdef CONFIG_SPE
/* SPE regs are not checkpointed with TM, so this section is
* simply the same as in restore_user_regs().
*/
regs->msr &= ~MSR_SPE;
if (msr & MSR_SPE) {
if (__copy_from_user(current->thread.evr, &sr->mc_vregs,
ELF_NEVRREG * sizeof(u32)))
return 1;
} else if (current->thread.used_spe)
memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32));
/* Always get SPEFSCR back */
if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs
+ ELF_NEVRREG))
return 1;
#endif /* CONFIG_SPE */
/* Get the top half of the MSR from the user context */
if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR]))
return 1;
msr_hi <<= 32;
/* If TM bits are set to the reserved value, it's an invalid context */
if (MSR_TM_RESV(msr_hi))
return 1;
/* Pull in the MSR TM bits from the user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr_hi & MSR_TS_MASK);
/* Now, recheckpoint. This loads up all of the checkpointed (older)
* registers, including FP and V[S]Rs. After recheckpointing, the
* transactional versions should be loaded.
*/
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return 0;
}
| 167,481 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() {
if (texture_holder_->IsSkiaTextureHolder())
return;
texture_holder_ =
std::make_unique<SkiaTextureHolder>(std::move(texture_holder_));
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (texture_holder_->IsSkiaTextureHolder())
return;
texture_holder_ =
std::make_unique<SkiaTextureHolder>(std::move(texture_holder_));
}
| 172,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sample_to_timespec(const clockid_t which_clock,
union cpu_time_count cpu,
struct timespec *tp)
{
if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {
tp->tv_sec = div_long_long_rem(cpu.sched,
NSEC_PER_SEC, &tp->tv_nsec);
} else {
cputime_to_timespec(cpu.cpu, tp);
}
}
Commit 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 <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static void sample_to_timespec(const clockid_t which_clock,
union cpu_time_count cpu,
struct timespec *tp)
{
if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED)
*tp = ns_to_timespec(cpu.sched);
else
cputime_to_timespec(cpu.cpu, tp);
}
| 165,753 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UnloadController::TabDetachedImpl(TabContents* contents) {
if (is_attempting_to_close_browser_)
ClearUnloadState(contents->web_contents(), false);
registrar_.Remove(
this,
content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::Source<content::WebContents>(contents->web_contents()));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void UnloadController::TabDetachedImpl(TabContents* contents) {
void UnloadController::TabDetachedImpl(content::WebContents* contents) {
if (is_attempting_to_close_browser_)
ClearUnloadState(contents, false);
registrar_.Remove(this,
content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::Source<content::WebContents>(contents));
}
| 171,520 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool BluetoothDeviceChromeOS::RunPairingCallbacks(Status status) {
if (!agent_.get())
return false;
bool callback_run = false;
if (!pincode_callback_.is_null()) {
pincode_callback_.Run(status, "");
pincode_callback_.Reset();
callback_run = true;
}
if (!passkey_callback_.is_null()) {
passkey_callback_.Run(status, 0);
passkey_callback_.Reset();
callback_run = true;
}
if (!confirmation_callback_.is_null()) {
confirmation_callback_.Run(status);
confirmation_callback_.Reset();
callback_run = true;
}
return callback_run;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool BluetoothDeviceChromeOS::RunPairingCallbacks(Status status) {
| 171,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TaskService::RunTask(InstanceId instance_id,
RunnerId runner_id,
base::OnceClosure task) {
base::subtle::AutoReadLock task_lock(task_lock_);
{
base::AutoLock lock(lock_);
if (instance_id != bound_instance_id_)
return;
}
std::move(task).Run();
}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <[email protected]>
Reviewed-by: Takashi Toyoshima <[email protected]>
Reviewed-by: Francois Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#497632}
CWE ID: CWE-20 | void TaskService::RunTask(InstanceId instance_id,
RunnerId runner_id,
base::OnceClosure task) {
{
base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_);
++tasks_in_flight_;
}
if (IsInstanceIdStillBound(instance_id))
std::move(task).Run();
{
base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_);
--tasks_in_flight_;
DCHECK_GE(tasks_in_flight_, 0);
if (tasks_in_flight_ == 0)
no_tasks_in_flight_cv_.Signal();
}
}
bool TaskService::IsInstanceIdStillBound(InstanceId instance_id) {
base::AutoLock lock(lock_);
return instance_id == bound_instance_id_;
}
| 172,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
version_ = GET_PARAM(2); // 0: high precision forward transform
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
version_ = GET_PARAM(2); // 0: high precision forward transform
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,531 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsUIBindings::CallClientFunction(const std::string& function_name,
const base::Value* arg1,
const base::Value* arg2,
const base::Value* arg3) {
if (!web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme))
return;
std::string javascript = function_name + "(";
if (arg1) {
std::string json;
base::JSONWriter::Write(*arg1, &json);
javascript.append(json);
if (arg2) {
base::JSONWriter::Write(*arg2, &json);
javascript.append(", ").append(json);
if (arg3) {
base::JSONWriter::Write(*arg3, &json);
javascript.append(", ").append(json);
}
}
}
javascript.append(");");
web_contents_->GetMainFrame()->ExecuteJavaScript(
base::UTF8ToUTF16(javascript));
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | void DevToolsUIBindings::CallClientFunction(const std::string& function_name,
const base::Value* arg1,
const base::Value* arg2,
const base::Value* arg3) {
if (!web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme))
return;
// If we're not exposing bindings, we shouldn't call functions either.
if (!frontend_host_)
return;
std::string javascript = function_name + "(";
if (arg1) {
std::string json;
base::JSONWriter::Write(*arg1, &json);
javascript.append(json);
if (arg2) {
base::JSONWriter::Write(*arg2, &json);
javascript.append(", ").append(json);
if (arg3) {
base::JSONWriter::Write(*arg3, &json);
javascript.append(", ").append(json);
}
}
}
javascript.append(");");
web_contents_->GetMainFrame()->ExecuteJavaScript(
base::UTF8ToUTF16(javascript));
}
| 172,451 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static UINT drdynvc_process_create_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
size_t pos;
UINT status;
UINT32 ChannelId;
wStream* data_out;
UINT channel_status;
if (!drdynvc)
return CHANNEL_RC_BAD_CHANNEL_HANDLE;
if (drdynvc->state == DRDYNVC_STATE_CAPABILITIES)
{
/**
* For some reason the server does not always send the
* capabilities pdu as it should. When this happens,
* send a capabilities response.
*/
drdynvc->version = 3;
if ((status = drdynvc_send_capability_response(drdynvc)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_send_capability_response failed!");
return status;
}
drdynvc->state = DRDYNVC_STATE_READY;
}
ChannelId = drdynvc_read_variable_uint(s, cbChId);
pos = Stream_GetPosition(s);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_create_request: ChannelId=%"PRIu32" ChannelName=%s",
ChannelId,
Stream_Pointer(s));
channel_status = dvcman_create_channel(drdynvc, drdynvc->channel_mgr, ChannelId,
(char*) Stream_Pointer(s));
data_out = Stream_New(NULL, pos + 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT8(data_out, 0x10 | cbChId);
Stream_SetPosition(s, 1);
Stream_Copy(s, data_out, pos - 1);
if (channel_status == CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "channel created");
Stream_Write_UINT32(data_out, 0);
}
else
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "no listener");
Stream_Write_UINT32(data_out, (UINT32)0xC0000001); /* same code used by mstsc */
}
status = drdynvc_send(drdynvc, data_out);
if (status != CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(status), status);
return status;
}
if (channel_status == CHANNEL_RC_OK)
{
if ((status = dvcman_open_channel(drdynvc, drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_open_channel failed with error %"PRIu32"!", status);
return status;
}
}
else
{
if ((status = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", status);
}
return status;
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_process_create_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
size_t pos;
UINT status;
UINT32 ChannelId;
wStream* data_out;
UINT channel_status;
char* name;
size_t length;
if (!drdynvc)
return CHANNEL_RC_BAD_CHANNEL_HANDLE;
if (drdynvc->state == DRDYNVC_STATE_CAPABILITIES)
{
/**
* For some reason the server does not always send the
* capabilities pdu as it should. When this happens,
* send a capabilities response.
*/
drdynvc->version = 3;
if ((status = drdynvc_send_capability_response(drdynvc)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_send_capability_response failed!");
return status;
}
drdynvc->state = DRDYNVC_STATE_READY;
}
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
pos = Stream_GetPosition(s);
name = Stream_Pointer(s);
length = Stream_GetRemainingLength(s);
if (strnlen(name, length) >= length)
return ERROR_INVALID_DATA;
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_create_request: ChannelId=%"PRIu32" ChannelName=%s",
ChannelId, name);
channel_status = dvcman_create_channel(drdynvc, drdynvc->channel_mgr, ChannelId, name);
data_out = Stream_New(NULL, pos + 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT8(data_out, 0x10 | cbChId);
Stream_SetPosition(s, 1);
Stream_Copy(s, data_out, pos - 1);
if (channel_status == CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "channel created");
Stream_Write_UINT32(data_out, 0);
}
else
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "no listener");
Stream_Write_UINT32(data_out, (UINT32)0xC0000001); /* same code used by mstsc */
}
status = drdynvc_send(drdynvc, data_out);
if (status != CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(status), status);
return status;
}
if (channel_status == CHANNEL_RC_OK)
{
if ((status = dvcman_open_channel(drdynvc, drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_open_channel failed with error %"PRIu32"!", status);
return status;
}
}
else
{
if ((status = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", status);
}
return status;
}
| 168,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
const EVP_MD *digest;
VALUE vpass, vsalt, viter, vdigest;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
ossl_raise(eCipherError, "salt must be an 8-octet string");
salt = (unsigned char *)RSTRING_PTR(vsalt);
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
(unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
ossl_raise(eCipherError, NULL);
OPENSSL_cleanse(key, sizeof key);
OPENSSL_cleanse(iv, sizeof iv);
return Qnil;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310 | ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
const EVP_MD *digest;
VALUE vpass, vsalt, viter, vdigest;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
ossl_raise(eCipherError, "salt must be an 8-octet string");
salt = (unsigned char *)RSTRING_PTR(vsalt);
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
(unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
ossl_raise(eCipherError, NULL);
OPENSSL_cleanse(key, sizeof key);
OPENSSL_cleanse(iv, sizeof iv);
rb_ivar_set(self, id_key_set, Qtrue);
return Qnil;
}
| 168,781 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udp_v6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
struct udphdr *uh;
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi6 *fl6 = &inet->cork.fl.u.ip6;
int err = 0;
int is_udplite = IS_UDPLITE(sk);
__wsum csum = 0;
/* Grab the skbuff where UDP header space exists. */
if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
goto out;
/*
* Create a UDP header
*/
uh = udp_hdr(skb);
uh->source = fl6->fl6_sport;
uh->dest = fl6->fl6_dport;
uh->len = htons(up->len);
uh->check = 0;
if (is_udplite)
csum = udplite_csum_outgoing(sk, skb);
else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr,
up->len);
goto send;
} else
csum = udp_csum_outgoing(sk, skb);
/* add protocol-dependent pseudo-header */
uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
up->len, fl6->flowi6_proto, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
send:
err = ip6_push_pending_frames(sk);
if (err) {
if (err == -ENOBUFS && !inet6_sk(sk)->recverr) {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_SNDBUFERRORS, is_udplite);
err = 0;
}
} else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_OUTDATAGRAMS, is_udplite);
out:
up->len = 0;
up->pending = 0;
return err;
}
Commit Message: ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data
We accidentally call down to ip6_push_pending_frames when uncorking
pending AF_INET data on a ipv6 socket. This results in the following
splat (from Dave Jones):
skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL>
------------[ cut here ]------------
kernel BUG at net/core/skbuff.c:126!
invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC
Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth
+netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c
CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37
task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000
RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282
RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006
RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520
RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800
R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800
FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600
Stack:
ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4
ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6
ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0
Call Trace:
[<ffffffff8159a9aa>] skb_push+0x3a/0x40
[<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0
[<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140
[<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0
[<ffffffff81694660>] ? udplite_getfrag+0x20/0x20
[<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0
[<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0
[<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40
[<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20
[<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0
[<ffffffff816f5d54>] tracesys+0xdd/0xe2
Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55
RIP [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP <ffff8801e6431de8>
This patch adds a check if the pending data is of address family AF_INET
and directly calls udp_push_ending_frames from udp_v6_push_pending_frames
if that is the case.
This bug was found by Dave Jones with trinity.
(Also move the initialization of fl6 below the AF_INET check, even if
not strictly necessary.)
Cc: Dave Jones <[email protected]>
Cc: YOSHIFUJI Hideaki <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int udp_v6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
struct udphdr *uh;
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi6 *fl6;
int err = 0;
int is_udplite = IS_UDPLITE(sk);
__wsum csum = 0;
if (up->pending == AF_INET)
return udp_push_pending_frames(sk);
fl6 = &inet->cork.fl.u.ip6;
/* Grab the skbuff where UDP header space exists. */
if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
goto out;
/*
* Create a UDP header
*/
uh = udp_hdr(skb);
uh->source = fl6->fl6_sport;
uh->dest = fl6->fl6_dport;
uh->len = htons(up->len);
uh->check = 0;
if (is_udplite)
csum = udplite_csum_outgoing(sk, skb);
else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr,
up->len);
goto send;
} else
csum = udp_csum_outgoing(sk, skb);
/* add protocol-dependent pseudo-header */
uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
up->len, fl6->flowi6_proto, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
send:
err = ip6_push_pending_frames(sk);
if (err) {
if (err == -ENOBUFS && !inet6_sk(sk)->recverr) {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_SNDBUFERRORS, is_udplite);
err = 0;
}
} else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_OUTDATAGRAMS, is_udplite);
out:
up->len = 0;
up->pending = 0;
return err;
}
| 166,017 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int perf_event_task_enable(void)
{
struct perf_event *event;
mutex_lock(¤t->perf_event_mutex);
list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
perf_event_for_each_child(event, perf_event_enable);
mutex_unlock(¤t->perf_event_mutex);
return 0;
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | int perf_event_task_enable(void)
{
struct perf_event_context *ctx;
struct perf_event *event;
mutex_lock(¤t->perf_event_mutex);
list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
ctx = perf_event_ctx_lock(event);
perf_event_for_each_child(event, _perf_event_enable);
perf_event_ctx_unlock(event, ctx);
}
mutex_unlock(¤t->perf_event_mutex);
return 0;
}
| 166,990 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void prefetch_table(const void *tab, size_t len)
{
const volatile byte *vtab = tab;
size_t i;
for (i = 0; i < len; i += 8 * 32)
{
(void)vtab[i + 0 * 32];
(void)vtab[i + 1 * 32];
(void)vtab[i + 2 * 32];
(void)vtab[i + 3 * 32];
(void)vtab[i + 4 * 32];
(void)vtab[i + 5 * 32];
(void)vtab[i + 6 * 32];
(void)vtab[i + 7 * 32];
}
(void)vtab[len - 1];
}
Commit Message: GCM: move look-up table to .data section and unshare between processes
* cipher/cipher-gcm.c (ATTR_ALIGNED_64): New.
(gcmR): Move to 'gcm_table' structure.
(gcm_table): New structure for look-up table with counters before and
after.
(gcmR): New macro.
(prefetch_table): Handle input with length not multiple of 256.
(do_prefetch_tables): Modify pre- and post-table counters to unshare
look-up table pages between processes.
--
GnuPG-bug-id: 4541
Signed-off-by: Jussi Kivilinna <[email protected]>
CWE ID: CWE-310 | void prefetch_table(const void *tab, size_t len)
{
const volatile byte *vtab = tab;
size_t i;
for (i = 0; len - i >= 8 * 32; i += 8 * 32)
{
(void)vtab[i + 0 * 32];
(void)vtab[i + 1 * 32];
(void)vtab[i + 2 * 32];
(void)vtab[i + 3 * 32];
(void)vtab[i + 4 * 32];
(void)vtab[i + 5 * 32];
(void)vtab[i + 6 * 32];
(void)vtab[i + 7 * 32];
}
for (; i < len; i += 32)
{
(void)vtab[i];
}
(void)vtab[len - 1];
}
| 169,651 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MockRenderThread::MockRenderThread()
: routing_id_(0), surface_id_(0), opener_id_(0) {
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | MockRenderThread::MockRenderThread()
: routing_id_(0), surface_id_(0), opener_id_(0), new_window_routing_id_(0) {
}
| 171,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_get_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_qop_t qop_req,
const gss_buffer_t message_buffer,
gss_buffer_t message_token)
{
OM_uint32 ret;
ret = gss_get_mic(minor_status,
context_handle,
qop_req,
message_buffer,
message_token);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_get_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_qop_t qop_req,
const gss_buffer_t message_buffer,
gss_buffer_t message_token)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_get_mic(minor_status,
sc->ctx_handle,
qop_req,
message_buffer,
message_token);
return (ret);
}
| 166,656 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tight_detect_smooth_image24(VncState *vs, int w, int h)
{
int off;
int x, y, d, dx;
unsigned int c;
unsigned int stats[256];
int pixels = 0;
int pix, left[3];
unsigned int errors;
unsigned char *buf = vs->tight.tight.buffer;
/*
* If client is big-endian, color samples begin from the second
* byte (offset 1) of a 32-bit pixel value.
*/
off = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
memset(stats, 0, sizeof (stats));
for (y = 0, x = 0; y < h && x < w;) {
for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;
d++) {
for (c = 0; c < 3; c++) {
left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;
}
for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {
for (c = 0; c < 3; c++) {
pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;
stats[abs(pix - left[c])]++;
left[c] = pix;
}
pixels++;
}
}
if (w > h) {
x += h;
y = 0;
} else {
x = 0;
y += w;
}
}
/* 95% smooth or more ... */
if (stats[0] * 33 / pixels >= 95) {
return 0;
}
errors = 0;
for (c = 1; c < 8; c++) {
errors += stats[c] * (c * c);
if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {
return 0;
}
}
for (; c < 256; c++) {
errors += stats[c] * (c * c);
}
errors /= (pixels * 3 - stats[0]);
return errors;
}
Commit Message:
CWE ID: CWE-125 | tight_detect_smooth_image24(VncState *vs, int w, int h)
{
int off;
int x, y, d, dx;
unsigned int c;
unsigned int stats[256];
int pixels = 0;
int pix, left[3];
unsigned int errors;
unsigned char *buf = vs->tight.tight.buffer;
/*
* If client is big-endian, color samples begin from the second
* byte (offset 1) of a 32-bit pixel value.
*/
off = vs->client_be;
memset(stats, 0, sizeof (stats));
for (y = 0, x = 0; y < h && x < w;) {
for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;
d++) {
for (c = 0; c < 3; c++) {
left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;
}
for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {
for (c = 0; c < 3; c++) {
pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;
stats[abs(pix - left[c])]++;
left[c] = pix;
}
pixels++;
}
}
if (w > h) {
x += h;
y = 0;
} else {
x = 0;
y += w;
}
}
/* 95% smooth or more ... */
if (stats[0] * 33 / pixels >= 95) {
return 0;
}
errors = 0;
for (c = 1; c < 8; c++) {
errors += stats[c] * (c * c);
if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {
return 0;
}
}
for (; c < 256; c++) {
errors += stats[c] * (c * c);
}
errors /= (pixels * 3 - stats[0]);
return errors;
}
| 165,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static uint64_t ReadBits(BitReader* reader, int num_bits) {
DCHECK_GE(reader->bits_available(), num_bits);
DCHECK((num_bits > 0) && (num_bits <= 64));
uint64_t value;
reader->ReadBits(num_bits, &value);
return value;
}
Commit Message: Cleanup media BitReader ReadBits() calls
Initialize temporary values, check return values.
Small tweaks to solution proposed by [email protected].
Bug: 929962
Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735
Reviewed-on: https://chromium-review.googlesource.com/c/1481085
Commit-Queue: Chrome Cunningham <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#634889}
CWE ID: CWE-200 | static uint64_t ReadBits(BitReader* reader, int num_bits) {
DCHECK_GE(reader->bits_available(), num_bits);
DCHECK((num_bits > 0) && (num_bits <= 64));
uint64_t value = 0;
if (!reader->ReadBits(num_bits, &value))
return 0;
return value;
}
| 173,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Cluster* Cluster::Create(
Segment* pSegment,
long idx,
long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment,
idx,
element_start);
assert(pCluster);
return pCluster;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Cluster* Cluster::Create(
| 174,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION( locale_get_script )
PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,182 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate(
const CompactHTMLToken& token,
HTMLTokenizer* tokenizer) {
SimulatedToken simulated_token = kOtherToken;
if (token.GetType() == HTMLToken::kStartTag) {
const String& tag_name = token.Data();
if (ThreadSafeMatch(tag_name, SVGNames::svgTag))
namespace_stack_.push_back(SVG);
if (ThreadSafeMatch(tag_name, MathMLNames::mathTag))
namespace_stack_.push_back(kMathML);
if (InForeignContent() && TokenExitsForeignContent(token))
namespace_stack_.pop_back();
if ((namespace_stack_.back() == SVG && TokenExitsSVG(token)) ||
(namespace_stack_.back() == kMathML && TokenExitsMath(token)))
namespace_stack_.push_back(HTML);
if (!InForeignContent()) {
if (ThreadSafeMatch(tag_name, textareaTag) ||
ThreadSafeMatch(tag_name, titleTag)) {
tokenizer->SetState(HTMLTokenizer::kRCDATAState);
} else if (ThreadSafeMatch(tag_name, scriptTag)) {
tokenizer->SetState(HTMLTokenizer::kScriptDataState);
simulated_token = kScriptStart;
} else if (ThreadSafeMatch(tag_name, linkTag)) {
simulated_token = kLink;
} else if (!in_select_insertion_mode_) {
if (ThreadSafeMatch(tag_name, plaintextTag) &&
!in_select_insertion_mode_) {
tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState);
} else if (ThreadSafeMatch(tag_name, styleTag) ||
ThreadSafeMatch(tag_name, iframeTag) ||
ThreadSafeMatch(tag_name, xmpTag) ||
(ThreadSafeMatch(tag_name, noembedTag) &&
options_.plugins_enabled) ||
ThreadSafeMatch(tag_name, noframesTag) ||
(ThreadSafeMatch(tag_name, noscriptTag) &&
options_.script_enabled)) {
tokenizer->SetState(HTMLTokenizer::kRAWTEXTState);
}
}
if (ThreadSafeMatch(tag_name, selectTag)) {
in_select_insertion_mode_ = true;
} else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) {
in_select_insertion_mode_ = false;
}
}
}
if (token.GetType() == HTMLToken::kEndTag ||
(token.GetType() == HTMLToken::kStartTag && token.SelfClosing() &&
InForeignContent())) {
const String& tag_name = token.Data();
if ((namespace_stack_.back() == SVG &&
ThreadSafeMatch(tag_name, SVGNames::svgTag)) ||
(namespace_stack_.back() == kMathML &&
ThreadSafeMatch(tag_name, MathMLNames::mathTag)) ||
(namespace_stack_.Contains(SVG) && namespace_stack_.back() == HTML &&
TokenExitsSVG(token)) ||
(namespace_stack_.Contains(kMathML) &&
namespace_stack_.back() == HTML && TokenExitsMath(token))) {
namespace_stack_.pop_back();
}
if (ThreadSafeMatch(tag_name, scriptTag)) {
if (!InForeignContent())
tokenizer->SetState(HTMLTokenizer::kDataState);
return kScriptEnd;
} else if (ThreadSafeMatch(tag_name, selectTag)) {
in_select_insertion_mode_ = false;
}
if (ThreadSafeMatch(tag_name, styleTag))
simulated_token = kStyleEnd;
}
tokenizer->SetForceNullCharacterReplacement(InForeignContent());
tokenizer->SetShouldAllowCDATA(InForeignContent());
return simulated_token;
}
Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator.
HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML
integration point. This CL adds <annotation-xml>, <desc>, and SVG
<title>.
Bug: 805924
Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2
Reviewed-on: https://chromium-review.googlesource.com/964038
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#543634}
CWE ID: CWE-79 | HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate(
const CompactHTMLToken& token,
HTMLTokenizer* tokenizer) {
SimulatedToken simulated_token = kOtherToken;
if (token.GetType() == HTMLToken::kStartTag) {
const String& tag_name = token.Data();
if (ThreadSafeMatch(tag_name, SVGNames::svgTag))
namespace_stack_.push_back(SVG);
if (ThreadSafeMatch(tag_name, MathMLNames::mathTag))
namespace_stack_.push_back(kMathML);
if (InForeignContent() && TokenExitsForeignContent(token))
namespace_stack_.pop_back();
if (IsHTMLIntegrationPointForStartTag(token) ||
(namespace_stack_.back() == kMathML && TokenExitsMath(token))) {
namespace_stack_.push_back(HTML);
} else if (!InForeignContent()) {
if (ThreadSafeMatch(tag_name, textareaTag) ||
ThreadSafeMatch(tag_name, titleTag)) {
tokenizer->SetState(HTMLTokenizer::kRCDATAState);
} else if (ThreadSafeMatch(tag_name, scriptTag)) {
tokenizer->SetState(HTMLTokenizer::kScriptDataState);
simulated_token = kScriptStart;
} else if (ThreadSafeMatch(tag_name, linkTag)) {
simulated_token = kLink;
} else if (!in_select_insertion_mode_) {
if (ThreadSafeMatch(tag_name, plaintextTag) &&
!in_select_insertion_mode_) {
tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState);
} else if (ThreadSafeMatch(tag_name, styleTag) ||
ThreadSafeMatch(tag_name, iframeTag) ||
ThreadSafeMatch(tag_name, xmpTag) ||
(ThreadSafeMatch(tag_name, noembedTag) &&
options_.plugins_enabled) ||
ThreadSafeMatch(tag_name, noframesTag) ||
(ThreadSafeMatch(tag_name, noscriptTag) &&
options_.script_enabled)) {
tokenizer->SetState(HTMLTokenizer::kRAWTEXTState);
}
}
if (ThreadSafeMatch(tag_name, selectTag)) {
in_select_insertion_mode_ = true;
} else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) {
in_select_insertion_mode_ = false;
}
}
}
if (token.GetType() == HTMLToken::kEndTag ||
(token.GetType() == HTMLToken::kStartTag && token.SelfClosing() &&
InForeignContent())) {
const String& tag_name = token.Data();
if ((namespace_stack_.back() == SVG &&
ThreadSafeMatch(tag_name, SVGNames::svgTag)) ||
(namespace_stack_.back() == kMathML &&
ThreadSafeMatch(tag_name, MathMLNames::mathTag)) ||
IsHTMLIntegrationPointForEndTag(token) ||
(namespace_stack_.Contains(kMathML) &&
namespace_stack_.back() == HTML && TokenExitsMath(token))) {
namespace_stack_.pop_back();
}
if (ThreadSafeMatch(tag_name, scriptTag)) {
if (!InForeignContent())
tokenizer->SetState(HTMLTokenizer::kDataState);
return kScriptEnd;
} else if (ThreadSafeMatch(tag_name, selectTag)) {
in_select_insertion_mode_ = false;
}
if (ThreadSafeMatch(tag_name, styleTag))
simulated_token = kStyleEnd;
}
tokenizer->SetForceNullCharacterReplacement(InForeignContent());
tokenizer->SetShouldAllowCDATA(InForeignContent());
return simulated_token;
}
| 173,254 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
if((cc0%rowsize)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
"%s", "(cc0%rowsize)!=0");
return 0;
}
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in
previous commit (fix for MSVR 35105)
CWE ID: CWE-119 | PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
if((cc0%rowsize)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
"%s", "(cc0%rowsize)!=0");
_TIFFfree( working_copy );
return 0;
}
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
| 169,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetPowerLibrary(
PowerLibrary* library, bool own) {
library_->power_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void CrosLibrary::TestApi::SetPowerLibrary(
| 170,643 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ForeignSessionHelper::TriggerSessionSync(
JNIEnv* env,
const JavaParamRef<jobject>& obj) {
browser_sync::ProfileSyncService* service =
ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_);
if (!service)
return;
const syncer::ModelTypeSet types(syncer::SESSIONS);
service->TriggerRefresh(types);
}
Commit Message: Prefer SyncService over ProfileSyncService in foreign_session_helper
SyncService is the interface, ProfileSyncService is the concrete
implementation. Generally no clients should need to use the conrete
implementation - for one, testing will be much easier once everyone
uses the interface only.
Bug: 924508
Change-Id: Ia210665f8f02512053d1a60d627dea0f22758387
Reviewed-on: https://chromium-review.googlesource.com/c/1461119
Auto-Submit: Marc Treib <[email protected]>
Commit-Queue: Yaron Friedman <[email protected]>
Reviewed-by: Yaron Friedman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#630662}
CWE ID: CWE-254 | void ForeignSessionHelper::TriggerSessionSync(
JNIEnv* env,
const JavaParamRef<jobject>& obj) {
syncer::SyncService* service =
ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_);
if (!service)
return;
service->TriggerRefresh({syncer::SESSIONS});
}
| 172,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromeContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
std::wstring plugin_dll = command_line->
GetSwitchValueNative(switches::kPluginPath);
FilePath builtin_flash;
if (!PathService::Get(chrome::FILE_FLASH_PLUGIN, &builtin_flash))
return false;
FilePath plugin_path(plugin_dll);
if (plugin_path.BaseName() != builtin_flash.BaseName())
return false;
if (base::win::GetVersion() <= base::win::VERSION_XP ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableFlashSandbox)) {
return false;
}
if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.*") != sandbox::SBOX_ALL_OK) {
NOTREACHED();
return false;
}
if (LoadFlashBroker(plugin_path, command_line)) {
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_INTERACTIVE);
if (base::win::GetVersion() == base::win::VERSION_VISTA) {
::ChangeWindowMessageFilter(WM_MOUSEWHEEL, MSGFLT_ADD);
::ChangeWindowMessageFilter(WM_APPCOMMAND, MSGFLT_ADD);
}
policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
} else {
DLOG(WARNING) << "Failed to start flash broker";
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(
sandbox::USER_UNPROTECTED, sandbox::USER_UNPROTECTED);
}
return true;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool ChromeContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
std::wstring plugin_dll = command_line->
GetSwitchValueNative(switches::kPluginPath);
FilePath builtin_flash;
if (!PathService::Get(chrome::FILE_FLASH_PLUGIN, &builtin_flash))
return false;
FilePath plugin_path(plugin_dll);
if (plugin_path.BaseName() != builtin_flash.BaseName())
return false;
if (base::win::GetVersion() <= base::win::VERSION_XP ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableFlashSandbox)) {
return false;
}
// Add policy for the plugin proxy window pump event
// used by WebPluginDelegateProxy::HandleInputEvent().
if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
sandbox::TargetPolicy::HANDLES_DUP_ANY,
L"Event") != sandbox::SBOX_ALL_OK) {
NOTREACHED();
return false;
}
if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.*") != sandbox::SBOX_ALL_OK) {
NOTREACHED();
return false;
}
if (LoadFlashBroker(plugin_path, command_line)) {
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_INTERACTIVE);
if (base::win::GetVersion() == base::win::VERSION_VISTA) {
::ChangeWindowMessageFilter(WM_MOUSEWHEEL, MSGFLT_ADD);
::ChangeWindowMessageFilter(WM_APPCOMMAND, MSGFLT_ADD);
}
policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
} else {
DLOG(WARNING) << "Failed to start flash broker";
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(
sandbox::USER_UNPROTECTED, sandbox::USER_UNPROTECTED);
}
return true;
}
| 170,916 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: rs_filter_graph(RSFilter *filter)
{
g_return_if_fail(RS_IS_FILTER(filter));
GString *str = g_string_new("digraph G {\n");
rs_filter_graph_helper(str, filter);
g_string_append_printf(str, "}\n");
g_file_set_contents("/tmp/rs-filter-graph", str->str, str->len, NULL);
if (0 != system("dot -Tpng >/tmp/rs-filter-graph.png </tmp/rs-filter-graph"))
g_warning("Calling dot failed");
if (0 != system("gnome-open /tmp/rs-filter-graph.png"))
g_warning("Calling gnome-open failed.");
g_string_free(str, TRUE);
}
Commit Message: Fixes insecure use of temporary file (CVE-2014-4978).
CWE ID: CWE-59 | rs_filter_graph(RSFilter *filter)
{
g_return_if_fail(RS_IS_FILTER(filter));
gchar *dot_filename;
gchar *png_filename;
gchar *command_line;
GString *str = g_string_new("digraph G {\n");
rs_filter_graph_helper(str, filter);
g_string_append_printf(str, "}\n");
/* Here we would like to use g_mkdtemp(), but due to a bug in upstream, that's impossible */
dot_filename = g_strdup_printf("/tmp/rs-filter-graph.%u", g_random_int());
png_filename = g_strdup_printf("%s.%u.png", dot_filename, g_random_int());
g_file_set_contents(dot_filename, str->str, str->len, NULL);
command_line = g_strdup_printf("dot -Tpng >%s <%s", png_filename, dot_filename);
if (0 != system(command_line))
g_warning("Calling dot failed");
g_free(command_line);
command_line = g_strdup_printf("gnome-open %s", png_filename);
if (0 != system(command_line))
g_warning("Calling gnome-open failed.");
g_free(command_line);
g_free(dot_filename);
g_free(png_filename);
g_string_free(str, TRUE);
}
| 168,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Cues::Init() const {
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) // CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; // consume payload
assert(pos <= stop);
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | void Cues::Init() const {
bool Cues::Init() const {
if (m_cue_points)
return true;
if (m_count != 0 || m_preload_count != 0)
return false;
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadID(pReader, pos, len);
if (id < 0 || (pos + len) > stop) {
return false;
}
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
if (size < 0 || (pos + len > stop)) {
return false;
}
pos += len; // consume Size field
if (pos + size > stop) {
return false;
}
if (id == 0x3B) { // CuePoint ID
if (!PreloadCuePoint(cue_points_size, idpos))
return false;
}
pos += size; // skip payload
}
return true;
}
| 173,827 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Cues* Segment::GetCues() const
{
return m_pCues;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Cues* Segment::GetCues() const
| 174,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int fwnet_incoming_packet(struct fwnet_device *dev, __be32 *buf, int len,
int source_node_id, int generation,
bool is_broadcast)
{
struct sk_buff *skb;
struct net_device *net = dev->netdev;
struct rfc2734_header hdr;
unsigned lf;
unsigned long flags;
struct fwnet_peer *peer;
struct fwnet_partial_datagram *pd;
int fg_off;
int dg_size;
u16 datagram_label;
int retval;
u16 ether_type;
hdr.w0 = be32_to_cpu(buf[0]);
lf = fwnet_get_hdr_lf(&hdr);
if (lf == RFC2374_HDR_UNFRAG) {
/*
* An unfragmented datagram has been received by the ieee1394
* bus. Build an skbuff around it so we can pass it to the
* high level network layer.
*/
ether_type = fwnet_get_hdr_ether_type(&hdr);
buf++;
len -= RFC2374_UNFRAG_HDR_SIZE;
skb = dev_alloc_skb(len + LL_RESERVED_SPACE(net));
if (unlikely(!skb)) {
net->stats.rx_dropped++;
return -ENOMEM;
}
skb_reserve(skb, LL_RESERVED_SPACE(net));
memcpy(skb_put(skb, len), buf, len);
return fwnet_finish_incoming_packet(net, skb, source_node_id,
is_broadcast, ether_type);
}
/* A datagram fragment has been received, now the fun begins. */
hdr.w1 = ntohl(buf[1]);
buf += 2;
len -= RFC2374_FRAG_HDR_SIZE;
if (lf == RFC2374_HDR_FIRSTFRAG) {
ether_type = fwnet_get_hdr_ether_type(&hdr);
fg_off = 0;
} else {
ether_type = 0;
fg_off = fwnet_get_hdr_fg_off(&hdr);
}
datagram_label = fwnet_get_hdr_dgl(&hdr);
dg_size = fwnet_get_hdr_dg_size(&hdr); /* ??? + 1 */
spin_lock_irqsave(&dev->lock, flags);
peer = fwnet_peer_find_by_node_id(dev, source_node_id, generation);
if (!peer) {
retval = -ENOENT;
goto fail;
}
pd = fwnet_pd_find(peer, datagram_label);
if (pd == NULL) {
while (peer->pdg_size >= FWNET_MAX_FRAGMENTS) {
/* remove the oldest */
fwnet_pd_delete(list_first_entry(&peer->pd_list,
struct fwnet_partial_datagram, pd_link));
peer->pdg_size--;
}
pd = fwnet_pd_new(net, peer, datagram_label,
dg_size, buf, fg_off, len);
if (pd == NULL) {
retval = -ENOMEM;
goto fail;
}
peer->pdg_size++;
} else {
if (fwnet_frag_overlap(pd, fg_off, len) ||
pd->datagram_size != dg_size) {
/*
* Differing datagram sizes or overlapping fragments,
* discard old datagram and start a new one.
*/
fwnet_pd_delete(pd);
pd = fwnet_pd_new(net, peer, datagram_label,
dg_size, buf, fg_off, len);
if (pd == NULL) {
peer->pdg_size--;
retval = -ENOMEM;
goto fail;
}
} else {
if (!fwnet_pd_update(peer, pd, buf, fg_off, len)) {
/*
* Couldn't save off fragment anyway
* so might as well obliterate the
* datagram now.
*/
fwnet_pd_delete(pd);
peer->pdg_size--;
retval = -ENOMEM;
goto fail;
}
}
} /* new datagram or add to existing one */
if (lf == RFC2374_HDR_FIRSTFRAG)
pd->ether_type = ether_type;
if (fwnet_pd_is_complete(pd)) {
ether_type = pd->ether_type;
peer->pdg_size--;
skb = skb_get(pd->skb);
fwnet_pd_delete(pd);
spin_unlock_irqrestore(&dev->lock, flags);
return fwnet_finish_incoming_packet(net, skb, source_node_id,
false, ether_type);
}
/*
* Datagram is not complete, we're done for the
* moment.
*/
retval = 0;
fail:
spin_unlock_irqrestore(&dev->lock, flags);
return retval;
}
Commit Message: firewire: net: guard against rx buffer overflows
The IP-over-1394 driver firewire-net lacked input validation when
handling incoming fragmented datagrams. A maliciously formed fragment
with a respectively large datagram_offset would cause a memcpy past the
datagram buffer.
So, drop any packets carrying a fragment with offset + length larger
than datagram_size.
In addition, ensure that
- GASP header, unfragmented encapsulation header, or fragment
encapsulation header actually exists before we access it,
- the encapsulated datagram or fragment is of nonzero size.
Reported-by: Eyal Itkin <[email protected]>
Reviewed-by: Eyal Itkin <[email protected]>
Fixes: CVE 2016-8633
Cc: [email protected]
Signed-off-by: Stefan Richter <[email protected]>
CWE ID: CWE-119 | static int fwnet_incoming_packet(struct fwnet_device *dev, __be32 *buf, int len,
int source_node_id, int generation,
bool is_broadcast)
{
struct sk_buff *skb;
struct net_device *net = dev->netdev;
struct rfc2734_header hdr;
unsigned lf;
unsigned long flags;
struct fwnet_peer *peer;
struct fwnet_partial_datagram *pd;
int fg_off;
int dg_size;
u16 datagram_label;
int retval;
u16 ether_type;
if (len <= RFC2374_UNFRAG_HDR_SIZE)
return 0;
hdr.w0 = be32_to_cpu(buf[0]);
lf = fwnet_get_hdr_lf(&hdr);
if (lf == RFC2374_HDR_UNFRAG) {
/*
* An unfragmented datagram has been received by the ieee1394
* bus. Build an skbuff around it so we can pass it to the
* high level network layer.
*/
ether_type = fwnet_get_hdr_ether_type(&hdr);
buf++;
len -= RFC2374_UNFRAG_HDR_SIZE;
skb = dev_alloc_skb(len + LL_RESERVED_SPACE(net));
if (unlikely(!skb)) {
net->stats.rx_dropped++;
return -ENOMEM;
}
skb_reserve(skb, LL_RESERVED_SPACE(net));
memcpy(skb_put(skb, len), buf, len);
return fwnet_finish_incoming_packet(net, skb, source_node_id,
is_broadcast, ether_type);
}
/* A datagram fragment has been received, now the fun begins. */
if (len <= RFC2374_FRAG_HDR_SIZE)
return 0;
hdr.w1 = ntohl(buf[1]);
buf += 2;
len -= RFC2374_FRAG_HDR_SIZE;
if (lf == RFC2374_HDR_FIRSTFRAG) {
ether_type = fwnet_get_hdr_ether_type(&hdr);
fg_off = 0;
} else {
ether_type = 0;
fg_off = fwnet_get_hdr_fg_off(&hdr);
}
datagram_label = fwnet_get_hdr_dgl(&hdr);
dg_size = fwnet_get_hdr_dg_size(&hdr); /* ??? + 1 */
if (fg_off + len > dg_size)
return 0;
spin_lock_irqsave(&dev->lock, flags);
peer = fwnet_peer_find_by_node_id(dev, source_node_id, generation);
if (!peer) {
retval = -ENOENT;
goto fail;
}
pd = fwnet_pd_find(peer, datagram_label);
if (pd == NULL) {
while (peer->pdg_size >= FWNET_MAX_FRAGMENTS) {
/* remove the oldest */
fwnet_pd_delete(list_first_entry(&peer->pd_list,
struct fwnet_partial_datagram, pd_link));
peer->pdg_size--;
}
pd = fwnet_pd_new(net, peer, datagram_label,
dg_size, buf, fg_off, len);
if (pd == NULL) {
retval = -ENOMEM;
goto fail;
}
peer->pdg_size++;
} else {
if (fwnet_frag_overlap(pd, fg_off, len) ||
pd->datagram_size != dg_size) {
/*
* Differing datagram sizes or overlapping fragments,
* discard old datagram and start a new one.
*/
fwnet_pd_delete(pd);
pd = fwnet_pd_new(net, peer, datagram_label,
dg_size, buf, fg_off, len);
if (pd == NULL) {
peer->pdg_size--;
retval = -ENOMEM;
goto fail;
}
} else {
if (!fwnet_pd_update(peer, pd, buf, fg_off, len)) {
/*
* Couldn't save off fragment anyway
* so might as well obliterate the
* datagram now.
*/
fwnet_pd_delete(pd);
peer->pdg_size--;
retval = -ENOMEM;
goto fail;
}
}
} /* new datagram or add to existing one */
if (lf == RFC2374_HDR_FIRSTFRAG)
pd->ether_type = ether_type;
if (fwnet_pd_is_complete(pd)) {
ether_type = pd->ether_type;
peer->pdg_size--;
skb = skb_get(pd->skb);
fwnet_pd_delete(pd);
spin_unlock_irqrestore(&dev->lock, flags);
return fwnet_finish_incoming_packet(net, skb, source_node_id,
false, ether_type);
}
/*
* Datagram is not complete, we're done for the
* moment.
*/
retval = 0;
fail:
spin_unlock_irqrestore(&dev->lock, flags);
return retval;
}
| 166,916 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: print_trans(netdissect_options *ndo,
const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)
{
u_int bcc;
const char *f1, *f2, *f3, *f4;
const u_char *data, *param;
const u_char *w = words + 1;
int datalen, paramlen;
if (request) {
ND_TCHECK2(w[12 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 9 * 2);
param = buf + EXTRACT_LE_16BITS(w + 10 * 2);
datalen = EXTRACT_LE_16BITS(w + 11 * 2);
data = buf + EXTRACT_LE_16BITS(w + 12 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n";
f2 = "|Name=[S]\n";
f3 = "|Param ";
f4 = "|Data ";
} else {
ND_TCHECK2(w[7 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 3 * 2);
param = buf + EXTRACT_LE_16BITS(w + 4 * 2);
datalen = EXTRACT_LE_16BITS(w + 6 * 2);
data = buf + EXTRACT_LE_16BITS(w + 7 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n";
f2 = "|Unknown ";
f3 = "|Param ";
f4 = "|Data ";
}
smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),
unicodestr);
ND_TCHECK2(*data1, 2);
bcc = EXTRACT_LE_16BITS(data1);
ND_PRINT((ndo, "smb_bcc=%u\n", bcc));
if (bcc > 0) {
smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);
if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) {
print_browse(ndo, param, paramlen, data, datalen);
return;
}
if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) {
print_ipc(ndo, param, paramlen, data, datalen);
return;
}
if (paramlen)
smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);
if (datalen)
smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: (for 4.9.3) SMB: Add two missing bounds checks
CWE ID: CWE-125 | print_trans(netdissect_options *ndo,
const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)
{
u_int bcc;
const char *f1, *f2, *f3, *f4;
const u_char *data, *param;
const u_char *w = words + 1;
int datalen, paramlen;
if (request) {
ND_TCHECK2(w[12 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 9 * 2);
param = buf + EXTRACT_LE_16BITS(w + 10 * 2);
datalen = EXTRACT_LE_16BITS(w + 11 * 2);
data = buf + EXTRACT_LE_16BITS(w + 12 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n";
f2 = "|Name=[S]\n";
f3 = "|Param ";
f4 = "|Data ";
} else {
ND_TCHECK2(w[7 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 3 * 2);
param = buf + EXTRACT_LE_16BITS(w + 4 * 2);
datalen = EXTRACT_LE_16BITS(w + 6 * 2);
data = buf + EXTRACT_LE_16BITS(w + 7 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n";
f2 = "|Unknown ";
f3 = "|Param ";
f4 = "|Data ";
}
smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),
unicodestr);
ND_TCHECK2(*data1, 2);
bcc = EXTRACT_LE_16BITS(data1);
ND_PRINT((ndo, "smb_bcc=%u\n", bcc));
if (bcc > 0) {
smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);
#define MAILSLOT_BROWSE_STR "\\MAILSLOT\\BROWSE"
ND_TCHECK2(*(data1 + 2), strlen(MAILSLOT_BROWSE_STR) + 1);
if (strcmp((const char *)(data1 + 2), MAILSLOT_BROWSE_STR) == 0) {
print_browse(ndo, param, paramlen, data, datalen);
return;
}
#undef MAILSLOT_BROWSE_STR
#define PIPE_LANMAN_STR "\\PIPE\\LANMAN"
ND_TCHECK2(*(data1 + 2), strlen(PIPE_LANMAN_STR) + 1);
if (strcmp((const char *)(data1 + 2), PIPE_LANMAN_STR) == 0) {
print_ipc(ndo, param, paramlen, data, datalen);
return;
}
#undef PIPE_LANMAN_STR
if (paramlen)
smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);
if (datalen)
smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 169,815 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error)
{
int len;
int i;
len = g_strv_length ((char**) in);
*out = g_new0 (char *, len + 1);
for (i = 0; i < len; i++)
{
(*out)[i] = g_ascii_strup (in[i], -1);
}
(*out)[i] = NULL;
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error)
| 165,113 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.