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: jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; size_t size; matrix = 0; if (numrows < 0 || numcols < 0) { goto error; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { goto error; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = 0; if (!jas_safe_size_mul(numrows, numcols, &size)) { goto error; } matrix->datasize_ = size; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { goto error; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { goto error; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; error: if (matrix) { jas_matrix_destroy(matrix); } return 0; } 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
jas_matrix_t *jas_matrix_create(int numrows, int numcols) jas_matrix_t *jas_matrix_create(jas_matind_t numrows, jas_matind_t numcols) { jas_matrix_t *matrix; jas_matind_t i; size_t size; matrix = 0; if (numrows < 0 || numcols < 0) { goto error; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { goto error; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = 0; if (!jas_safe_size_mul(numrows, numcols, &size)) { goto error; } matrix->datasize_ = size; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { goto error; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { goto error; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; error: if (matrix) { jas_matrix_destroy(matrix); } return 0; }
168,703
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 readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint32 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ Commit Message: * tools/tiffcrop.c: fix readContigStripsIntoBuffer() in -i (ignore) mode so that the output buffer is correctly incremented to avoid write outside bounds. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2620 CWE ID: CWE-119
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint32 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += stripsize; } return 1; } /* end readContigStripsIntoBuffer */
168,461
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 extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; sprintf(url_address, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; } Commit Message: Stratum: extract_sockaddr: Truncate overlong addresses rather than stack overflow Thanks to Mick Ayzenberg <[email protected]> for finding this! CWE ID: CWE-119
bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; if (url_len >= sizeof(url_address)) { applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'", __func__, url_len, url_begin); url_len = sizeof(url_address) - 1; } sprintf(url_address, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; }
166,308
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 Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { ipfix_template_record_t *ipfix_template_record; while ( size_left ) { uint32_t id; ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; id = ntohs(ipfix_template_record->TemplateID); if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) { remove_all_translation_tables(exporter); ReInitExtensionMapList(fs); } else { remove_translation_table(fs, exporter, id); } DataPtr = DataPtr + 4; if ( size_left < 4 ) { dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } } } // End of Process_ipfix_template_withdraw Commit Message: Fix potential unsigned integer underflow CWE ID: CWE-190
static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { ipfix_template_record_t *ipfix_template_record; while ( size_left ) { uint32_t id; if ( size_left < 4 ) { LogError("Process_ipfix [%u] Template withdraw size error at %s line %u" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; id = ntohs(ipfix_template_record->TemplateID); if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) { remove_all_translation_tables(exporter); ReInitExtensionMapList(fs); } else { remove_translation_table(fs, exporter, id); } DataPtr = DataPtr + 4; if ( size_left < 4 ) { dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } } } // End of Process_ipfix_template_withdraw
169,583
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 ip_options *tcp_v4_save_options(struct sock *sk, struct sk_buff *skb) { struct ip_options *opt = &(IPCB(skb)->opt); struct ip_options *dopt = NULL; if (opt && opt->optlen) { int opt_size = optlength(opt); dopt = kmalloc(opt_size, GFP_ATOMIC); if (dopt) { if (ip_options_echo(dopt, skb)) { kfree(dopt); dopt = NULL; } } } return dopt; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static struct ip_options *tcp_v4_save_options(struct sock *sk, static struct ip_options_rcu *tcp_v4_save_options(struct sock *sk, struct sk_buff *skb) { const struct ip_options *opt = &(IPCB(skb)->opt); struct ip_options_rcu *dopt = NULL; if (opt && opt->optlen) { int opt_size = sizeof(*dopt) + opt->optlen; dopt = kmalloc(opt_size, GFP_ATOMIC); if (dopt) { if (ip_options_echo(&dopt->opt, skb)) { kfree(dopt); dopt = NULL; } } } return dopt; }
165,571
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: err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } s += padlen + 3; (*psig) = s; /* return SUCCESS */ return NULL; } Commit Message: wo#7449 . verify padding contents for IKEv2 RSA sig check Special thanks to Sze Yiu Chau of Purdue University ([email protected]) who reported the issue. CWE ID: CWE-347
err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } /* signature starts after ASN wrapped padding [00,01,FF..FF,00] */ (*psig) = s + padlen + 3; /* verify padding contents */ { const u_char *p; size_t cnt_ffs = 0; for (p = s+2; p < s+padlen+2; p++) if (*p == 0xFF) cnt_ffs ++; if (cnt_ffs != padlen) return "4" "invalid Padding String"; } /* return SUCCESS */ return NULL; }
169,097
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 atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, "eth%d"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; } Commit Message: atl2: Disable unimplemented scatter/gather feature atl2 includes NETIF_F_SG in hw_features even though it has no support for non-linear skbs. This bug was originally harmless since the driver does not claim to implement checksum offload and that used to be a requirement for SG. Now that SG and checksum offload are independent features, if you explicitly enable SG *and* use one of the rare protocols that can use SG without checkusm offload, this potentially leaks sensitive information (before you notice that it just isn't working). Therefore this obscure bug has been designated CVE-2016-2117. Reported-by: Justin Yackoski <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Fixes: ec5f06156423 ("net: Kill link between CSUM and SG features.") Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, "eth%d"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; }
167,436
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: jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; Jbig2SymbolDict **dicts; int n_dicts = jbig2_sd_count_referred(ctx, segment); int dindex = 0; dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts); if (dicts == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries"); return NULL; } for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) { /* add this referred to symbol dictionary */ dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result; } } if (dindex != n_dicts) { /* should never happen */ jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex); } return (dicts); } Commit Message: CWE ID: CWE-119
jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; Jbig2SymbolDict **dicts; uint32_t n_dicts = jbig2_sd_count_referred(ctx, segment); uint32_t dindex = 0; dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts); if (dicts == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries"); return NULL; } for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) { /* add this referred to symbol dictionary */ dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result; } } if (dindex != n_dicts) { /* should never happen */ jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex); } return (dicts); }
165,501
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 BluetoothDeviceChooserController::GetDevice( blink::mojom::WebBluetoothRequestDeviceOptionsPtr options, const SuccessCallback& success_callback, const ErrorCallback& error_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(success_callback_.is_null()); DCHECK(error_callback_.is_null()); success_callback_ = success_callback; error_callback_ = error_callback; options_ = std::move(options); LogRequestDeviceOptions(options_); if (options_->filters && BluetoothBlocklist::Get().IsExcluded(options_->filters.value())) { RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLOCKLISTED_SERVICE_IN_FILTER); PostErrorCallback( blink::mojom::WebBluetoothResult::REQUEST_DEVICE_WITH_BLOCKLISTED_UUID); return; } BluetoothBlocklist::Get().RemoveExcludedUUIDs(options_.get()); const url::Origin requesting_origin = render_frame_host_->GetLastCommittedOrigin(); const url::Origin embedding_origin = web_contents_->GetMainFrame()->GetLastCommittedOrigin(); if (!embedding_origin.IsSameOriginWith(requesting_origin)) { PostErrorCallback(blink::mojom::WebBluetoothResult:: REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME); return; } DCHECK(!requesting_origin.opaque()); if (!adapter_->IsPresent()) { DVLOG(1) << "Bluetooth Adapter not present. Can't serve requestDevice."; RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLUETOOTH_ADAPTER_NOT_PRESENT); PostErrorCallback(blink::mojom::WebBluetoothResult::NO_BLUETOOTH_ADAPTER); return; } switch (GetContentClient()->browser()->AllowWebBluetooth( web_contents_->GetBrowserContext(), requesting_origin, embedding_origin)) { case ContentBrowserClient::AllowWebBluetoothResult::BLOCK_POLICY: { RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLUETOOTH_CHOOSER_POLICY_DISABLED); PostErrorCallback(blink::mojom::WebBluetoothResult:: CHOOSER_NOT_SHOWN_API_LOCALLY_DISABLED); return; } case ContentBrowserClient::AllowWebBluetoothResult:: BLOCK_GLOBALLY_DISABLED: { web_contents_->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kInfo, "Bluetooth permission has been blocked."); RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLUETOOTH_GLOBALLY_DISABLED); PostErrorCallback(blink::mojom::WebBluetoothResult:: CHOOSER_NOT_SHOWN_API_GLOBALLY_DISABLED); return; } case ContentBrowserClient::AllowWebBluetoothResult::ALLOW: break; } BluetoothChooser::EventHandler chooser_event_handler = base::Bind(&BluetoothDeviceChooserController::OnBluetoothChooserEvent, base::Unretained(this)); if (WebContentsDelegate* delegate = web_contents_->GetDelegate()) { chooser_ = delegate->RunBluetoothChooser(render_frame_host_, std::move(chooser_event_handler)); } if (!chooser_.get()) { PostErrorCallback( blink::mojom::WebBluetoothResult::WEB_BLUETOOTH_NOT_SUPPORTED); return; } if (!chooser_->CanAskForScanningPermission()) { DVLOG(1) << "Closing immediately because Chooser cannot obtain permission."; OnBluetoothChooserEvent(BluetoothChooser::Event::DENIED_PERMISSION, "" /* device_address */); return; } device_ids_.clear(); PopulateConnectedDevices(); if (!chooser_.get()) { return; } if (!adapter_->IsPowered()) { chooser_->SetAdapterPresence( BluetoothChooser::AdapterPresence::POWERED_OFF); return; } StartDeviceDiscovery(); } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
void BluetoothDeviceChooserController::GetDevice( blink::mojom::WebBluetoothRequestDeviceOptionsPtr options, const SuccessCallback& success_callback, const ErrorCallback& error_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(success_callback_.is_null()); DCHECK(error_callback_.is_null()); success_callback_ = success_callback; error_callback_ = error_callback; options_ = std::move(options); LogRequestDeviceOptions(options_); if (options_->filters && BluetoothBlocklist::Get().IsExcluded(options_->filters.value())) { RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLOCKLISTED_SERVICE_IN_FILTER); PostErrorCallback(WebBluetoothResult::REQUEST_DEVICE_WITH_BLOCKLISTED_UUID); return; } BluetoothBlocklist::Get().RemoveExcludedUUIDs(options_.get()); WebBluetoothResult allow_result = web_bluetooth_service_->GetBluetoothAllowed(); if (allow_result != WebBluetoothResult::SUCCESS) { switch (allow_result) { case WebBluetoothResult::CHOOSER_NOT_SHOWN_API_LOCALLY_DISABLED: { RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLUETOOTH_CHOOSER_POLICY_DISABLED); break; } case WebBluetoothResult::CHOOSER_NOT_SHOWN_API_GLOBALLY_DISABLED: { // Log to the developer console. web_contents_->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kInfo, "Bluetooth permission has been blocked."); // Block requests. RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLUETOOTH_GLOBALLY_DISABLED); break; } default: break; } PostErrorCallback(allow_result); return; } if (!adapter_->IsPresent()) { DVLOG(1) << "Bluetooth Adapter not present. Can't serve requestDevice."; RecordRequestDeviceOutcome( UMARequestDeviceOutcome::BLUETOOTH_ADAPTER_NOT_PRESENT); PostErrorCallback(WebBluetoothResult::NO_BLUETOOTH_ADAPTER); return; } BluetoothChooser::EventHandler chooser_event_handler = base::Bind(&BluetoothDeviceChooserController::OnBluetoothChooserEvent, base::Unretained(this)); if (WebContentsDelegate* delegate = web_contents_->GetDelegate()) { chooser_ = delegate->RunBluetoothChooser(render_frame_host_, std::move(chooser_event_handler)); } if (!chooser_.get()) { PostErrorCallback(WebBluetoothResult::WEB_BLUETOOTH_NOT_SUPPORTED); return; } if (!chooser_->CanAskForScanningPermission()) { DVLOG(1) << "Closing immediately because Chooser cannot obtain permission."; OnBluetoothChooserEvent(BluetoothChooser::Event::DENIED_PERMISSION, "" /* device_address */); return; } device_ids_.clear(); PopulateConnectedDevices(); if (!chooser_.get()) { return; } if (!adapter_->IsPowered()) { chooser_->SetAdapterPresence( BluetoothChooser::AdapterPresence::POWERED_OFF); return; } StartDeviceDiscovery(); }
172,443
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 ping_unhash(struct sock *sk) { struct inet_sock *isk = inet_sk(sk); pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num); if (sk_hashed(sk)) { write_lock_bh(&ping_table.lock); hlist_nulls_del(&sk->sk_nulls_node); sk_nulls_node_init(&sk->sk_nulls_node); sock_put(sk); isk->inet_num = 0; isk->inet_sport = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); write_unlock_bh(&ping_table.lock); } } Commit Message: ping: implement proper locking We got a report of yet another bug in ping http://www.openwall.com/lists/oss-security/2017/03/24/6 ->disconnect() is not called with socket lock held. Fix this by acquiring ping rwlock earlier. Thanks to Daniel, Alexander and Andrey for letting us know this problem. Fixes: c319b4d76b9e ("net: ipv4: add IPPROTO_ICMP socket kind") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Daniel Jiang <[email protected]> Reported-by: Solar Designer <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
void ping_unhash(struct sock *sk) { struct inet_sock *isk = inet_sk(sk); pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num); write_lock_bh(&ping_table.lock); if (sk_hashed(sk)) { hlist_nulls_del(&sk->sk_nulls_node); sk_nulls_node_init(&sk->sk_nulls_node); sock_put(sk); isk->inet_num = 0; isk->inet_sport = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); } write_unlock_bh(&ping_table.lock); }
168,435
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 CreatePrintSettingsDictionary(DictionaryValue* dict) { dict->SetBoolean(printing::kSettingLandscape, false); dict->SetBoolean(printing::kSettingCollate, false); dict->SetInteger(printing::kSettingColor, printing::GRAY); dict->SetBoolean(printing::kSettingPrintToPDF, true); dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX); dict->SetInteger(printing::kSettingCopies, 1); dict->SetString(printing::kSettingDeviceName, "dummy"); dict->SetString(printing::kPreviewUIAddr, "0xb33fbeef"); dict->SetInteger(printing::kPreviewRequestID, 12345); dict->SetBoolean(printing::kIsFirstRequest, true); dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS); dict->SetBoolean(printing::kSettingPreviewModifiable, false); dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false); dict->SetBoolean(printing::kSettingGenerateDraftData, true); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void CreatePrintSettingsDictionary(DictionaryValue* dict) { dict->SetBoolean(printing::kSettingLandscape, false); dict->SetBoolean(printing::kSettingCollate, false); dict->SetInteger(printing::kSettingColor, printing::GRAY); dict->SetBoolean(printing::kSettingPrintToPDF, true); dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX); dict->SetInteger(printing::kSettingCopies, 1); dict->SetString(printing::kSettingDeviceName, "dummy"); dict->SetInteger(printing::kPreviewUIID, 4); dict->SetInteger(printing::kPreviewRequestID, 12345); dict->SetBoolean(printing::kIsFirstRequest, true); dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS); dict->SetBoolean(printing::kSettingPreviewModifiable, false); dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false); dict->SetBoolean(printing::kSettingGenerateDraftData, true); }
170,858
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: xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while ((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if ((in_space) && (normalize)) { while (buf[len - 1] == 0x20) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); } Commit Message: Add a check to prevent len from going negative in xmlParseAttValueComplex. BUG=158249 Review URL: https://chromiumcodereview.appspot.com/11343029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@164867 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while ((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); }
170,696
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_set_filter_heuristics(png_structp png_ptr, int heuristic_method, int num_weights, png_doublep filter_weights, png_doublep filter_costs) { int i; png_debug(1, "in png_set_filter_heuristics"); if (png_ptr == NULL) return; if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST) { png_warning(png_ptr, "Unknown filter heuristic method"); return; } if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT) { heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED; } if (num_weights < 0 || filter_weights == NULL || heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED) { num_weights = 0; } png_ptr->num_prev_filters = (png_byte)num_weights; png_ptr->heuristic_method = (png_byte)heuristic_method; if (num_weights > 0) { if (png_ptr->prev_filters == NULL) { png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_byte) * num_weights)); /* To make sure that the weighting starts out fairly */ for (i = 0; i < num_weights; i++) { png_ptr->prev_filters[i] = 255; } } if (png_ptr->filter_weights == NULL) { png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); for (i = 0; i < num_weights; i++) { png_ptr->inv_filter_weights[i] = png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; } } for (i = 0; i < num_weights; i++) { if (filter_weights[i] < 0.0) { png_ptr->inv_filter_weights[i] = png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; } else { png_ptr->inv_filter_weights[i] = (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5); png_ptr->filter_weights[i] = (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5); } } } /* If, in the future, there are other filter methods, this would * need to be based on png_ptr->filter. */ if (png_ptr->filter_costs == NULL) { png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) { png_ptr->inv_filter_costs[i] = png_ptr->filter_costs[i] = PNG_COST_FACTOR; } } /* Here is where we set the relative costs of the different filters. We * should take the desired compression level into account when setting * the costs, so that Paeth, for instance, has a high relative cost at low * compression levels, while it has a lower relative cost at higher * compression settings. The filter types are in order of increasing * relative cost, so it would be possible to do this with an algorithm. */ for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) { if (filter_costs == NULL || filter_costs[i] < 0.0) { png_ptr->inv_filter_costs[i] = png_ptr->filter_costs[i] = PNG_COST_FACTOR; } else if (filter_costs[i] >= 1.0) { png_ptr->inv_filter_costs[i] = (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5); png_ptr->filter_costs[i] = (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5); } } } 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_set_filter_heuristics(png_structp png_ptr, int heuristic_method, int num_weights, png_doublep filter_weights, png_doublep filter_costs) { PNG_UNUSED(png_ptr) PNG_UNUSED(heuristic_method) PNG_UNUSED(num_weights) PNG_UNUSED(filter_weights) PNG_UNUSED(filter_costs) }
172,188
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 vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) { struct virgl_gl_ctx_param ctx_params; int i; if (blit_ctx->initialised) { vrend_clicbs->make_current(0, blit_ctx->gl_context); return; } ctx_params.shared = true; ctx_params.major_ver = VREND_GL_VER_MAJOR; ctx_params.minor_ver = VREND_GL_VER_MINOR; vrend_clicbs->make_current(0, blit_ctx->gl_context); glGenVertexArrays(1, &blit_ctx->vaoid); glGenFramebuffers(1, &blit_ctx->fb_id); glGenBuffers(1, &blit_ctx->vbo_id); blit_build_vs_passthrough(blit_ctx); for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][3] = 1; /*v.w*/ glBindVertexArray(blit_ctx->vaoid); glBindBuffer(GL_ARRAY_BUFFER, blit_ctx->vbo_id); } Commit Message: CWE ID: CWE-772
static void vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) { struct virgl_gl_ctx_param ctx_params; int i; if (blit_ctx->initialised) { vrend_clicbs->make_current(0, blit_ctx->gl_context); return; } blit_ctx->initialised = true; ctx_params.shared = true; ctx_params.major_ver = VREND_GL_VER_MAJOR; ctx_params.minor_ver = VREND_GL_VER_MINOR; vrend_clicbs->make_current(0, blit_ctx->gl_context); glGenVertexArrays(1, &blit_ctx->vaoid); glGenFramebuffers(1, &blit_ctx->fb_id); glGenBuffers(1, &blit_ctx->vbo_id); blit_build_vs_passthrough(blit_ctx); for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][3] = 1; /*v.w*/ glBindVertexArray(blit_ctx->vaoid); glBindBuffer(GL_ARRAY_BUFFER, blit_ctx->vbo_id); }
164,955
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 double pcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* Percentage error permitted in the linear values. Note that the specified * value is a percentage but this routine returns a simple number. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxpc16 * .01; else return pm->maxpc8 * .01; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double pcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double pcerr(const png_modifier *pm, int in_depth, int out_depth) { /* Percentage error permitted in the linear values. Note that the specified * value is a percentage but this routine returns a simple number. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxpc16 * .01; else return pm->maxpc8 * .01; }
173,677
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 gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height) { const int w = 8; const int ix = ox >> (16 + shift); const int iy = oy >> (16 + shift); const int oxs = ox >> 4; const int oys = oy >> 4; const int dxxs = dxx >> 4; const int dxys = dxy >> 4; const int dyxs = dyx >> 4; const int dyys = dyy >> 4; const uint16_t r4[4] = { r, r, r, r }; const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; const uint64_t shift2 = 2 * shift; #define MAX_STRIDE 4096U #define MAX_H 8U uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; int x, y; const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); int need_emu = (unsigned) ix >= width - w || (unsigned) iy >= height - h; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || (dxx | dxy | dyx | dyy) & 15 || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy * stride; if (need_emu) { ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); src = edge_buf; } __asm__ volatile ( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r" (1 << shift)); for (x = 0; x < w; x += 4) { uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), oxs - dxys + dxxs * (x + 1), oxs - dxys + dxxs * (x + 2), oxs - dxys + dxxs * (x + 3) }; uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), oys - dyys + dyxs * (x + 1), oys - dyys + dyxs * (x + 2), oys - dyys + dyxs * (x + 3) }; for (y = 0; y < h; y++) { __asm__ volatile ( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m" (*dx4), "+m" (*dy4) : "m" (*dxy4), "m" (*dyy4)); __asm__ volatile ( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy) "pmullw %%mm5, %%mm3 \n\t" // dx * dy "pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy "pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy "pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy) "pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m" (dst[x + y * stride]) : "m" (src[0]), "m" (src[1]), "m" (src[stride]), "m" (src[stride + 1]), "m" (*r4), "m" (shift2)); src += stride; } src += 4 - h * stride; } } Commit Message: avcodec/x86/mpegvideodsp: Fix signedness bug in need_emu Fixes: out of array read Fixes: 3516/attachment-311488.dat Found-by: Insu Yun, Georgia Tech. Tested-by: [email protected] Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-125
static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height) { const int w = 8; const int ix = ox >> (16 + shift); const int iy = oy >> (16 + shift); const int oxs = ox >> 4; const int oys = oy >> 4; const int dxxs = dxx >> 4; const int dxys = dxy >> 4; const int dyxs = dyx >> 4; const int dyys = dyy >> 4; const uint16_t r4[4] = { r, r, r, r }; const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; const uint64_t shift2 = 2 * shift; #define MAX_STRIDE 4096U #define MAX_H 8U uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; int x, y; const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); int need_emu = (unsigned) ix >= width - w || width < w || (unsigned) iy >= height - h || height< h ; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || (dxx | dxy | dyx | dyy) & 15 || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy * stride; if (need_emu) { ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); src = edge_buf; } __asm__ volatile ( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r" (1 << shift)); for (x = 0; x < w; x += 4) { uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), oxs - dxys + dxxs * (x + 1), oxs - dxys + dxxs * (x + 2), oxs - dxys + dxxs * (x + 3) }; uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), oys - dyys + dyxs * (x + 1), oys - dyys + dyxs * (x + 2), oys - dyys + dyxs * (x + 3) }; for (y = 0; y < h; y++) { __asm__ volatile ( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m" (*dx4), "+m" (*dy4) : "m" (*dxy4), "m" (*dyy4)); __asm__ volatile ( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy) "pmullw %%mm5, %%mm3 \n\t" // dx * dy "pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy "pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy "pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy) "pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m" (dst[x + y * stride]) : "m" (src[0]), "m" (src[1]), "m" (src[stride]), "m" (src[stride + 1]), "m" (*r4), "m" (shift2)); src += stride; } src += 4 - h * stride; } }
167,655
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 write_mem(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { phys_addr_t p = *ppos; ssize_t written, sz; unsigned long copied; void *ptr; if (p != *ppos) return -EFBIG; if (!valid_phys_addr_range(p, count)) return -EFAULT; written = 0; #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED /* we don't have page 0 mapped on sparc and m68k.. */ if (p < PAGE_SIZE) { sz = size_inside_page(p, count); /* Hmm. Do something? */ buf += sz; p += sz; count -= sz; written += sz; } #endif while (count > 0) { sz = size_inside_page(p, count); if (!range_is_allowed(p >> PAGE_SHIFT, sz)) return -EPERM; /* * On ia64 if a page has been mapped somewhere as uncached, then * it must also be accessed uncached by the kernel or data * corruption may occur. */ ptr = xlate_dev_mem_ptr(p); if (!ptr) { if (written) break; return -EFAULT; } copied = copy_from_user(ptr, buf, sz); unxlate_dev_mem_ptr(p, ptr); if (copied) { written += sz - copied; if (written) break; return -EFAULT; } buf += sz; p += sz; count -= sz; written += sz; } *ppos += written; return written; } Commit Message: mm: Tighten x86 /dev/mem with zeroing reads Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is disallowed. However, on x86, the first 1MB was always allowed for BIOS and similar things, regardless of it actually being System RAM. It was possible for heap to end up getting allocated in low 1MB RAM, and then read by things like x86info or dd, which would trip hardened usercopy: usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes) This changes the x86 exception for the low 1MB by reading back zeros for System RAM areas instead of blindly allowing them. More work is needed to extend this to mmap, but currently mmap doesn't go through usercopy, so hardened usercopy won't Oops the kernel. Reported-by: Tommi Rantala <[email protected]> Tested-by: Tommi Rantala <[email protected]> Signed-off-by: Kees Cook <[email protected]> CWE ID: CWE-732
static ssize_t write_mem(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { phys_addr_t p = *ppos; ssize_t written, sz; unsigned long copied; void *ptr; if (p != *ppos) return -EFBIG; if (!valid_phys_addr_range(p, count)) return -EFAULT; written = 0; #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED /* we don't have page 0 mapped on sparc and m68k.. */ if (p < PAGE_SIZE) { sz = size_inside_page(p, count); /* Hmm. Do something? */ buf += sz; p += sz; count -= sz; written += sz; } #endif while (count > 0) { int allowed; sz = size_inside_page(p, count); allowed = page_is_allowed(p >> PAGE_SHIFT); if (!allowed) return -EPERM; /* Skip actual writing when a page is marked as restricted. */ if (allowed == 1) { /* * On ia64 if a page has been mapped somewhere as * uncached, then it must also be accessed uncached * by the kernel or data corruption may occur. */ ptr = xlate_dev_mem_ptr(p); if (!ptr) { if (written) break; return -EFAULT; } copied = copy_from_user(ptr, buf, sz); unxlate_dev_mem_ptr(p, ptr); if (copied) { written += sz - copied; if (written) break; return -EFAULT; } } buf += sz; p += sz; count -= sz; written += sz; } *ppos += written; return written; }
168,243
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 Chapters::Atom::Clear() { delete[] m_string_uid; m_string_uid = NULL; while (m_displays_count > 0) { Display& d = m_displays[--m_displays_count]; d.Clear(); } delete[] m_displays; m_displays = NULL; m_displays_size = 0; } 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
void Chapters::Atom::Clear()
174,245
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 WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) { DCHECK(main_task_runner_->BelongsToCurrentThread()); channel_.reset(); if (launch_elevated_) { if (job_.IsValid()) { TerminateJobObject(job_, exit_code); } } else { if (worker_process_.IsValid()) { TerminateProcess(worker_process_, exit_code); } } } 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
void WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) { DCHECK(main_task_runner_->BelongsToCurrentThread()); channel_.reset(); pipe_.Close(); if (launch_elevated_) { if (job_.IsValid()) { TerminateJobObject(job_, exit_code); } } else { if (worker_process_.IsValid()) { TerminateProcess(worker_process_, exit_code); } } }
171,559
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: struct key *key_get_instantiation_authkey(key_serial_t target_id) { char description[16]; struct keyring_search_context ctx = { .index_key.type = &key_type_request_key_auth, .index_key.description = description, .cred = current_cred(), .match_data.cmp = user_match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *authkey; key_ref_t authkey_ref; sprintf(description, "%x", target_id); authkey_ref = search_process_keyrings(&ctx); if (IS_ERR(authkey_ref)) { authkey = ERR_CAST(authkey_ref); if (authkey == ERR_PTR(-EAGAIN)) authkey = ERR_PTR(-ENOKEY); goto error; } authkey = key_ref_to_ptr(authkey_ref); if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) { key_put(authkey); authkey = ERR_PTR(-EKEYREVOKED); } error: return authkey; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476
struct key *key_get_instantiation_authkey(key_serial_t target_id) { char description[16]; struct keyring_search_context ctx = { .index_key.type = &key_type_request_key_auth, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *authkey; key_ref_t authkey_ref; sprintf(description, "%x", target_id); authkey_ref = search_process_keyrings(&ctx); if (IS_ERR(authkey_ref)) { authkey = ERR_CAST(authkey_ref); if (authkey == ERR_PTR(-EAGAIN)) authkey = ERR_PTR(-ENOKEY); goto error; } authkey = key_ref_to_ptr(authkey_ref); if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) { key_put(authkey); authkey = ERR_PTR(-EKEYREVOKED); } error: return authkey; }
168,442
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: hash_foreach (gpointer key, gpointer val, gpointer user_data) { const char *keystr = key; const char *valstr = val; guint *count = user_data; *count += (strlen (keystr) + strlen (valstr)); g_print ("%s -> %s\n", keystr, valstr); } Commit Message: CWE ID: CWE-264
hash_foreach (gpointer key, gpointer val, gpointer user_data)
165,084
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 pagemap_open(struct inode *inode, struct file *file) { pr_warn_once("Bits 55-60 of /proc/PID/pagemap entries are about " "to stop being page-shift some time soon. See the " "linux/Documentation/vm/pagemap.txt for details.\n"); return 0; } Commit Message: pagemap: do not leak physical addresses to non-privileged userspace As pointed by recent post[1] on exploiting DRAM physical imperfection, /proc/PID/pagemap exposes sensitive information which can be used to do attacks. This disallows anybody without CAP_SYS_ADMIN to read the pagemap. [1] http://googleprojectzero.blogspot.com/2015/03/exploiting-dram-rowhammer-bug-to-gain.html [ Eventually we might want to do anything more finegrained, but for now this is the simple model. - Linus ] Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Konstantin Khlebnikov <[email protected]> Acked-by: Andy Lutomirski <[email protected]> Cc: Pavel Emelyanov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Mark Seaborn <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
static int pagemap_open(struct inode *inode, struct file *file) { /* do not disclose physical addresses: attack vector */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; pr_warn_once("Bits 55-60 of /proc/PID/pagemap entries are about " "to stop being page-shift some time soon. See the " "linux/Documentation/vm/pagemap.txt for details.\n"); return 0; }
167,450
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_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) { char *f_org, *f_dest; int f_org_len, f_dest_len; long height, width, threshold; gdImagePtr im_org, im_dest, im_tmp; char *fn_org = NULL; char *fn_dest = NULL; FILE *org, *dest; int dest_height = -1; int dest_width = -1; int org_height, org_width; int white, black; int color, color_org, median; int int_threshold; int x, y; float x_ratio, y_ratio; long ignore_warning; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { return; } fn_org = f_org; fn_dest = f_dest; dest_height = height; dest_width = width; int_threshold = threshold; /* Check threshold value */ if (int_threshold < 0 || int_threshold > 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold); RETURN_FALSE; } /* Check origin file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename"); /* Check destination file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename"); /* Open origin file */ org = VCWD_FOPEN(fn_org, "rb"); if (!org) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org); RETURN_FALSE; } /* Open destination file */ dest = VCWD_FOPEN(fn_dest, "wb"); if (!dest) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest); RETURN_FALSE; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im_org = gdImageCreateFromJpegEx(org, ignore_warning); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_PNG */ default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported"); RETURN_FALSE; break; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == NULL ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); RETURN_FALSE; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); fclose(org); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer"); RETURN_FALSE; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } int_threshold = int_threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < int_threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageDestroy (im_tmp ); gdImageWBMP(im_dest, black , dest); fflush(dest); fclose(dest); gdImageDestroy(im_dest); RETURN_TRUE; } Commit Message: Fix bug#72697 - select_colors write out-of-bounds CWE ID: CWE-787
static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) { char *f_org, *f_dest; int f_org_len, f_dest_len; long height, width, threshold; gdImagePtr im_org, im_dest, im_tmp; char *fn_org = NULL; char *fn_dest = NULL; FILE *org, *dest; int dest_height = -1; int dest_width = -1; int org_height, org_width; int white, black; int color, color_org, median; int int_threshold; int x, y; float x_ratio, y_ratio; long ignore_warning; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { return; } fn_org = f_org; fn_dest = f_dest; dest_height = height; dest_width = width; int_threshold = threshold; /* Check threshold value */ if (int_threshold < 0 || int_threshold > 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold); RETURN_FALSE; } /* Check origin file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename"); /* Check destination file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename"); /* Open origin file */ org = VCWD_FOPEN(fn_org, "rb"); if (!org) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org); RETURN_FALSE; } /* Open destination file */ dest = VCWD_FOPEN(fn_dest, "wb"); if (!dest) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest); RETURN_FALSE; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im_org = gdImageCreateFromJpegEx(org, ignore_warning); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_PNG */ default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported"); RETURN_FALSE; break; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == NULL ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); RETURN_FALSE; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); fclose(org); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer"); RETURN_FALSE; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } int_threshold = int_threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < int_threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageDestroy (im_tmp ); gdImageWBMP(im_dest, black , dest); fflush(dest); fclose(dest); gdImageDestroy(im_dest); RETURN_TRUE; }
166,956
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 ParamTraits<GURL>::Write(Message* m, const GURL& p) { DCHECK(p.possibly_invalid_spec().length() <= content::kMaxURLChars); m->WriteString(p.possibly_invalid_spec()); } Commit Message: Beware of print-read inconsistency when serializing GURLs. BUG=165622 Review URL: https://chromiumcodereview.appspot.com/11576038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173583 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void ParamTraits<GURL>::Write(Message* m, const GURL& p) { DCHECK(p.possibly_invalid_spec().length() <= content::kMaxURLChars); // Beware of print-parse inconsistency which would change an invalid // URL into a valid one. Ideally, the message would contain this flag // so that the read side could make the check, but performing it here // avoids changing the on-the-wire representation of such a fundamental // type as GURL. See https://crbug.com/166486 for additional work in // this area. if (!p.is_valid()) { GURL reconstructed_url(p.possibly_invalid_spec()); if (reconstructed_url.is_valid()) { DLOG(WARNING) << "GURL string " << p.possibly_invalid_spec() << " (marked invalid) but parsed as valid."; m->WriteString(std::string()); return; } } m->WriteString(p.possibly_invalid_spec()); }
171,503
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 CoordinatorImpl::GetVmRegionsForHeapProfiler( const std::vector<base::ProcessId>& pids, GetVmRegionsForHeapProfilerCallback callback) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); uint64_t dump_guid = ++next_dump_id_; std::unique_ptr<QueuedVmRegionRequest> request = std::make_unique<QueuedVmRegionRequest>(dump_guid, std::move(callback)); in_progress_vm_region_requests_[dump_guid] = std::move(request); std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } QueuedVmRegionRequest* request_ptr = in_progress_vm_region_requests_[dump_guid].get(); auto os_callback = base::BindRepeating(&CoordinatorImpl::OnOSMemoryDumpForVMRegions, base::Unretained(this), dump_guid); QueuedRequestDispatcher::SetUpAndDispatchVmRegionRequest(request_ptr, clients, pids, os_callback); FinalizeVmRegionDumpIfAllManagersReplied(dump_guid); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::GetVmRegionsForHeapProfiler( const std::vector<base::ProcessId>& pids, GetVmRegionsForHeapProfilerCallback callback) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); uint64_t dump_guid = ++next_dump_id_; std::unique_ptr<QueuedVmRegionRequest> request = std::make_unique<QueuedVmRegionRequest>(dump_guid, std::move(callback)); in_progress_vm_region_requests_[dump_guid] = std::move(request); std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } QueuedVmRegionRequest* request_ptr = in_progress_vm_region_requests_[dump_guid].get(); auto os_callback = base::BindRepeating(&CoordinatorImpl::OnOSMemoryDumpForVMRegions, weak_ptr_factory_.GetWeakPtr(), dump_guid); QueuedRequestDispatcher::SetUpAndDispatchVmRegionRequest(request_ptr, clients, pids, os_callback); FinalizeVmRegionDumpIfAllManagersReplied(dump_guid); }
173,213
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 ImageBitmapFactories::Trace(blink::Visitor* visitor) { visitor->Trace(pending_loaders_); Supplement<LocalDOMWindow>::Trace(visitor); Supplement<WorkerGlobalScope>::Trace(visitor); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Marijn Kruisselbrink <[email protected]> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::Trace(blink::Visitor* visitor) { ImageBitmapFactories::ImageBitmapLoader::~ImageBitmapLoader() { DCHECK(!loader_); }
173,070
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 WarmupURLFetcher::FetchWarmupURLNow( const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1, 2); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server to warm up " "the connection to the proxy." trigger: "A network change while the data reduction proxy is enabled will " "trigger this request." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop it " "is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); GURL warmup_url_with_query_params; GetWarmupURLWithQueryParam(&warmup_url_with_query_params); url_loader_.reset(); fetch_timeout_timer_.Stop(); is_fetch_in_flight_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = warmup_url_with_query_params; resource_request->load_flags = net::LOAD_BYPASS_CACHE; resource_request->render_frame_id = MSG_ROUTING_CONTROL; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->SetAllowHttpErrorResults(true); fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this, &WarmupURLFetcher::OnFetchTimeout); url_loader_->SetOnResponseStartedCallback(base::BindOnce( &WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this))); url_loader_->SetOnRedirectCallback(base::BindRepeating( &WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this))); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( GetNetworkServiceURLLoaderFactory(proxy_server), base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete, base::Unretained(this))); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void WarmupURLFetcher::FetchWarmupURLNow( const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!params::IsIncludedInHoldbackFieldTrial()); UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1, 2); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server to warm up " "the connection to the proxy." trigger: "A network change while the data reduction proxy is enabled will " "trigger this request." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop it " "is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); GURL warmup_url_with_query_params; GetWarmupURLWithQueryParam(&warmup_url_with_query_params); url_loader_.reset(); fetch_timeout_timer_.Stop(); is_fetch_in_flight_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = warmup_url_with_query_params; resource_request->load_flags = net::LOAD_BYPASS_CACHE; resource_request->render_frame_id = MSG_ROUTING_CONTROL; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->SetAllowHttpErrorResults(true); fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this, &WarmupURLFetcher::OnFetchTimeout); url_loader_->SetOnResponseStartedCallback(base::BindOnce( &WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this))); url_loader_->SetOnRedirectCallback(base::BindRepeating( &WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this))); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( GetNetworkServiceURLLoaderFactory(proxy_server), base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete, base::Unretained(this))); }
172,425
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 ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; upperdentry = ovl_dentry_upper(dentry); if (upperdentry) { mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } else { err = ovl_copy_up_last(dentry, attr, false); } ovl_drop_write(dentry); out: return err; } Commit Message: ovl: fix permission checking for setattr [Al Viro] The bug is in being too enthusiastic about optimizing ->setattr() away - instead of "copy verbatim with metadata" + "chmod/chown/utimes" (with the former being always safe and the latter failing in case of insufficient permissions) it tries to combine these two. Note that copyup itself will have to do ->setattr() anyway; _that_ is where the elevated capabilities are right. Having these two ->setattr() (one to set verbatim copy of metadata, another to do what overlayfs ->setattr() had been asked to do in the first place) combined is where it breaks. Signed-off-by: Miklos Szeredi <[email protected]> Cc: <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264
int ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; err = ovl_copy_up(dentry); if (!err) { upperdentry = ovl_dentry_upper(dentry); mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } ovl_drop_write(dentry); out: return err; }
166,559
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 masq_inet_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = ((struct in_ifaddr *)ptr)->ifa_dev->dev; struct netdev_notifier_info info; netdev_notifier_info_init(&info, dev); return masq_device_event(this, event, &info); } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[email protected]> CWE ID: CWE-399
static int masq_inet_event(struct notifier_block *this, unsigned long event, void *ptr) { struct in_device *idev = ((struct in_ifaddr *)ptr)->ifa_dev; struct netdev_notifier_info info; /* The masq_dev_notifier will catch the case of the device going * down. So if the inetdev is dead and being destroyed we have * no work to do. Otherwise this is an individual address removal * and we have to perform the flush. */ if (idev->dead) return NOTIFY_DONE; netdev_notifier_info_init(&info, idev->dev); return masq_device_event(this, event, &info); }
167,356
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 WebMediaPlayerImpl::OnError(PipelineStatus status) { DVLOG(1) << __func__; DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK_NE(status, PIPELINE_OK); if (suppress_destruction_errors_) return; #if defined(OS_ANDROID) if (status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS) { renderer_factory_selector_->SetUseMediaPlayer(true); pipeline_controller_.Stop(); SetMemoryReportingState(false); main_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerImpl::StartPipeline, AsWeakPtr())); return; } #endif ReportPipelineError(load_type_, status, media_log_.get()); media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status)); media_metrics_provider_->OnError(status); if (watch_time_reporter_) watch_time_reporter_->OnError(status); if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) { SetNetworkState(WebMediaPlayer::kNetworkStateFormatError); } else { SetNetworkState(PipelineErrorToNetworkState(status)); } pipeline_controller_.Stop(); UpdatePlayState(); } Commit Message: Fix HasSingleSecurityOrigin for HLS HLS manifests can request segments from a different origin than the original manifest's origin. We do not inspect HLS manifests within Chromium, and instead delegate to Android's MediaPlayer. This means we need to be conservative, and always assume segments might come from a different origin. HasSingleSecurityOrigin should always return false when decoding HLS. Bug: 864283 Change-Id: Ie16849ac6f29ae7eaa9caf342ad0509a226228ef Reviewed-on: https://chromium-review.googlesource.com/1142691 Reviewed-by: Dale Curtis <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Commit-Queue: Thomas Guilbert <[email protected]> Cr-Commit-Position: refs/heads/master@{#576378} CWE ID: CWE-346
void WebMediaPlayerImpl::OnError(PipelineStatus status) { DVLOG(1) << __func__; DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK_NE(status, PIPELINE_OK); if (suppress_destruction_errors_) return; #if defined(OS_ANDROID) if (status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS) { demuxer_found_hls_ = true; renderer_factory_selector_->SetUseMediaPlayer(true); pipeline_controller_.Stop(); SetMemoryReportingState(false); main_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerImpl::StartPipeline, AsWeakPtr())); return; } #endif ReportPipelineError(load_type_, status, media_log_.get()); media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status)); media_metrics_provider_->OnError(status); if (watch_time_reporter_) watch_time_reporter_->OnError(status); if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) { SetNetworkState(WebMediaPlayer::kNetworkStateFormatError); } else { SetNetworkState(PipelineErrorToNetworkState(status)); } pipeline_controller_.Stop(); UpdatePlayState(); }
173,179
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); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fht8x8_ref; } 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); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fht8x8_ref; bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }
174,563
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 VRDisplay::cancelAnimationFrame(int id) { if (!scripted_animation_controller_) return; scripted_animation_controller_->CancelCallback(id); } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID:
void VRDisplay::cancelAnimationFrame(int id) { DVLOG(2) << __FUNCTION__; if (!scripted_animation_controller_) return; scripted_animation_controller_->CancelCallback(id); }
172,000
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 v9fs_device_unrealize_common(V9fsState *s, Error **errp) { g_free(s->ctx.fs_root); g_free(s->tag); } Commit Message: CWE ID: CWE-400
void v9fs_device_unrealize_common(V9fsState *s, Error **errp) { g_free(s->tag); g_free(s->ctx.fs_root); }
164,896
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 double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* Error in the linear composition arithmetic - only relevant when * composition actually happens (0 < alpha < 1). */ if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxcalc16; else if (pm->assume_16_bit_calculations) return pm->maxcalcG; else return pm->maxcalc8; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double calcerr(const png_modifier *pm, int in_depth, int out_depth) { /* Error in the linear composition arithmetic - only relevant when * composition actually happens (0 < alpha < 1). */ if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxcalc16; else if (pm->assume_16_bit_calculations) return pm->maxcalcG; else return pm->maxcalc8; }
173,604
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: pipe_write(struct kiocb *iocb, const struct iovec *_iov, unsigned long nr_segs, loff_t ppos) { struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; ssize_t ret; int do_wakeup; struct iovec *iov = (struct iovec *)_iov; size_t total_len; ssize_t chars; total_len = iov_length(iov, nr_segs); /* Null write succeeds. */ if (unlikely(total_len == 0)) return 0; do_wakeup = 0; ret = 0; __pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); ret = -EPIPE; goto out; } /* We try to merge small writes */ chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */ if (pipe->nrbufs && chars != 0) { int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + lastbuf; const struct pipe_buf_operations *ops = buf->ops; int offset = buf->offset + buf->len; if (ops->can_merge && offset + chars <= PAGE_SIZE) { int error, atomic = 1; void *addr; error = ops->confirm(pipe, buf); if (error) goto out; iov_fault_in_pages_read(iov, chars); redo1: if (atomic) addr = kmap_atomic(buf->page); else addr = kmap(buf->page); error = pipe_iov_copy_from_user(offset + addr, iov, chars, atomic); if (atomic) kunmap_atomic(addr); else kunmap(buf->page); ret = error; do_wakeup = 1; if (error) { if (atomic) { atomic = 0; goto redo1; } goto out; } buf->len += chars; total_len -= chars; ret = chars; if (!total_len) goto out; } } for (;;) { int bufs; if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } bufs = pipe->nrbufs; if (bufs < pipe->buffers) { int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1); struct pipe_buffer *buf = pipe->bufs + newbuf; struct page *page = pipe->tmp_page; char *src; int error, atomic = 1; if (!page) { page = alloc_page(GFP_HIGHUSER); if (unlikely(!page)) { ret = ret ? : -ENOMEM; break; } pipe->tmp_page = page; } /* Always wake up, even if the copy fails. Otherwise * we lock up (O_NONBLOCK-)readers that sleep due to * syscall merging. * FIXME! Is this really true? */ do_wakeup = 1; chars = PAGE_SIZE; if (chars > total_len) chars = total_len; iov_fault_in_pages_read(iov, chars); redo2: if (atomic) src = kmap_atomic(page); else src = kmap(page); error = pipe_iov_copy_from_user(src, iov, chars, atomic); if (atomic) kunmap_atomic(src); else kunmap(page); if (unlikely(error)) { if (atomic) { atomic = 0; goto redo2; } if (!ret) ret = error; break; } ret += chars; /* Insert it into the buffer array */ buf->page = page; buf->ops = &anon_pipe_buf_ops; buf->offset = 0; buf->len = chars; buf->flags = 0; if (is_packetized(filp)) { buf->ops = &packet_pipe_buf_ops; buf->flags = PIPE_BUF_FLAG_PACKET; } pipe->nrbufs = ++bufs; pipe->tmp_page = NULL; total_len -= chars; if (!total_len) break; } if (bufs < pipe->buffers) continue; if (filp->f_flags & O_NONBLOCK) { if (!ret) ret = -EAGAIN; break; } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); do_wakeup = 0; } pipe->waiting_writers++; pipe_wait(pipe); pipe->waiting_writers--; } out: __pipe_unlock(pipe); if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) { int err = file_update_time(filp); if (err) ret = err; sb_end_write(file_inode(filp)->i_sb); } return ret; } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
pipe_write(struct kiocb *iocb, const struct iovec *_iov, pipe_write(struct kiocb *iocb, struct iov_iter *from) { struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; ssize_t ret = 0; int do_wakeup = 0; size_t total_len = iov_iter_count(from); ssize_t chars; /* Null write succeeds. */ if (unlikely(total_len == 0)) return 0; __pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); ret = -EPIPE; goto out; } /* We try to merge small writes */ chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */ if (pipe->nrbufs && chars != 0) { int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + lastbuf; const struct pipe_buf_operations *ops = buf->ops; int offset = buf->offset + buf->len; if (ops->can_merge && offset + chars <= PAGE_SIZE) { int error = ops->confirm(pipe, buf); if (error) goto out; ret = copy_page_from_iter(buf->page, offset, chars, from); if (unlikely(ret < chars)) { error = -EFAULT; goto out; } do_wakeup = 1; buf->len += chars; ret = chars; if (!iov_iter_count(from)) goto out; } } for (;;) { int bufs; if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } bufs = pipe->nrbufs; if (bufs < pipe->buffers) { int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1); struct pipe_buffer *buf = pipe->bufs + newbuf; struct page *page = pipe->tmp_page; int copied; if (!page) { page = alloc_page(GFP_HIGHUSER); if (unlikely(!page)) { ret = ret ? : -ENOMEM; break; } pipe->tmp_page = page; } /* Always wake up, even if the copy fails. Otherwise * we lock up (O_NONBLOCK-)readers that sleep due to * syscall merging. * FIXME! Is this really true? */ do_wakeup = 1; copied = copy_page_from_iter(page, 0, PAGE_SIZE, from); if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) { if (!ret) ret = -EFAULT; break; } ret += copied; /* Insert it into the buffer array */ buf->page = page; buf->ops = &anon_pipe_buf_ops; buf->offset = 0; buf->len = copied; buf->flags = 0; if (is_packetized(filp)) { buf->ops = &packet_pipe_buf_ops; buf->flags = PIPE_BUF_FLAG_PACKET; } pipe->nrbufs = ++bufs; pipe->tmp_page = NULL; if (!iov_iter_count(from)) break; } if (bufs < pipe->buffers) continue; if (filp->f_flags & O_NONBLOCK) { if (!ret) ret = -EAGAIN; break; } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); do_wakeup = 0; } pipe->waiting_writers++; pipe_wait(pipe); pipe->waiting_writers--; } out: __pipe_unlock(pipe); if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) { int err = file_update_time(filp); if (err) ret = err; sb_end_write(file_inode(filp)->i_sb); } return ret; }
166,687
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 IOThread::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(prefs::kAuthSchemes, "basic,digest,ntlm,negotiate," "spdyproxy"); registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false); registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false); registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string()); registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist, std::string()); registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string()); registry->RegisterStringPref(prefs::kSpdyProxyAuthOrigin, std::string()); registry->RegisterBooleanPref(prefs::kEnableReferrers, true); registry->RegisterInt64Pref(prefs::kHttpReceivedContentLength, 0); registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0); #if defined(OS_ANDROID) || defined(OS_IOS) registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength); registry->RegisterListPref( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyOriginalContentLengthViaDataReductionProxy); registry->RegisterListPref( prefs::kDailyContentLengthViaDataReductionProxy); registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate, 0L); #endif registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void IOThread::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(prefs::kAuthSchemes, "basic,digest,ntlm,negotiate," "spdyproxy"); registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false); registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false); registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string()); registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist, std::string()); registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string()); registry->RegisterStringPref(prefs::kSpdyProxyAuthOrigin, std::string()); registry->RegisterBooleanPref(prefs::kEnableReferrers, true); registry->RegisterInt64Pref(prefs::kHttpReceivedContentLength, 0); registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0); #if defined(OS_ANDROID) || defined(OS_IOS) registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength); registry->RegisterListPref( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled); registry->RegisterListPref( prefs::kDailyOriginalContentLengthViaDataReductionProxy); registry->RegisterListPref( prefs::kDailyContentLengthViaDataReductionProxy); registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate, 0L); #endif registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true); }
171,320
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_init_sec_context( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { send_token_flag send_token = NO_TOKEN_SEND; OM_uint32 tmpmin, ret, negState; gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_cred_id_t spcred = NULL; spnego_gss_ctx_id_t spnego_ctx = NULL; dsyslog("Entering init_sec_context\n"); mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER; negState = REJECT; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context * function and examine the results. * 3. Process or generate MICs if necessary. * * The three steps share responsibility for determining when the * exchange is complete. If the selected mech completed in a previous * call and no MIC exchange is expected, then step 1 will decide. If * the selected mech completes in this call and no MIC exchange is * expected, then step 2 will decide. If a MIC exchange is expected, * then step 3 will decide. If an error occurs in any step, the * exchange will be aborted, possibly with an error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * send_token is used to indicate what type of token, if any, should be * generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (actual_mech != NULL) *actual_mech = GSS_C_NO_OID; /* Step 1: perform mechanism negotiation. */ spcred = (spnego_gss_cred_id_t)claimant_cred_handle; if (*context_handle == GSS_C_NO_CONTEXT) { ret = init_ctx_new(minor_status, spcred, context_handle, &send_token); if (ret != GSS_S_CONTINUE_NEEDED) { goto cleanup; } } else { ret = init_ctx_cont(minor_status, context_handle, input_token, &mechtok_in, &mechListMIC_in, &negState, &send_token); if (HARD_ERROR(ret)) { goto cleanup; } } /* Step 2: invoke the selected or optimistic mechanism's * gss_init_sec_context function, if it didn't complete previously. */ spnego_ctx = (spnego_gss_ctx_id_t)*context_handle; if (!spnego_ctx->mech_complete) { ret = init_ctx_call_init( minor_status, spnego_ctx, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, &mechtok_out, ret_flags, time_rec, &negState, &send_token); /* Give the mechanism a chance to force a mechlistMIC. */ if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx)) spnego_ctx->mic_reqd = 1; } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && spnego_ctx->mech_complete && (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mechListMIC_in, (mechtok_out.length != 0), spnego_ctx, &mechListMIC_out, &negState, &send_token); } cleanup: if (send_token == INIT_TOKEN_SEND) { if (make_spnego_tokenInit_msg(spnego_ctx, 0, mechListMIC_out, req_flags, &mechtok_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } else if (send_token != NO_TOKEN_SEND) { if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID, &mechtok_out, mechListMIC_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } gss_release_buffer(&tmpmin, &mechtok_out); if (ret == GSS_S_COMPLETE) { /* * Now, switch the output context to refer to the * negotiated mechanism's context. */ *context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle; if (actual_mech != NULL) *actual_mech = spnego_ctx->actual_mech; if (ret_flags != NULL) *ret_flags = spnego_ctx->ctx_flags; release_spnego_ctx(&spnego_ctx); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (spnego_ctx != NULL) { gss_delete_sec_context(&tmpmin, &spnego_ctx->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&spnego_ctx); } *context_handle = GSS_C_NO_CONTEXT; } if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mechListMIC_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_in); free(mechListMIC_in); } if (mechListMIC_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_out); free(mechListMIC_out); } return ret; } /* init_sec_context */ 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_init_sec_context( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { send_token_flag send_token = NO_TOKEN_SEND; OM_uint32 tmpmin, ret, negState; gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_cred_id_t spcred = NULL; spnego_gss_ctx_id_t spnego_ctx = NULL; dsyslog("Entering init_sec_context\n"); mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER; negState = REJECT; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context * function and examine the results. * 3. Process or generate MICs if necessary. * * The three steps share responsibility for determining when the * exchange is complete. If the selected mech completed in a previous * call and no MIC exchange is expected, then step 1 will decide. If * the selected mech completes in this call and no MIC exchange is * expected, then step 2 will decide. If a MIC exchange is expected, * then step 3 will decide. If an error occurs in any step, the * exchange will be aborted, possibly with an error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * send_token is used to indicate what type of token, if any, should be * generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (actual_mech != NULL) *actual_mech = GSS_C_NO_OID; /* Step 1: perform mechanism negotiation. */ spcred = (spnego_gss_cred_id_t)claimant_cred_handle; if (*context_handle == GSS_C_NO_CONTEXT) { ret = init_ctx_new(minor_status, spcred, context_handle, &send_token); if (ret != GSS_S_CONTINUE_NEEDED) { goto cleanup; } } else { ret = init_ctx_cont(minor_status, context_handle, input_token, &mechtok_in, &mechListMIC_in, &negState, &send_token); if (HARD_ERROR(ret)) { goto cleanup; } } /* Step 2: invoke the selected or optimistic mechanism's * gss_init_sec_context function, if it didn't complete previously. */ spnego_ctx = (spnego_gss_ctx_id_t)*context_handle; if (!spnego_ctx->mech_complete) { ret = init_ctx_call_init( minor_status, spnego_ctx, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, &mechtok_out, ret_flags, time_rec, &negState, &send_token); /* Give the mechanism a chance to force a mechlistMIC. */ if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx)) spnego_ctx->mic_reqd = 1; } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && spnego_ctx->mech_complete && (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mechListMIC_in, (mechtok_out.length != 0), spnego_ctx, &mechListMIC_out, &negState, &send_token); } cleanup: if (send_token == INIT_TOKEN_SEND) { if (make_spnego_tokenInit_msg(spnego_ctx, 0, mechListMIC_out, req_flags, &mechtok_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } else if (send_token != NO_TOKEN_SEND) { if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID, &mechtok_out, mechListMIC_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } gss_release_buffer(&tmpmin, &mechtok_out); if (ret == GSS_S_COMPLETE) { spnego_ctx->opened = 1; if (actual_mech != NULL) *actual_mech = spnego_ctx->actual_mech; if (ret_flags != NULL) *ret_flags = spnego_ctx->ctx_flags; } else if (ret != GSS_S_CONTINUE_NEEDED) { if (spnego_ctx != NULL) { gss_delete_sec_context(&tmpmin, &spnego_ctx->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&spnego_ctx); } *context_handle = GSS_C_NO_CONTEXT; } if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mechListMIC_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_in); free(mechListMIC_in); } if (mechListMIC_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_out); free(mechListMIC_out); } return ret; } /* init_sec_context */
166,660
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 process_line(URLContext *h, char *line, int line_count, int *new_location) { HTTPContext *s = h->priv_data; const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET"; char *tag, *p, *end, *method, *resource, *version; int ret; /* end of header */ if (line[0] == '\0') { s->end_header = 1; return 0; } p = line; if (line_count == 0) { if (s->is_connected_server) { method = p; while (*p && !av_isspace(*p)) p++; *(p++) = '\0'; av_log(h, AV_LOG_TRACE, "Received method: %s\n", method); if (s->method) { if (av_strcasecmp(s->method, method)) { av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n", s->method, method); return ff_http_averror(400, AVERROR(EIO)); } } else { av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method); if (av_strcasecmp(auto_method, method)) { av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match " "(%s autodetected %s received)\n", auto_method, method); return ff_http_averror(400, AVERROR(EIO)); } if (!(s->method = av_strdup(method))) return AVERROR(ENOMEM); } while (av_isspace(*p)) p++; resource = p; while (!av_isspace(*p)) p++; *(p++) = '\0'; av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource); if (!(s->resource = av_strdup(resource))) return AVERROR(ENOMEM); while (av_isspace(*p)) p++; version = p; while (*p && !av_isspace(*p)) p++; *p = '\0'; if (av_strncasecmp(version, "HTTP/", 5)) { av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n"); return ff_http_averror(400, AVERROR(EIO)); } av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version); } else { while (!av_isspace(*p) && *p != '\0') p++; while (av_isspace(*p)) p++; s->http_code = strtol(p, &end, 10); av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code); if ((ret = check_http_code(h, s->http_code, end)) < 0) return ret; } } else { while (*p != '\0' && *p != ':') p++; if (*p != ':') return 1; *p = '\0'; tag = line; p++; while (av_isspace(*p)) p++; if (!av_strcasecmp(tag, "Location")) { if ((ret = parse_location(s, p)) < 0) return ret; *new_location = 1; } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) { s->filesize = strtoll(p, NULL, 10); } else if (!av_strcasecmp(tag, "Content-Range")) { parse_content_range(h, p); } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) { h->is_streamed = 0; } else if (!av_strcasecmp(tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) { s->filesize = -1; s->chunksize = 0; } else if (!av_strcasecmp(tag, "WWW-Authenticate")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp(tag, "Authentication-Info")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) { ff_http_auth_handle_header(&s->proxy_auth_state, tag, p); } else if (!av_strcasecmp(tag, "Connection")) { if (!strcmp(p, "close")) s->willclose = 1; } else if (!av_strcasecmp(tag, "Server")) { if (!av_strcasecmp(p, "AkamaiGHost")) { s->is_akamai = 1; } else if (!av_strncasecmp(p, "MediaGateway", 12)) { s->is_mediagateway = 1; } } else if (!av_strcasecmp(tag, "Content-Type")) { av_free(s->mime_type); s->mime_type = av_strdup(p); } else if (!av_strcasecmp(tag, "Set-Cookie")) { if (parse_cookie(s, p, &s->cookie_dict)) av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p); } else if (!av_strcasecmp(tag, "Icy-MetaInt")) { s->icy_metaint = strtoll(p, NULL, 10); } else if (!av_strncasecmp(tag, "Icy-", 4)) { if ((ret = parse_icy(s, tag, p)) < 0) return ret; } else if (!av_strcasecmp(tag, "Content-Encoding")) { if ((ret = parse_content_encoding(h, p)) < 0) return ret; } } return 1; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119
static int process_line(URLContext *h, char *line, int line_count, int *new_location) { HTTPContext *s = h->priv_data; const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET"; char *tag, *p, *end, *method, *resource, *version; int ret; /* end of header */ if (line[0] == '\0') { s->end_header = 1; return 0; } p = line; if (line_count == 0) { if (s->is_connected_server) { method = p; while (*p && !av_isspace(*p)) p++; *(p++) = '\0'; av_log(h, AV_LOG_TRACE, "Received method: %s\n", method); if (s->method) { if (av_strcasecmp(s->method, method)) { av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n", s->method, method); return ff_http_averror(400, AVERROR(EIO)); } } else { av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method); if (av_strcasecmp(auto_method, method)) { av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match " "(%s autodetected %s received)\n", auto_method, method); return ff_http_averror(400, AVERROR(EIO)); } if (!(s->method = av_strdup(method))) return AVERROR(ENOMEM); } while (av_isspace(*p)) p++; resource = p; while (!av_isspace(*p)) p++; *(p++) = '\0'; av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource); if (!(s->resource = av_strdup(resource))) return AVERROR(ENOMEM); while (av_isspace(*p)) p++; version = p; while (*p && !av_isspace(*p)) p++; *p = '\0'; if (av_strncasecmp(version, "HTTP/", 5)) { av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n"); return ff_http_averror(400, AVERROR(EIO)); } av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version); } else { while (!av_isspace(*p) && *p != '\0') p++; while (av_isspace(*p)) p++; s->http_code = strtol(p, &end, 10); av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code); if ((ret = check_http_code(h, s->http_code, end)) < 0) return ret; } } else { while (*p != '\0' && *p != ':') p++; if (*p != ':') return 1; *p = '\0'; tag = line; p++; while (av_isspace(*p)) p++; if (!av_strcasecmp(tag, "Location")) { if ((ret = parse_location(s, p)) < 0) return ret; *new_location = 1; } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == UINT64_MAX) { s->filesize = strtoull(p, NULL, 10); } else if (!av_strcasecmp(tag, "Content-Range")) { parse_content_range(h, p); } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) { h->is_streamed = 0; } else if (!av_strcasecmp(tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) { s->filesize = UINT64_MAX; s->chunksize = 0; } else if (!av_strcasecmp(tag, "WWW-Authenticate")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp(tag, "Authentication-Info")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) { ff_http_auth_handle_header(&s->proxy_auth_state, tag, p); } else if (!av_strcasecmp(tag, "Connection")) { if (!strcmp(p, "close")) s->willclose = 1; } else if (!av_strcasecmp(tag, "Server")) { if (!av_strcasecmp(p, "AkamaiGHost")) { s->is_akamai = 1; } else if (!av_strncasecmp(p, "MediaGateway", 12)) { s->is_mediagateway = 1; } } else if (!av_strcasecmp(tag, "Content-Type")) { av_free(s->mime_type); s->mime_type = av_strdup(p); } else if (!av_strcasecmp(tag, "Set-Cookie")) { if (parse_cookie(s, p, &s->cookie_dict)) av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p); } else if (!av_strcasecmp(tag, "Icy-MetaInt")) { s->icy_metaint = strtoull(p, NULL, 10); } else if (!av_strncasecmp(tag, "Icy-", 4)) { if ((ret = parse_icy(s, tag, p)) < 0) return ret; } else if (!av_strcasecmp(tag, "Content-Encoding")) { if ((ret = parse_content_encoding(h, p)) < 0) return ret; } } return 1; }
168,504
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: expand_string_integer(uschar *string, BOOL isplus) { int_eximarith_t value; uschar *s = expand_string(string); uschar *msg = US"invalid integer \"%s\""; uschar *endptr; /* If expansion failed, expand_string_message will be set. */ if (s == NULL) return -1; /* On an overflow, strtol() returns LONG_MAX or LONG_MIN, and sets errno to ERANGE. When there isn't an overflow, errno is not changed, at least on some systems, so we set it zero ourselves. */ errno = 0; expand_string_message = NULL; /* Indicates no error */ /* Before Exim 4.64, strings consisting entirely of whitespace compared equal to 0. Unfortunately, people actually relied upon that, so preserve the behaviour explicitly. Stripping leading whitespace is a harmless noop change since strtol skips it anyway (provided that there is a number to find at all). */ if (isspace(*s)) { while (isspace(*s)) ++s; if (*s == '\0') { DEBUG(D_expand) debug_printf("treating blank string as number 0\n"); return 0; } } value = strtoll(CS s, CSS &endptr, 10); if (endptr == s) { msg = US"integer expected but \"%s\" found"; } else if (value < 0 && isplus) { msg = US"non-negative integer expected but \"%s\" found"; } else { switch (tolower(*endptr)) { default: break; case 'k': if (value > EXIM_ARITH_MAX/1024 || value < EXIM_ARITH_MIN/1024) errno = ERANGE; else value *= 1024; endptr++; break; case 'm': if (value > EXIM_ARITH_MAX/(1024*1024) || value < EXIM_ARITH_MIN/(1024*1024)) errno = ERANGE; else value *= 1024*1024; endptr++; break; case 'g': if (value > EXIM_ARITH_MAX/(1024*1024*1024) || value < EXIM_ARITH_MIN/(1024*1024*1024)) errno = ERANGE; else value *= 1024*1024*1024; endptr++; break; } if (errno == ERANGE) msg = US"absolute value of integer \"%s\" is too large (overflow)"; else { while (isspace(*endptr)) endptr++; if (*endptr == 0) return value; } } expand_string_message = string_sprintf(CS msg, s); return -2; } Commit Message: CWE ID: CWE-189
expand_string_integer(uschar *string, BOOL isplus) { return expanded_string_integer(expand_string(string), isplus); } /************************************************* * Interpret string as an integer * *************************************************/ /* Convert a string (that has already been expanded) into an integer. This function is used inside the expansion code. Arguments: s the string to be expanded isplus TRUE if a non-negative number is expected Returns: the integer value, or -1 if string is NULL (which implies an expansion error) -2 for an integer interpretation error expand_string_message is set NULL for an OK integer */ static int_eximarith_t expanded_string_integer(uschar *s, BOOL isplus) { int_eximarith_t value; uschar *msg = US"invalid integer \"%s\""; uschar *endptr; /* If expansion failed, expand_string_message will be set. */ if (s == NULL) return -1; /* On an overflow, strtol() returns LONG_MAX or LONG_MIN, and sets errno to ERANGE. When there isn't an overflow, errno is not changed, at least on some systems, so we set it zero ourselves. */ errno = 0; expand_string_message = NULL; /* Indicates no error */ /* Before Exim 4.64, strings consisting entirely of whitespace compared equal to 0. Unfortunately, people actually relied upon that, so preserve the behaviour explicitly. Stripping leading whitespace is a harmless noop change since strtol skips it anyway (provided that there is a number to find at all). */ if (isspace(*s)) { while (isspace(*s)) ++s; if (*s == '\0') { DEBUG(D_expand) debug_printf("treating blank string as number 0\n"); return 0; } } value = strtoll(CS s, CSS &endptr, 10); if (endptr == s) { msg = US"integer expected but \"%s\" found"; } else if (value < 0 && isplus) { msg = US"non-negative integer expected but \"%s\" found"; } else { switch (tolower(*endptr)) { default: break; case 'k': if (value > EXIM_ARITH_MAX/1024 || value < EXIM_ARITH_MIN/1024) errno = ERANGE; else value *= 1024; endptr++; break; case 'm': if (value > EXIM_ARITH_MAX/(1024*1024) || value < EXIM_ARITH_MIN/(1024*1024)) errno = ERANGE; else value *= 1024*1024; endptr++; break; case 'g': if (value > EXIM_ARITH_MAX/(1024*1024*1024) || value < EXIM_ARITH_MIN/(1024*1024*1024)) errno = ERANGE; else value *= 1024*1024*1024; endptr++; break; } if (errno == ERANGE) msg = US"absolute value of integer \"%s\" is too large (overflow)"; else { while (isspace(*endptr)) endptr++; if (*endptr == 0) return value; } } expand_string_message = string_sprintf(CS msg, s); return -2; }
165,191
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: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; } Commit Message: CWE ID: CWE-189
JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmallocn(h, line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; }
164,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: int main(int argc, char **argv) { const char *test_name = NULL; bool skip_sanity_suite = false; for (int i = 1; i < argc; ++i) { if (!strcmp("--help", argv[i])) { print_usage(argv[0]); return 0; } if (!strcmp("--insanity", argv[i])) { skip_sanity_suite = true; continue; } if (!is_valid(argv[i])) { printf("Error: invalid test name.\n"); print_usage(argv[0]); return -1; } if (test_name != NULL) { printf("Error: invalid arguments.\n"); print_usage(argv[0]); return -1; } test_name = argv[i]; } if (is_shell_running()) { printf("Run 'adb shell stop' before running %s.\n", argv[0]); return -1; } config_t *config = config_new(CONFIG_FILE_PATH); if (!config) { printf("Error: unable to open stack config file.\n"); print_usage(argv[0]); return -1; } for (const config_section_node_t *node = config_section_begin(config); node != config_section_end(config); node = config_section_next(node)) { const char *name = config_section_name(node); if (config_has_key(config, name, "LinkKey") && string_to_bdaddr(name, &bt_remote_bdaddr)) { break; } } config_free(config); if (bdaddr_is_empty(&bt_remote_bdaddr)) { printf("Error: unable to find paired device in config file.\n"); print_usage(argv[0]); return -1; } if (!hal_open(callbacks_get_adapter_struct())) { printf("Unable to open Bluetooth HAL.\n"); return 1; } if (!btsocket_init()) { printf("Unable to initialize Bluetooth sockets.\n"); return 2; } if (!pan_init()) { printf("Unable to initialize PAN.\n"); return 3; } if (!gatt_init()) { printf("Unable to initialize GATT.\n"); return 4; } watchdog_running = true; pthread_create(&watchdog_thread, NULL, watchdog_fn, NULL); static const char *DEFAULT = "\x1b[0m"; static const char *GREEN = "\x1b[0;32m"; static const char *RED = "\x1b[0;31m"; if (!isatty(fileno(stdout))) { DEFAULT = GREEN = RED = ""; } int pass = 0; int fail = 0; int case_num = 0; if (!skip_sanity_suite) { for (size_t i = 0; i < sanity_suite_size; ++i) { if (!test_name || !strcmp(test_name, sanity_suite[i].function_name)) { callbacks_init(); if (sanity_suite[i].function()) { printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, sanity_suite[i].function_name, GREEN, DEFAULT); ++pass; } else { printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, sanity_suite[i].function_name, RED, DEFAULT); ++fail; } callbacks_cleanup(); ++watchdog_id; } } } if (fail) { printf("\n%sSanity suite failed with %d errors.%s\n", RED, fail, DEFAULT); hal_close(); return 4; } for (size_t i = 0; i < test_suite_size; ++i) { if (!test_name || !strcmp(test_name, test_suite[i].function_name)) { callbacks_init(); CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); if (test_suite[i].function()) { printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, test_suite[i].function_name, GREEN, DEFAULT); ++pass; } else { printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, test_suite[i].function_name, RED, DEFAULT); ++fail; } CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed); callbacks_cleanup(); ++watchdog_id; } } printf("\n"); if (fail) { printf("%d/%d tests failed. See above for failed test cases.\n", fail, sanity_suite_size + test_suite_size); } else { printf("All tests passed!\n"); } watchdog_running = false; pthread_join(watchdog_thread, NULL); hal_close(); return 0; } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
int main(int argc, char **argv) { const char *test_name = NULL; bool skip_sanity_suite = false; for (int i = 1; i < argc; ++i) { if (!strcmp("--help", argv[i])) { print_usage(argv[0]); return 0; } if (!strcmp("--insanity", argv[i])) { skip_sanity_suite = true; continue; } if (!is_valid(argv[i])) { printf("Error: invalid test name.\n"); print_usage(argv[0]); return -1; } if (test_name != NULL) { printf("Error: invalid arguments.\n"); print_usage(argv[0]); return -1; } test_name = argv[i]; } if (is_shell_running()) { printf("Run 'adb shell stop' before running %s.\n", argv[0]); return -1; } config_t *config = config_new(CONFIG_FILE_PATH); if (!config) { printf("Error: unable to open stack config file.\n"); print_usage(argv[0]); return -1; } for (const config_section_node_t *node = config_section_begin(config); node != config_section_end(config); node = config_section_next(node)) { const char *name = config_section_name(node); if (config_has_key(config, name, "LinkKey") && string_to_bdaddr(name, &bt_remote_bdaddr)) { break; } } config_free(config); if (bdaddr_is_empty(&bt_remote_bdaddr)) { printf("Error: unable to find paired device in config file.\n"); print_usage(argv[0]); return -1; } if (!hal_open(callbacks_get_adapter_struct())) { printf("Unable to open Bluetooth HAL.\n"); return 1; } if (!btsocket_init()) { printf("Unable to initialize Bluetooth sockets.\n"); return 2; } if (!pan_init()) { printf("Unable to initialize PAN.\n"); return 3; } if (!gatt_init()) { printf("Unable to initialize GATT.\n"); return 4; } watchdog_running = true; pthread_create(&watchdog_thread, NULL, watchdog_fn, NULL); static const char *DEFAULT = "\x1b[0m"; static const char *GREEN = "\x1b[0;32m"; static const char *RED = "\x1b[0;31m"; if (!isatty(fileno(stdout))) { DEFAULT = GREEN = RED = ""; } int pass = 0; int fail = 0; int case_num = 0; if (!skip_sanity_suite) { for (size_t i = 0; i < sanity_suite_size; ++i) { if (!test_name || !strcmp(test_name, sanity_suite[i].function_name)) { callbacks_init(); if (sanity_suite[i].function()) { printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, sanity_suite[i].function_name, GREEN, DEFAULT); ++pass; } else { printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, sanity_suite[i].function_name, RED, DEFAULT); ++fail; } callbacks_cleanup(); ++watchdog_id; } } } if (fail) { printf("\n%sSanity suite failed with %d errors.%s\n", RED, fail, DEFAULT); hal_close(); return 4; } for (size_t i = 0; i < test_suite_size; ++i) { if (!test_name || !strcmp(test_name, test_suite[i].function_name)) { callbacks_init(); CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); if (test_suite[i].function()) { printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, test_suite[i].function_name, GREEN, DEFAULT); ++pass; } else { printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, test_suite[i].function_name, RED, DEFAULT); ++fail; } CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed); callbacks_cleanup(); ++watchdog_id; } } printf("\n"); if (fail) { printf("%d/%d tests failed. See above for failed test cases.\n", fail, sanity_suite_size + test_suite_size); } else { printf("All tests passed!\n"); } watchdog_running = false; pthread_join(watchdog_thread, NULL); hal_close(); return 0; }
173,557
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 GpuProcessHostUIShim::OnAcceleratedSurfaceRelease( const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) { RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; view->AcceleratedSurfaceRelease(params.identifier); } 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 GpuProcessHostUIShim::OnAcceleratedSurfaceRelease( const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) { RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; view->AcceleratedSurfaceRelease(); }
171,360
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: uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; } Commit Message: CWE ID: CWE-20
uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } if (session->smb2->should_sign) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; }
164,675
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 ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << "Failed to change keyboard layout to " << current_input_method_.keyboard_layout; } ObserverListBase<Observer>::Iterator it(observers_); Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); } 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
void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { void ChangeCurrentInputMethod(const input_method::InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << "Failed to change keyboard layout to " << current_input_method_.keyboard_layout; } ObserverListBase<InputMethodLibrary::Observer>::Iterator it(observers_); InputMethodLibrary::Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); }
170,478
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 exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC) { int de; int NumDirEntries; int NextDirOffset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength); #endif ImageInfo->sections_found |= FOUND_IFD0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) { return FALSE; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return TRUE; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size); #endif if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail ) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC); } return TRUE; } else { return FALSE; } } return TRUE; } Commit Message: CWE ID: CWE-119
static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC) { int de; int NumDirEntries; int NextDirOffset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength); #endif ImageInfo->sections_found |= FOUND_IFD0; if ((dir_start + 2) >= (offset_base+IFDlength)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size"); return FALSE; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) { return FALSE; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return TRUE; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ if ((dir_start+2+12*de + 4) >= (offset_base+IFDlength)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size"); return FALSE; } NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size); #endif if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail ) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC); } return TRUE; } else { return FALSE; } } return TRUE; }
165,033
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: swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; TIFFSwabArrayOfShort(wp, wc); horAcc16(tif, cp0, cc); } 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
swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; TIFFSwabArrayOfShort(wp, wc); return horAcc16(tif, cp0, cc); }
166,888
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: _crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { if ((*q++ = *key << 1)) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\0'; p = (u_char *) data->output + 9; } else { /* * "old"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); } Commit Message: CWE ID: CWE-310
_crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { *q++ = *key << 1; if (*key) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\0'; p = (u_char *) data->output + 9; } else { /* * "old"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); }
165,028
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 unregisterBlobURLTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().unregisterBlobURL(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 unregisterBlobURLTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->unregisterBlobURL(blobRegistryContext->url); }
170,691
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: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic, const char *s, charset_t src_charset, charset_t dst_charset) { size_t count = 0; #ifdef DEVELOPER switch (dst_charset) { case CH_DOS: case CH_UNIX: smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)"); default: break; } switch (src_charset) { case CH_UTF16LE: case CH_UTF16BE: smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)"); default: break; } #endif if (!s) { return 0; } while (*s && !(((uint8_t)*s) & 0x80)) { s++; count++; } if (!*s) { return count; } while (*s) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size); s += c_size; switch (dst_charset) { case CH_UTF16BE: case CH_UTF16MUNGED: if (c < 0x10000) { /* Unicode char fits into 16 bits. */ count += 1; } else { /* Double-width unicode char - 32 bits. */ count += 2; } break; case CH_UTF8: /* * this only checks ranges, and does not * check for invalid codepoints */ if (c < 0x80) { count += 1; } else if (c < 0x800) { count += 2; } else if (c < 0x10000) { count += 3; } else { count += 4; } break; default: /* * non-unicode encoding: * assume that each codepoint fits into * one unit in the destination encoding. */ count += 1; } } return count; } Commit Message: CWE ID: CWE-200
_PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic, const char *s, charset_t src_charset, charset_t dst_charset) { size_t count = 0; #ifdef DEVELOPER switch (dst_charset) { case CH_DOS: case CH_UNIX: smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)"); default: break; } switch (src_charset) { case CH_UTF16LE: case CH_UTF16BE: smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)"); default: break; } #endif if (!s) { return 0; } while (*s && !(((uint8_t)*s) & 0x80)) { s++; count++; } if (!*s) { return count; } while (*s) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(ic, s, strnlen(s, 5), src_charset, &c_size); s += c_size; switch (dst_charset) { case CH_UTF16BE: case CH_UTF16MUNGED: if (c < 0x10000) { /* Unicode char fits into 16 bits. */ count += 1; } else { /* Double-width unicode char - 32 bits. */ count += 2; } break; case CH_UTF8: /* * this only checks ranges, and does not * check for invalid codepoints */ if (c < 0x80) { count += 1; } else if (c < 0x800) { count += 2; } else if (c < 0x10000) { count += 3; } else { count += 4; } break; default: /* * non-unicode encoding: * assume that each codepoint fits into * one unit in the destination encoding. */ count += 1; } } return count; }
164,671
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 GDataCacheMetadataMap::Initialize( const std::vector<FilePath>& cache_paths) { AssertOnSequencedWorkerPool(); if (cache_paths.size() < GDataCache::NUM_CACHE_TYPES) { LOG(ERROR) << "Size of cache_paths is invalid."; return; } if (!GDataCache::CreateCacheDirectories(cache_paths)) return; if (!ChangeFilePermissions(cache_paths[GDataCache::CACHE_TYPE_PERSISTENT], S_IRWXU | S_IXGRP | S_IXOTH)) return; DVLOG(1) << "Scanning directories"; ResourceIdToFilePathMap persistent_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PERSISTENT, &cache_map_, &persistent_file_map); ResourceIdToFilePathMap tmp_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_TMP, &cache_map_, &tmp_file_map); ResourceIdToFilePathMap pinned_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PINNED, &cache_map_, &pinned_file_map); ResourceIdToFilePathMap outgoing_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_OUTGOING, &cache_map_, &outgoing_file_map); RemoveInvalidFilesFromPersistentDirectory(persistent_file_map, outgoing_file_map, &cache_map_); DVLOG(1) << "Directory scan finished"; } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void GDataCacheMetadataMap::Initialize( const std::vector<FilePath>& cache_paths) { AssertOnSequencedWorkerPool(); if (cache_paths.size() < GDataCache::NUM_CACHE_TYPES) { DLOG(ERROR) << "Size of cache_paths is invalid."; return; } if (!CreateCacheDirectories(cache_paths)) return; if (!ChangeFilePermissions(cache_paths[GDataCache::CACHE_TYPE_PERSISTENT], S_IRWXU | S_IXGRP | S_IXOTH)) return; DVLOG(1) << "Scanning directories"; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PERSISTENT, &cache_map_); ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_TMP, &cache_map_); // Then scan pinned and outgoing directories to update existing entries in // cache map, or create new ones for pinned symlinks to /dev/null which target // nothing. // Pinned and outgoing directories should be scanned after the persistent // directory as we'll add PINNED and DIRTY states respectively to the existing // files in the persistent directory per the contents of the pinned and // outgoing directories. ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PINNED, &cache_map_); ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_OUTGOING, &cache_map_); DVLOG(1) << "Directory scan finished"; }
170,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: static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1451 CWE ID: CWE-399
static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); }
169,729
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: Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; assert(p); delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pSeekHead; } 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
Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pTags; delete m_pSeekHead; }
173,870
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: file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len += 20) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; } Commit Message: PR/454: Fix memory corruption when the continuation level jumps by more than 20 in a single step. CWE ID: CWE-119
file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len = 20 + level) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; }
167,475
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 CreateOAuth2ServiceDelegate( signin::AccountConsistencyMethod account_consistency) { oauth2_service_delegate_.reset(new MutableProfileOAuth2TokenServiceDelegate( client_.get(), &signin_error_controller_, &account_tracker_service_, token_web_data_, account_consistency, revoke_all_tokens_on_load_, true /* can_revoke_credantials */)); base::RunLoop().RunUntilIdle(); oauth2_service_delegate_->AddObserver(this); } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20
void CreateOAuth2ServiceDelegate( std::unique_ptr<MutableProfileOAuth2TokenServiceDelegate> CreateOAuth2ServiceDelegate( signin::AccountConsistencyMethod account_consistency) { return std::make_unique<MutableProfileOAuth2TokenServiceDelegate>( client_.get(), &signin_error_controller_, &account_tracker_service_, token_web_data_, account_consistency, revoke_all_tokens_on_load_, true /* can_revoke_credantials */); // Make sure delegate has a chance to load itself before continuing. base::RunLoop().RunUntilIdle(); } void InitializeOAuth2ServiceDelegate( signin::AccountConsistencyMethod account_consistency) { oauth2_service_delegate_ = CreateOAuth2ServiceDelegate(account_consistency); oauth2_service_delegate_->AddObserver(this); }
172,568
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: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort) return res; if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, BOOLEAN verifyLength, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength, verifyLength); if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort) return res; if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; }
170,143
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 DevToolsAgentHostImpl::AttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; InnerAttachClient(client); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void DevToolsAgentHostImpl::AttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; InnerAttachClient(client, false /* restricted */); } bool DevToolsAgentHostImpl::AttachRestrictedClient( DevToolsAgentHostClient* client) { if (SessionByClient(client)) return false; return InnerAttachClient(client, true /* restricted */); }
173,242
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 mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { int ret; mbedtls_hmac_drbg_context rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len ); ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, &rng_ctx ); cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted CWE ID: CWE-200
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, static int ecdsa_sign_det_internal( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { int ret; mbedtls_hmac_drbg_context rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; /* Variables for deterministic blinding fallback */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); mbedtls_hmac_drbg_init( &rng_ctx_blind ); /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len ); if( f_rng_blind != NULL ) ret = ecdsa_sign_internal( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, &rng_ctx, f_rng_blind, p_rng_blind ); else { /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ mbedtls_hmac_drbg_seed_buf( &rng_ctx_blind, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( &rng_ctx_blind, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) goto cleanup; /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_internal( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, &rng_ctx, mbedtls_hmac_drbg_random, &rng_ctx_blind ); } cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_hmac_drbg_free( &rng_ctx_blind ); mbedtls_mpi_free( &h ); return( ret ); }
170,181
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: gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gint base64_len) { GstBuffer *img; guchar *img_data; gsize img_len; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; img_data = g_try_malloc0 (base64_len * 3 / 4); if (img_data == NULL) goto alloc_failed; img_len = g_base64_decode_step (img_data_base64, base64_len, img_data, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (img_data, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); g_free (img_data); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } alloc_failed: { GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag"); return; } decode_failed: { GST_WARNING ("Couldn't decode bas64 image data from COVERART tag"); g_free (img_data); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); g_free (img_data); return; } } Commit Message: CWE ID: CWE-189
gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gst_vorbis_tag_add_coverart (GstTagList * tags, gchar * img_data_base64, gint base64_len) { GstBuffer *img; gsize img_len; guchar *out; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; /* img_data_base64 points to a temporary copy of the base64 encoded data, so * it's safe to do inpace decoding here * TODO: glib 2.20 and later provides g_base64_decode_inplace, so change this * to use glib's API instead once it's in wider use: * http://bugzilla.gnome.org/show_bug.cgi?id=564728 * http://svn.gnome.org/viewvc/glib?view=revision&revision=7807 */ out = (guchar *) img_data_base64; img_len = g_base64_decode_step (img_data_base64, base64_len, out, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (out, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } decode_failed: { GST_WARNING ("Couldn't decode base64 image data from COVERART tag"); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); return; } }
164,754
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 fx_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { struct effect_s *effect = (struct effect_s *)self; if (effect == NULL) return -EINVAL; switch (cmdCode) { case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)) return -EINVAL; *(int *)pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: { if (pCmdData == NULL|| cmdSize != sizeof(effect_config_t)|| pReplyData == NULL|| *replySize != sizeof(int)) { ALOGV("fx_command() EFFECT_CMD_SET_CONFIG invalid args"); return -EINVAL; } *(int *)pReplyData = session_set_config(effect->session, (effect_config_t *)pCmdData); if (*(int *)pReplyData != 0) break; if (effect->state != EFFECT_STATE_ACTIVE) *(int *)pReplyData = effect_set_state(effect, EFFECT_STATE_CONFIG); } break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("fx_command() EFFECT_CMD_GET_CONFIG invalid args"); return -EINVAL; } session_get_config(effect->session, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: break; case EFFECT_CMD_GET_PARAM: { if (pCmdData == NULL || cmdSize < (int)sizeof(effect_param_t) || pReplyData == NULL || *replySize < (int)sizeof(effect_param_t)) { ALOGV("fx_command() EFFECT_CMD_GET_PARAM invalid args"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; p->status = -ENOSYS; } break; case EFFECT_CMD_SET_PARAM: { if (pCmdData == NULL|| cmdSize < (int)sizeof(effect_param_t) || pReplyData == NULL || *replySize != sizeof(int32_t)) { ALOGV("fx_command() EFFECT_CMD_SET_PARAM invalid args"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)) { ALOGV("fx_command() EFFECT_CMD_SET_PARAM invalid param format"); return -EINVAL; } *(int *)pReplyData = -ENOSYS; } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("fx_command() EFFECT_CMD_ENABLE invalid args"); return -EINVAL; } *(int *)pReplyData = effect_set_state(effect, EFFECT_STATE_ACTIVE); break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("fx_command() EFFECT_CMD_DISABLE invalid args"); return -EINVAL; } *(int *)pReplyData = effect_set_state(effect, EFFECT_STATE_CONFIG); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_INPUT_DEVICE: case EFFECT_CMD_SET_VOLUME: case EFFECT_CMD_SET_AUDIO_MODE: if (pCmdData == NULL || cmdSize != sizeof(uint32_t)) { ALOGV("fx_command() %s invalid args", cmdCode == EFFECT_CMD_SET_DEVICE ? "EFFECT_CMD_SET_DEVICE" : cmdCode == EFFECT_CMD_SET_INPUT_DEVICE ? "EFFECT_CMD_SET_INPUT_DEVICE" : cmdCode == EFFECT_CMD_SET_VOLUME ? "EFFECT_CMD_SET_VOLUME" : cmdCode == EFFECT_CMD_SET_AUDIO_MODE ? "EFFECT_CMD_SET_AUDIO_MODE" : ""); return -EINVAL; } ALOGV("fx_command() %s value %08x", cmdCode == EFFECT_CMD_SET_DEVICE ? "EFFECT_CMD_SET_DEVICE" : cmdCode == EFFECT_CMD_SET_INPUT_DEVICE ? "EFFECT_CMD_SET_INPUT_DEVICE" : cmdCode == EFFECT_CMD_SET_VOLUME ? "EFFECT_CMD_SET_VOLUME" : cmdCode == EFFECT_CMD_SET_AUDIO_MODE ? "EFFECT_CMD_SET_AUDIO_MODE": "", *(int *)pCmdData); break; default: return -EINVAL; } return 0; } Commit Message: DO NOT MERGE Fix AudioEffect reply overflow Bug: 28173666 Change-Id: I055af37a721b20c5da0f1ec4b02f630dcd5aee02 CWE ID: CWE-119
static int fx_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { struct effect_s *effect = (struct effect_s *)self; if (effect == NULL) return -EINVAL; switch (cmdCode) { case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)) return -EINVAL; *(int *)pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: { if (pCmdData == NULL|| cmdSize != sizeof(effect_config_t)|| pReplyData == NULL|| *replySize != sizeof(int)) { ALOGV("fx_command() EFFECT_CMD_SET_CONFIG invalid args"); return -EINVAL; } *(int *)pReplyData = session_set_config(effect->session, (effect_config_t *)pCmdData); if (*(int *)pReplyData != 0) break; if (effect->state != EFFECT_STATE_ACTIVE) *(int *)pReplyData = effect_set_state(effect, EFFECT_STATE_CONFIG); } break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("fx_command() EFFECT_CMD_GET_CONFIG invalid args"); return -EINVAL; } session_get_config(effect->session, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: break; case EFFECT_CMD_GET_PARAM: { if (pCmdData == NULL || cmdSize < (int)sizeof(effect_param_t) || pReplyData == NULL || *replySize < (int)sizeof(effect_param_t) || // constrain memcpy below ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t)) { ALOGV("fx_command() EFFECT_CMD_GET_PARAM invalid args"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; p->status = -ENOSYS; } break; case EFFECT_CMD_SET_PARAM: { if (pCmdData == NULL|| cmdSize < (int)sizeof(effect_param_t) || pReplyData == NULL || *replySize != sizeof(int32_t)) { ALOGV("fx_command() EFFECT_CMD_SET_PARAM invalid args"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)) { ALOGV("fx_command() EFFECT_CMD_SET_PARAM invalid param format"); return -EINVAL; } *(int *)pReplyData = -ENOSYS; } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("fx_command() EFFECT_CMD_ENABLE invalid args"); return -EINVAL; } *(int *)pReplyData = effect_set_state(effect, EFFECT_STATE_ACTIVE); break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("fx_command() EFFECT_CMD_DISABLE invalid args"); return -EINVAL; } *(int *)pReplyData = effect_set_state(effect, EFFECT_STATE_CONFIG); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_INPUT_DEVICE: case EFFECT_CMD_SET_VOLUME: case EFFECT_CMD_SET_AUDIO_MODE: if (pCmdData == NULL || cmdSize != sizeof(uint32_t)) { ALOGV("fx_command() %s invalid args", cmdCode == EFFECT_CMD_SET_DEVICE ? "EFFECT_CMD_SET_DEVICE" : cmdCode == EFFECT_CMD_SET_INPUT_DEVICE ? "EFFECT_CMD_SET_INPUT_DEVICE" : cmdCode == EFFECT_CMD_SET_VOLUME ? "EFFECT_CMD_SET_VOLUME" : cmdCode == EFFECT_CMD_SET_AUDIO_MODE ? "EFFECT_CMD_SET_AUDIO_MODE" : ""); return -EINVAL; } ALOGV("fx_command() %s value %08x", cmdCode == EFFECT_CMD_SET_DEVICE ? "EFFECT_CMD_SET_DEVICE" : cmdCode == EFFECT_CMD_SET_INPUT_DEVICE ? "EFFECT_CMD_SET_INPUT_DEVICE" : cmdCode == EFFECT_CMD_SET_VOLUME ? "EFFECT_CMD_SET_VOLUME" : cmdCode == EFFECT_CMD_SET_AUDIO_MODE ? "EFFECT_CMD_SET_AUDIO_MODE": "", *(int *)pCmdData); break; default: return -EINVAL; } return 0; }
173,756
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 fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */ { struct fpm_worker_pool_config_s *c = wp->config; /* uninitialized */ wp->socket_uid = -1; wp->socket_gid = -1; wp->socket_mode = 0666; if (!c) { return 0; } if (c->listen_owner && *c->listen_owner) { struct passwd *pwd; pwd = getpwnam(c->listen_owner); if (!pwd) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get uid for user '%s'", wp->config->name, c->listen_owner); return -1; } wp->socket_uid = pwd->pw_uid; wp->socket_gid = pwd->pw_gid; } if (c->listen_group && *c->listen_group) { struct group *grp; grp = getgrnam(c->listen_group); if (!grp) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get gid for group '%s'", wp->config->name, c->listen_group); return -1; } wp->socket_gid = grp->gr_gid; } if (c->listen_mode && *c->listen_mode) { wp->socket_mode = strtoul(c->listen_mode, 0, 8); } return 0; } /* }}} */ Commit Message: Fix bug #67060: use default mode of 660 CWE ID: CWE-264
int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */ { struct fpm_worker_pool_config_s *c = wp->config; /* uninitialized */ wp->socket_uid = -1; wp->socket_gid = -1; wp->socket_mode = 0660; if (!c) { return 0; } if (c->listen_owner && *c->listen_owner) { struct passwd *pwd; pwd = getpwnam(c->listen_owner); if (!pwd) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get uid for user '%s'", wp->config->name, c->listen_owner); return -1; } wp->socket_uid = pwd->pw_uid; wp->socket_gid = pwd->pw_gid; } if (c->listen_group && *c->listen_group) { struct group *grp; grp = getgrnam(c->listen_group); if (!grp) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get gid for group '%s'", wp->config->name, c->listen_group); return -1; } wp->socket_gid = grp->gr_gid; } if (c->listen_mode && *c->listen_mode) { wp->socket_mode = strtoul(c->listen_mode, 0, 8); } return 0; } /* }}} */
166,457
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: status_t CameraClient::dump(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264
status_t CameraClient::dump(int fd, const Vector<String16>& args) { return BasicClient::dump(fd, args); } status_t CameraClient::dumpClient(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); }
173,938
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 inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
int inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); rcu_read_lock(); final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; }
167,328
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 do_adjtimex(struct timex *txc) { long mtemp, save_adjust, rem; s64 freq_adj; int result; /* In order to modify anything, you gotta be super-user! */ if (txc->modes && !capable(CAP_SYS_TIME)) return -EPERM; /* Now we validate the data before disabling interrupts */ if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT) { /* singleshot must not be used with any other mode bits */ if (txc->modes != ADJ_OFFSET_SINGLESHOT && txc->modes != ADJ_OFFSET_SS_READ) return -EINVAL; } if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET)) /* adjustment Offset limited to +- .512 seconds */ if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE ) return -EINVAL; /* if the quartz is off by more than 10% something is VERY wrong ! */ if (txc->modes & ADJ_TICK) if (txc->tick < 900000/USER_HZ || txc->tick > 1100000/USER_HZ) return -EINVAL; write_seqlock_irq(&xtime_lock); result = time_state; /* mostly `TIME_OK' */ /* Save for later - semantics of adjtime is to return old value */ save_adjust = time_adjust; #if 0 /* STA_CLOCKERR is never set yet */ time_status &= ~STA_CLOCKERR; /* reset STA_CLOCKERR */ #endif /* If there are input parameters, then process them */ if (txc->modes) { if (txc->modes & ADJ_STATUS) /* only set allowed bits */ time_status = (txc->status & ~STA_RONLY) | (time_status & STA_RONLY); if (txc->modes & ADJ_FREQUENCY) { /* p. 22 */ if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) { result = -EINVAL; goto leave; } time_freq = ((s64)txc->freq * NSEC_PER_USEC) >> (SHIFT_USEC - SHIFT_NSEC); } if (txc->modes & ADJ_MAXERROR) { if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) { result = -EINVAL; goto leave; } time_maxerror = txc->maxerror; } if (txc->modes & ADJ_ESTERROR) { if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) { result = -EINVAL; goto leave; } time_esterror = txc->esterror; } if (txc->modes & ADJ_TIMECONST) { /* p. 24 */ if (txc->constant < 0) { /* NTP v4 uses values > 6 */ result = -EINVAL; goto leave; } time_constant = min(txc->constant + 4, (long)MAXTC); } if (txc->modes & ADJ_OFFSET) { /* values checked earlier */ if (txc->modes == ADJ_OFFSET_SINGLESHOT) { /* adjtime() is independent from ntp_adjtime() */ time_adjust = txc->offset; } else if (time_status & STA_PLL) { time_offset = txc->offset * NSEC_PER_USEC; /* * Scale the phase adjustment and * clamp to the operating range. */ time_offset = min(time_offset, (s64)MAXPHASE * NSEC_PER_USEC); time_offset = max(time_offset, (s64)-MAXPHASE * NSEC_PER_USEC); /* * Select whether the frequency is to be controlled * and in which mode (PLL or FLL). Clamp to the operating * range. Ugly multiply/divide should be replaced someday. */ if (time_status & STA_FREQHOLD || time_reftime == 0) time_reftime = xtime.tv_sec; mtemp = xtime.tv_sec - time_reftime; time_reftime = xtime.tv_sec; freq_adj = time_offset * mtemp; freq_adj = shift_right(freq_adj, time_constant * 2 + (SHIFT_PLL + 2) * 2 - SHIFT_NSEC); if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) freq_adj += div_s64(time_offset << (SHIFT_NSEC - SHIFT_FLL), mtemp); freq_adj += time_freq; freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC); time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC); time_offset = div_long_long_rem_signed(time_offset, NTP_INTERVAL_FREQ, &rem); time_offset <<= SHIFT_UPDATE; } /* STA_PLL */ } /* txc->modes & ADJ_OFFSET */ if (txc->modes & ADJ_TICK) tick_usec = txc->tick; if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET)) ntp_update_frequency(); } /* txc->modes */ leave: if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0) result = TIME_ERROR; if ((txc->modes == ADJ_OFFSET_SINGLESHOT) || (txc->modes == ADJ_OFFSET_SS_READ)) txc->offset = save_adjust; else txc->offset = ((long)shift_right(time_offset, SHIFT_UPDATE)) * NTP_INTERVAL_FREQ / 1000; txc->freq = (time_freq / NSEC_PER_USEC) << (SHIFT_USEC - SHIFT_NSEC); txc->maxerror = time_maxerror; txc->esterror = time_esterror; txc->status = time_status; txc->constant = time_constant; txc->precision = 1; txc->tolerance = MAXFREQ; txc->tick = tick_usec; /* PPS is not implemented, so these are zero */ txc->ppsfreq = 0; txc->jitter = 0; txc->shift = 0; txc->stabil = 0; txc->jitcnt = 0; txc->calcnt = 0; txc->errcnt = 0; txc->stbcnt = 0; write_sequnlock_irq(&xtime_lock); do_gettimeofday(&txc->time); notify_cmos_timer(); return(result); } 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
int do_adjtimex(struct timex *txc) { long mtemp, save_adjust; s64 freq_adj; int result; /* In order to modify anything, you gotta be super-user! */ if (txc->modes && !capable(CAP_SYS_TIME)) return -EPERM; /* Now we validate the data before disabling interrupts */ if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT) { /* singleshot must not be used with any other mode bits */ if (txc->modes != ADJ_OFFSET_SINGLESHOT && txc->modes != ADJ_OFFSET_SS_READ) return -EINVAL; } if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET)) /* adjustment Offset limited to +- .512 seconds */ if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE ) return -EINVAL; /* if the quartz is off by more than 10% something is VERY wrong ! */ if (txc->modes & ADJ_TICK) if (txc->tick < 900000/USER_HZ || txc->tick > 1100000/USER_HZ) return -EINVAL; write_seqlock_irq(&xtime_lock); result = time_state; /* mostly `TIME_OK' */ /* Save for later - semantics of adjtime is to return old value */ save_adjust = time_adjust; #if 0 /* STA_CLOCKERR is never set yet */ time_status &= ~STA_CLOCKERR; /* reset STA_CLOCKERR */ #endif /* If there are input parameters, then process them */ if (txc->modes) { if (txc->modes & ADJ_STATUS) /* only set allowed bits */ time_status = (txc->status & ~STA_RONLY) | (time_status & STA_RONLY); if (txc->modes & ADJ_FREQUENCY) { /* p. 22 */ if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) { result = -EINVAL; goto leave; } time_freq = ((s64)txc->freq * NSEC_PER_USEC) >> (SHIFT_USEC - SHIFT_NSEC); } if (txc->modes & ADJ_MAXERROR) { if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) { result = -EINVAL; goto leave; } time_maxerror = txc->maxerror; } if (txc->modes & ADJ_ESTERROR) { if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) { result = -EINVAL; goto leave; } time_esterror = txc->esterror; } if (txc->modes & ADJ_TIMECONST) { /* p. 24 */ if (txc->constant < 0) { /* NTP v4 uses values > 6 */ result = -EINVAL; goto leave; } time_constant = min(txc->constant + 4, (long)MAXTC); } if (txc->modes & ADJ_OFFSET) { /* values checked earlier */ if (txc->modes == ADJ_OFFSET_SINGLESHOT) { /* adjtime() is independent from ntp_adjtime() */ time_adjust = txc->offset; } else if (time_status & STA_PLL) { time_offset = txc->offset * NSEC_PER_USEC; /* * Scale the phase adjustment and * clamp to the operating range. */ time_offset = min(time_offset, (s64)MAXPHASE * NSEC_PER_USEC); time_offset = max(time_offset, (s64)-MAXPHASE * NSEC_PER_USEC); /* * Select whether the frequency is to be controlled * and in which mode (PLL or FLL). Clamp to the operating * range. Ugly multiply/divide should be replaced someday. */ if (time_status & STA_FREQHOLD || time_reftime == 0) time_reftime = xtime.tv_sec; mtemp = xtime.tv_sec - time_reftime; time_reftime = xtime.tv_sec; freq_adj = time_offset * mtemp; freq_adj = shift_right(freq_adj, time_constant * 2 + (SHIFT_PLL + 2) * 2 - SHIFT_NSEC); if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) freq_adj += div_s64(time_offset << (SHIFT_NSEC - SHIFT_FLL), mtemp); freq_adj += time_freq; freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC); time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC); time_offset = div_s64(time_offset, NTP_INTERVAL_FREQ); time_offset <<= SHIFT_UPDATE; } /* STA_PLL */ } /* txc->modes & ADJ_OFFSET */ if (txc->modes & ADJ_TICK) tick_usec = txc->tick; if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET)) ntp_update_frequency(); } /* txc->modes */ leave: if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0) result = TIME_ERROR; if ((txc->modes == ADJ_OFFSET_SINGLESHOT) || (txc->modes == ADJ_OFFSET_SS_READ)) txc->offset = save_adjust; else txc->offset = ((long)shift_right(time_offset, SHIFT_UPDATE)) * NTP_INTERVAL_FREQ / 1000; txc->freq = (time_freq / NSEC_PER_USEC) << (SHIFT_USEC - SHIFT_NSEC); txc->maxerror = time_maxerror; txc->esterror = time_esterror; txc->status = time_status; txc->constant = time_constant; txc->precision = 1; txc->tolerance = MAXFREQ; txc->tick = tick_usec; /* PPS is not implemented, so these are zero */ txc->ppsfreq = 0; txc->jitter = 0; txc->shift = 0; txc->stabil = 0; txc->jitcnt = 0; txc->calcnt = 0; txc->errcnt = 0; txc->stbcnt = 0; write_sequnlock_irq(&xtime_lock); do_gettimeofday(&txc->time); notify_cmos_timer(); return(result); }
165,757
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(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,095
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 OnDidAddMessageToConsole(int32_t, const base::string16& message, int32_t, const base::string16&) { callback_.Run(message); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void OnDidAddMessageToConsole(int32_t,
172,490
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: string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else if (type_ == INLINE_INSTALL_PROMPT) { return l10n_util::GetStringFUTF16( kTitleIds[type_], l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } }
170,981
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 dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size - 1) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; } Commit Message: fix #6857 CWE ID: CWE-125
static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; }
168,341
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 Process_ipfix_template_add(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { input_translation_t *translation_table; ipfix_template_record_t *ipfix_template_record; ipfix_template_elements_std_t *NextElement; int i; while ( size_left ) { uint32_t table_id, count, size_required; uint32_t num_extensions = 0; if ( size_left && size_left < 4 ) { LogError("Process_ipfix [%u] Template size error at %s line %u" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; table_id = ntohs(ipfix_template_record->TemplateID); count = ntohs(ipfix_template_record->FieldCount); dbg_printf("\n[%u] Template ID: %u\n", exporter->info.id, table_id); dbg_printf("FieldCount: %u buffersize: %u\n", count, size_left); memset((void *)cache.common_extensions, 0, (Max_num_extensions+1)*sizeof(uint32_t)); memset((void *)cache.lookup_info, 0, 65536 * sizeof(struct element_param_s)); for (i=1; ipfix_element_map[i].id != 0; i++ ) { uint32_t Type = ipfix_element_map[i].id; if ( ipfix_element_map[i].id == ipfix_element_map[i-1].id ) continue; cache.lookup_info[Type].index = i; } cache.input_order = calloc(count, sizeof(struct order_s)); if ( !cache.input_order ) { LogError("Process_ipfix: Panic! malloc(): %s line %d: %s", __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } cache.input_count = count; size_required = 4*count; if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } NextElement = (ipfix_template_elements_std_t *)ipfix_template_record->elements; for ( i=0; i<count; i++ ) { uint16_t Type, Length; uint32_t ext_id; int Enterprise; Type = ntohs(NextElement->Type); Length = ntohs(NextElement->Length); Enterprise = Type & 0x8000 ? 1 : 0; Type = Type & 0x7FFF; ext_id = MapElement(Type, Length, i); if ( ext_id && extension_descriptor[ext_id].enabled ) { if ( cache.common_extensions[ext_id] == 0 ) { cache.common_extensions[ext_id] = 1; num_extensions++; } } if ( Enterprise ) { ipfix_template_elements_e_t *e = (ipfix_template_elements_e_t *)NextElement; size_required += 4; // ad 4 for enterprise value if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } if ( ntohl(e->EnterpriseNumber) == IPFIX_ReverseInformationElement ) { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u Reverse Information Element: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } else { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u EnterpriseNumber: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } e++; NextElement = (ipfix_template_elements_std_t *)e; } else { dbg_printf(" [%i] Enterprise: 0, Type: %u, Length %u\n", i, Type, Length); NextElement++; } } dbg_printf("Processed: %u\n", size_required); if ( compact_input_order() ) { if ( extension_descriptor[EX_ROUTER_IP_v4].enabled ) { if ( cache.common_extensions[EX_ROUTER_IP_v4] == 0 ) { cache.common_extensions[EX_ROUTER_IP_v4] = 1; num_extensions++; } dbg_printf("Add sending router IP address (%s) => Extension: %u\n", fs->sa_family == PF_INET6 ? "ipv6" : "ipv4", EX_ROUTER_IP_v4); } extension_descriptor[EX_ROUTER_ID].enabled = 0; /* if ( extension_descriptor[EX_ROUTER_ID].enabled ) { if ( cache.common_extensions[EX_ROUTER_ID] == 0 ) { cache.common_extensions[EX_ROUTER_ID] = 1; num_extensions++; } dbg_printf("Force add router ID (engine type/ID), Extension: %u\n", EX_ROUTER_ID); } */ if ( extension_descriptor[EX_RECEIVED].enabled ) { if ( cache.common_extensions[EX_RECEIVED] == 0 ) { cache.common_extensions[EX_RECEIVED] = 1; num_extensions++; } dbg_printf("Force add packet received time, Extension: %u\n", EX_RECEIVED); } #ifdef DEVEL { int i; for (i=4; extension_descriptor[i].id; i++ ) { if ( cache.common_extensions[i] ) { printf("Enabled extension: %i\n", i); } } } #endif translation_table = setup_translation_table(exporter, table_id); if (translation_table->extension_map_changed ) { dbg_printf("Translation Table changed! Add extension map ID: %i\n", translation_table->extension_info.map->map_id); AddExtensionMap(fs, translation_table->extension_info.map); translation_table->extension_map_changed = 0; dbg_printf("Translation Table added! map ID: %i\n", translation_table->extension_info.map->map_id); } if ( !reorder_sequencer(translation_table) ) { LogError("Process_ipfix: [%u] Failed to reorder sequencer. Remove table id: %u", exporter->info.id, table_id); remove_translation_table(fs, exporter, table_id); } } else { dbg_printf("Template does not contain any common fields - skip\n"); } size_left -= size_required; DataPtr = DataPtr + size_required+4; // +4 for header if ( size_left < 4 ) { dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } free(cache.input_order); cache.input_order = NULL; } } // End of Process_ipfix_template_add Commit Message: Fix potential unsigned integer underflow CWE ID: CWE-190
static void Process_ipfix_template_add(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { input_translation_t *translation_table; ipfix_template_record_t *ipfix_template_record; ipfix_template_elements_std_t *NextElement; int i; while ( size_left ) { uint32_t table_id, count, size_required; uint32_t num_extensions = 0; if ( size_left < 4 ) { LogError("Process_ipfix [%u] Template size error at %s line %u" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; table_id = ntohs(ipfix_template_record->TemplateID); count = ntohs(ipfix_template_record->FieldCount); dbg_printf("\n[%u] Template ID: %u\n", exporter->info.id, table_id); dbg_printf("FieldCount: %u buffersize: %u\n", count, size_left); memset((void *)cache.common_extensions, 0, (Max_num_extensions+1)*sizeof(uint32_t)); memset((void *)cache.lookup_info, 0, 65536 * sizeof(struct element_param_s)); for (i=1; ipfix_element_map[i].id != 0; i++ ) { uint32_t Type = ipfix_element_map[i].id; if ( ipfix_element_map[i].id == ipfix_element_map[i-1].id ) continue; cache.lookup_info[Type].index = i; } cache.input_order = calloc(count, sizeof(struct order_s)); if ( !cache.input_order ) { LogError("Process_ipfix: Panic! malloc(): %s line %d: %s", __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } cache.input_count = count; size_required = 4*count; if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } NextElement = (ipfix_template_elements_std_t *)ipfix_template_record->elements; for ( i=0; i<count; i++ ) { uint16_t Type, Length; uint32_t ext_id; int Enterprise; Type = ntohs(NextElement->Type); Length = ntohs(NextElement->Length); Enterprise = Type & 0x8000 ? 1 : 0; Type = Type & 0x7FFF; ext_id = MapElement(Type, Length, i); if ( ext_id && extension_descriptor[ext_id].enabled ) { if ( cache.common_extensions[ext_id] == 0 ) { cache.common_extensions[ext_id] = 1; num_extensions++; } } if ( Enterprise ) { ipfix_template_elements_e_t *e = (ipfix_template_elements_e_t *)NextElement; size_required += 4; // ad 4 for enterprise value if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } if ( ntohl(e->EnterpriseNumber) == IPFIX_ReverseInformationElement ) { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u Reverse Information Element: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } else { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u EnterpriseNumber: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } e++; NextElement = (ipfix_template_elements_std_t *)e; } else { dbg_printf(" [%i] Enterprise: 0, Type: %u, Length %u\n", i, Type, Length); NextElement++; } } dbg_printf("Processed: %u\n", size_required); if ( compact_input_order() ) { if ( extension_descriptor[EX_ROUTER_IP_v4].enabled ) { if ( cache.common_extensions[EX_ROUTER_IP_v4] == 0 ) { cache.common_extensions[EX_ROUTER_IP_v4] = 1; num_extensions++; } dbg_printf("Add sending router IP address (%s) => Extension: %u\n", fs->sa_family == PF_INET6 ? "ipv6" : "ipv4", EX_ROUTER_IP_v4); } extension_descriptor[EX_ROUTER_ID].enabled = 0; /* if ( extension_descriptor[EX_ROUTER_ID].enabled ) { if ( cache.common_extensions[EX_ROUTER_ID] == 0 ) { cache.common_extensions[EX_ROUTER_ID] = 1; num_extensions++; } dbg_printf("Force add router ID (engine type/ID), Extension: %u\n", EX_ROUTER_ID); } */ if ( extension_descriptor[EX_RECEIVED].enabled ) { if ( cache.common_extensions[EX_RECEIVED] == 0 ) { cache.common_extensions[EX_RECEIVED] = 1; num_extensions++; } dbg_printf("Force add packet received time, Extension: %u\n", EX_RECEIVED); } #ifdef DEVEL { int i; for (i=4; extension_descriptor[i].id; i++ ) { if ( cache.common_extensions[i] ) { printf("Enabled extension: %i\n", i); } } } #endif translation_table = setup_translation_table(exporter, table_id); if (translation_table->extension_map_changed ) { dbg_printf("Translation Table changed! Add extension map ID: %i\n", translation_table->extension_info.map->map_id); AddExtensionMap(fs, translation_table->extension_info.map); translation_table->extension_map_changed = 0; dbg_printf("Translation Table added! map ID: %i\n", translation_table->extension_info.map->map_id); } if ( !reorder_sequencer(translation_table) ) { LogError("Process_ipfix: [%u] Failed to reorder sequencer. Remove table id: %u", exporter->info.id, table_id); remove_translation_table(fs, exporter, table_id); } } else { dbg_printf("Template does not contain any common fields - skip\n"); } size_left -= size_required; DataPtr = DataPtr + size_required+4; // +4 for header if ( size_left < 4 ) { dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } free(cache.input_order); cache.input_order = NULL; } } // End of Process_ipfix_template_add
169,582
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 ext4_ext_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; ssize_t ret; size_t count = iov_length(iov, nr_segs); loff_t final_size = offset + count; if (rw == WRITE && final_size <= inode->i_size) { /* * We could direct write to holes and fallocate. * * Allocated blocks to fill the hole are marked as uninitialized * to prevent paralel buffered read to expose the stale data * before DIO complete the data IO. * * As to previously fallocated extents, ext4 get_block * will just simply mark the buffer mapped but still * keep the extents uninitialized. * * for non AIO case, we will convert those unwritten extents * to written after return back from blockdev_direct_IO. * * for async DIO, the conversion needs to be defered when * the IO is completed. The ext4 end_io callback function * will be called to take care of the conversion work. * Here for async case, we allocate an io_end structure to * hook to the iocb. */ iocb->private = NULL; EXT4_I(inode)->cur_aio_dio = NULL; if (!is_sync_kiocb(iocb)) { iocb->private = ext4_init_io_end(inode); if (!iocb->private) return -ENOMEM; /* * we save the io structure for current async * direct IO, so that later ext4_get_blocks() * could flag the io structure whether there * is a unwritten extents needs to be converted * when IO is completed. */ EXT4_I(inode)->cur_aio_dio = iocb->private; } ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov, offset, nr_segs, ext4_get_block_write, ext4_end_io_dio); if (iocb->private) EXT4_I(inode)->cur_aio_dio = NULL; /* * The io_end structure takes a reference to the inode, * that structure needs to be destroyed and the * reference to the inode need to be dropped, when IO is * complete, even with 0 byte write, or failed. * * In the successful AIO DIO case, the io_end structure will be * desctroyed and the reference to the inode will be dropped * after the end_io call back function is called. * * In the case there is 0 byte write, or error case, since * VFS direct IO won't invoke the end_io call back function, * we need to free the end_io structure here. */ if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) { ext4_free_io_end(iocb->private); iocb->private = NULL; } else if (ret > 0 && ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN)) { int err; /* * for non AIO case, since the IO is already * completed, we could do the convertion right here */ err = ext4_convert_unwritten_extents(inode, offset, ret); if (err < 0) ret = err; ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } return ret; } /* for write the the end of file case, we fall back to old way */ return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; ssize_t ret; size_t count = iov_length(iov, nr_segs); loff_t final_size = offset + count; if (rw == WRITE && final_size <= inode->i_size) { /* * We could direct write to holes and fallocate. * * Allocated blocks to fill the hole are marked as uninitialized * to prevent paralel buffered read to expose the stale data * before DIO complete the data IO. * * As to previously fallocated extents, ext4 get_block * will just simply mark the buffer mapped but still * keep the extents uninitialized. * * for non AIO case, we will convert those unwritten extents * to written after return back from blockdev_direct_IO. * * for async DIO, the conversion needs to be defered when * the IO is completed. The ext4 end_io callback function * will be called to take care of the conversion work. * Here for async case, we allocate an io_end structure to * hook to the iocb. */ iocb->private = NULL; EXT4_I(inode)->cur_aio_dio = NULL; if (!is_sync_kiocb(iocb)) { iocb->private = ext4_init_io_end(inode, GFP_NOFS); if (!iocb->private) return -ENOMEM; /* * we save the io structure for current async * direct IO, so that later ext4_get_blocks() * could flag the io structure whether there * is a unwritten extents needs to be converted * when IO is completed. */ EXT4_I(inode)->cur_aio_dio = iocb->private; } ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov, offset, nr_segs, ext4_get_block_write, ext4_end_io_dio); if (iocb->private) EXT4_I(inode)->cur_aio_dio = NULL; /* * The io_end structure takes a reference to the inode, * that structure needs to be destroyed and the * reference to the inode need to be dropped, when IO is * complete, even with 0 byte write, or failed. * * In the successful AIO DIO case, the io_end structure will be * desctroyed and the reference to the inode will be dropped * after the end_io call back function is called. * * In the case there is 0 byte write, or error case, since * VFS direct IO won't invoke the end_io call back function, * we need to free the end_io structure here. */ if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) { ext4_free_io_end(iocb->private); iocb->private = NULL; } else if (ret > 0 && ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN)) { int err; /* * for non AIO case, since the IO is already * completed, we could do the convertion right here */ err = ext4_convert_unwritten_extents(inode, offset, ret); if (err < 0) ret = err; ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } return ret; } /* for write the the end of file case, we fall back to old way */ return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs); }
167,543
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_import_sec_context( OM_uint32 *minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t *context_handle) { OM_uint32 ret; ret = gss_import_sec_context(minor_status, interprocess_token, context_handle); 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_import_sec_context( OM_uint32 *minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t *context_handle) { /* * Until we implement partial context exports, there are no SPNEGO * exported context tokens, only tokens for underlying mechs. So just * return an error for now. */ return GSS_S_UNAVAILABLE; }
166,659
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: devzvol_readdir(struct vnode *dvp, struct uio *uiop, struct cred *cred, int *eofp, caller_context_t *ct_unused, int flags_unused) { struct sdev_node *sdvp = VTOSDEV(dvp); char *ptr; sdcmn_err13(("zv readdir of '%s' %s'", sdvp->sdev_path, sdvp->sdev_name)); if (strcmp(sdvp->sdev_path, ZVOL_DIR) == 0) { struct vnode *vp; rw_exit(&sdvp->sdev_contents); (void) devname_lookup_func(sdvp, "dsk", &vp, cred, devzvol_create_dir, SDEV_VATTR); VN_RELE(vp); (void) devname_lookup_func(sdvp, "rdsk", &vp, cred, devzvol_create_dir, SDEV_VATTR); VN_RELE(vp); rw_enter(&sdvp->sdev_contents, RW_READER); return (devname_readdir_func(dvp, uiop, cred, eofp, 0)); } if (uiop->uio_offset == 0) devzvol_prunedir(sdvp); ptr = sdvp->sdev_path + strlen(ZVOL_DIR); if ((strcmp(ptr, "/dsk") == 0) || (strcmp(ptr, "/rdsk") == 0)) { rw_exit(&sdvp->sdev_contents); devzvol_create_pool_dirs(dvp); rw_enter(&sdvp->sdev_contents, RW_READER); return (devname_readdir_func(dvp, uiop, cred, eofp, 0)); } ptr = strchr(ptr + 1, '/') + 1; rw_exit(&sdvp->sdev_contents); sdev_iter_datasets(dvp, ZFS_IOC_DATASET_LIST_NEXT, ptr); rw_enter(&sdvp->sdev_contents, RW_READER); return (devname_readdir_func(dvp, uiop, cred, eofp, 0)); } Commit Message: 5421 devzvol_readdir() needs to be more careful with strchr Reviewed by: Keith Wesolowski <[email protected]> Reviewed by: Jerry Jelinek <[email protected]> Approved by: Dan McDonald <[email protected]> CWE ID:
devzvol_readdir(struct vnode *dvp, struct uio *uiop, struct cred *cred, int *eofp, caller_context_t *ct_unused, int flags_unused) { struct sdev_node *sdvp = VTOSDEV(dvp); char *ptr; sdcmn_err13(("zv readdir of '%s' %s'", sdvp->sdev_path, sdvp->sdev_name)); if (strcmp(sdvp->sdev_path, ZVOL_DIR) == 0) { struct vnode *vp; rw_exit(&sdvp->sdev_contents); (void) devname_lookup_func(sdvp, "dsk", &vp, cred, devzvol_create_dir, SDEV_VATTR); VN_RELE(vp); (void) devname_lookup_func(sdvp, "rdsk", &vp, cred, devzvol_create_dir, SDEV_VATTR); VN_RELE(vp); rw_enter(&sdvp->sdev_contents, RW_READER); return (devname_readdir_func(dvp, uiop, cred, eofp, 0)); } if (uiop->uio_offset == 0) devzvol_prunedir(sdvp); ptr = sdvp->sdev_path + strlen(ZVOL_DIR); if ((strcmp(ptr, "/dsk") == 0) || (strcmp(ptr, "/rdsk") == 0)) { rw_exit(&sdvp->sdev_contents); devzvol_create_pool_dirs(dvp); rw_enter(&sdvp->sdev_contents, RW_READER); return (devname_readdir_func(dvp, uiop, cred, eofp, 0)); } ptr = strchr(ptr + 1, '/'); if (ptr == NULL) return (ENOENT); ptr++; rw_exit(&sdvp->sdev_contents); sdev_iter_datasets(dvp, ZFS_IOC_DATASET_LIST_NEXT, ptr); rw_enter(&sdvp->sdev_contents, RW_READER); return (devname_readdir_func(dvp, uiop, cred, eofp, 0)); }
166,785
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 mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos, long long size_, double& result) { assert(pReader); assert(pos >= 0); if ((size_ != 4) && (size_ != 8)) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) // error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { assert(size == 8); union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } return 0; } 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
long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos, long UnserializeFloat(IMkvReader* pReader, long long pos, long long size_, double& result) { if (!pReader || pos < 0 || ((size_ != 4) && (size_ != 8))) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) // error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } if (std::isinf(result) || std::isnan(result)) return E_FILE_FORMAT_INVALID; return 0; }
173,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: void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) { blink::WebLocalFrame* frame = NULL; GetPrintFrame(&frame); DCHECK(frame); auto plugin = delegate_->GetPdfElement(frame); if (!plugin.isNull()) { PrintNode(plugin); return; } print_preview_context_.InitWithFrame(frame); RequestPrintPreview(selection_only ? PRINT_PREVIEW_USER_INITIATED_SELECTION : PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME); } 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::OnInitiatePrintPreview(bool selection_only) { CHECK_LE(ipc_nesting_level_, 1); blink::WebLocalFrame* frame = NULL; GetPrintFrame(&frame); DCHECK(frame); auto plugin = delegate_->GetPdfElement(frame); if (!plugin.isNull()) { PrintNode(plugin); return; } print_preview_context_.InitWithFrame(frame); RequestPrintPreview(selection_only ? PRINT_PREVIEW_USER_INITIATED_SELECTION : PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME); }
171,871
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 unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct unix_sock *u = unix_sk(sk); DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name); struct sock *other = NULL; int namelen = 0; /* fake GCC */ int err; unsigned int hash; struct sk_buff *skb; long timeo; struct scm_cookie scm; int max_level; int data_len = 0; wait_for_unix_gc(); err = scm_send(sock, msg, &scm, false); if (err < 0) return err; err = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto out; if (msg->msg_namelen) { err = unix_mkname(sunaddr, msg->msg_namelen, &hash); if (err < 0) goto out; namelen = err; } else { sunaddr = NULL; err = -ENOTCONN; other = unix_peer_get(sk); if (!other) goto out; } if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr && (err = unix_autobind(sock)) != 0) goto out; err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; if (len > SKB_MAX_ALLOC) { data_len = min_t(size_t, len - SKB_MAX_ALLOC, MAX_SKB_FRAGS * PAGE_SIZE); data_len = PAGE_ALIGN(data_len); BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE); } skb = sock_alloc_send_pskb(sk, len - data_len, data_len, msg->msg_flags & MSG_DONTWAIT, &err, PAGE_ALLOC_COSTLY_ORDER); if (skb == NULL) goto out; err = unix_scm_to_skb(&scm, skb, true); if (err < 0) goto out_free; max_level = err + 1; skb_put(skb, len - data_len); skb->data_len = data_len; skb->len = len; err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len); if (err) goto out_free; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); restart: if (!other) { err = -ECONNRESET; if (sunaddr == NULL) goto out_free; other = unix_find_other(net, sunaddr, namelen, sk->sk_type, hash, &err); if (other == NULL) goto out_free; } if (sk_filter(other, skb) < 0) { /* Toss the packet but do not return any error to the sender */ err = len; goto out_free; } unix_state_lock(other); err = -EPERM; if (!unix_may_send(sk, other)) goto out_unlock; if (sock_flag(other, SOCK_DEAD)) { /* * Check with 1003.1g - what should * datagram error */ unix_state_unlock(other); sock_put(other); err = 0; unix_state_lock(sk); if (unix_peer(sk) == other) { unix_peer(sk) = NULL; unix_state_unlock(sk); unix_dgram_disconnected(sk, other); sock_put(other); err = -ECONNREFUSED; } else { unix_state_unlock(sk); } other = NULL; if (err) goto out_free; goto restart; } err = -EPIPE; if (other->sk_shutdown & RCV_SHUTDOWN) goto out_unlock; if (sk->sk_type != SOCK_SEQPACKET) { err = security_unix_may_send(sk->sk_socket, other->sk_socket); if (err) goto out_unlock; } if (unix_peer(other) != sk && unix_recvq_full(other)) { if (!timeo) { err = -EAGAIN; goto out_unlock; } timeo = unix_wait_for_peer(other, timeo); err = sock_intr_errno(timeo); if (signal_pending(current)) goto out_free; goto restart; } if (sock_flag(other, SOCK_RCVTSTAMP)) __net_timestamp(skb); maybe_add_creds(skb, sock, other); skb_queue_tail(&other->sk_receive_queue, skb); if (max_level > unix_sk(other)->recursion_level) unix_sk(other)->recursion_level = max_level; unix_state_unlock(other); other->sk_data_ready(other); sock_put(other); scm_destroy(&scm); return len; out_unlock: unix_state_unlock(other); out_free: kfree_skb(skb); out: if (other) sock_put(other); scm_destroy(&scm); return err; } Commit Message: unix: avoid use-after-free in ep_remove_wait_queue Rainer Weikusat <[email protected]> writes: An AF_UNIX datagram socket being the client in an n:1 association with some server socket is only allowed to send messages to the server if the receive queue of this socket contains at most sk_max_ack_backlog datagrams. This implies that prospective writers might be forced to go to sleep despite none of the message presently enqueued on the server receive queue were sent by them. In order to ensure that these will be woken up once space becomes again available, the present unix_dgram_poll routine does a second sock_poll_wait call with the peer_wait wait queue of the server socket as queue argument (unix_dgram_recvmsg does a wake up on this queue after a datagram was received). This is inherently problematic because the server socket is only guaranteed to remain alive for as long as the client still holds a reference to it. In case the connection is dissolved via connect or by the dead peer detection logic in unix_dgram_sendmsg, the server socket may be freed despite "the polling mechanism" (in particular, epoll) still has a pointer to the corresponding peer_wait queue. There's no way to forcibly deregister a wait queue with epoll. Based on an idea by Jason Baron, the patch below changes the code such that a wait_queue_t belonging to the client socket is enqueued on the peer_wait queue of the server whenever the peer receive queue full condition is detected by either a sendmsg or a poll. A wake up on the peer queue is then relayed to the ordinary wait queue of the client socket via wake function. The connection to the peer wait queue is again dissolved if either a wake up is about to be relayed or the client socket reconnects or a dead peer is detected or the client socket is itself closed. This enables removing the second sock_poll_wait from unix_dgram_poll, thus avoiding the use-after-free, while still ensuring that no blocked writer sleeps forever. Signed-off-by: Rainer Weikusat <[email protected]> Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets") Reviewed-by: Jason Baron <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct unix_sock *u = unix_sk(sk); DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name); struct sock *other = NULL; int namelen = 0; /* fake GCC */ int err; unsigned int hash; struct sk_buff *skb; long timeo; struct scm_cookie scm; int max_level; int data_len = 0; int sk_locked; wait_for_unix_gc(); err = scm_send(sock, msg, &scm, false); if (err < 0) return err; err = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto out; if (msg->msg_namelen) { err = unix_mkname(sunaddr, msg->msg_namelen, &hash); if (err < 0) goto out; namelen = err; } else { sunaddr = NULL; err = -ENOTCONN; other = unix_peer_get(sk); if (!other) goto out; } if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr && (err = unix_autobind(sock)) != 0) goto out; err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; if (len > SKB_MAX_ALLOC) { data_len = min_t(size_t, len - SKB_MAX_ALLOC, MAX_SKB_FRAGS * PAGE_SIZE); data_len = PAGE_ALIGN(data_len); BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE); } skb = sock_alloc_send_pskb(sk, len - data_len, data_len, msg->msg_flags & MSG_DONTWAIT, &err, PAGE_ALLOC_COSTLY_ORDER); if (skb == NULL) goto out; err = unix_scm_to_skb(&scm, skb, true); if (err < 0) goto out_free; max_level = err + 1; skb_put(skb, len - data_len); skb->data_len = data_len; skb->len = len; err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len); if (err) goto out_free; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); restart: if (!other) { err = -ECONNRESET; if (sunaddr == NULL) goto out_free; other = unix_find_other(net, sunaddr, namelen, sk->sk_type, hash, &err); if (other == NULL) goto out_free; } if (sk_filter(other, skb) < 0) { /* Toss the packet but do not return any error to the sender */ err = len; goto out_free; } sk_locked = 0; unix_state_lock(other); restart_locked: err = -EPERM; if (!unix_may_send(sk, other)) goto out_unlock; if (unlikely(sock_flag(other, SOCK_DEAD))) { /* * Check with 1003.1g - what should * datagram error */ unix_state_unlock(other); sock_put(other); if (!sk_locked) unix_state_lock(sk); err = 0; if (unix_peer(sk) == other) { unix_peer(sk) = NULL; unix_dgram_peer_wake_disconnect_wakeup(sk, other); unix_state_unlock(sk); unix_dgram_disconnected(sk, other); sock_put(other); err = -ECONNREFUSED; } else { unix_state_unlock(sk); } other = NULL; if (err) goto out_free; goto restart; } err = -EPIPE; if (other->sk_shutdown & RCV_SHUTDOWN) goto out_unlock; if (sk->sk_type != SOCK_SEQPACKET) { err = security_unix_may_send(sk->sk_socket, other->sk_socket); if (err) goto out_unlock; } if (unlikely(unix_peer(other) != sk && unix_recvq_full(other))) { if (timeo) { timeo = unix_wait_for_peer(other, timeo); err = sock_intr_errno(timeo); if (signal_pending(current)) goto out_free; goto restart; } if (!sk_locked) { unix_state_unlock(other); unix_state_double_lock(sk, other); } if (unix_peer(sk) != other || unix_dgram_peer_wake_me(sk, other)) { err = -EAGAIN; sk_locked = 1; goto out_unlock; } if (!sk_locked) { sk_locked = 1; goto restart_locked; } } if (unlikely(sk_locked)) unix_state_unlock(sk); if (sock_flag(other, SOCK_RCVTSTAMP)) __net_timestamp(skb); maybe_add_creds(skb, sock, other); skb_queue_tail(&other->sk_receive_queue, skb); if (max_level > unix_sk(other)->recursion_level) unix_sk(other)->recursion_level = max_level; unix_state_unlock(other); other->sk_data_ready(other); sock_put(other); scm_destroy(&scm); return len; out_unlock: if (sk_locked) unix_state_unlock(sk); unix_state_unlock(other); out_free: kfree_skb(skb); out: if (other) sock_put(other); scm_destroy(&scm); return err; }
166,836
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: cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') separator = *src++; /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); } Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option This fixes a directory traversal in the cpio tool. CWE ID: CWE-22
cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }
166,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: static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len)
166,685
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: image_transform_default_ini(PNG_CONST image_transform *this, transform_display *that) { this->next->ini(this->next, that); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_default_ini(PNG_CONST image_transform *this, extern void image_transform_default_ini(const image_transform *this, transform_display *that); /* silence GCC warnings */ void /* private, but almost always needed */ image_transform_default_ini(const image_transform *this, transform_display *that) { this->next->ini(this->next, that); }
173,621
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 mark_object(struct object *obj, struct strbuf *path, const char *name, void *data) { update_progress(data); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void mark_object(struct object *obj, struct strbuf *path, static void mark_object(struct object *obj, const char *name, void *data) { update_progress(data); }
167,425
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 nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else if (pool->free_total < NW_BUF_POOL_MAX_SIZE) { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } else { free(buf); } }
169,015
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 read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); } Commit Message: Fix possible stack overflows in decoder for illegal bit streams Fixes CVE-2018-0429 A vulnerability in the Thor decoder (available at: https://github.com/cisco/thor) could allow an authenticated, local attacker to cause segmentation faults and stack overflows when using a non-conformant Thor bitstream as input. The vulnerability is due to lack of input validation when parsing the bitstream. A successful exploit could allow the attacker to cause a stack overflow and potentially inject and execute arbitrary code. CWE ID: CWE-119
void read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->log2_sb_size = clip(decoder_info->log2_sb_size, log2i(MIN_BLOCK_SIZE), log2i(MAX_SB_SIZE)); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); }
169,367
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 BluetoothDeviceChromeOS::RequestPasskey( const dbus::ObjectPath& device_path, const PasskeyCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestPasskey"; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_REQUEST_PASSKEY, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(passkey_callback_.is_null()); passkey_callback_ = callback; pairing_delegate_->RequestPasskey(this); pairing_delegate_used_ = true; } 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:
void BluetoothDeviceChromeOS::RequestPasskey(
171,236
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 sysMapFile(const char* fn, MemMapping* pMap) { memset(pMap, 0, sizeof(*pMap)); if (fn && fn[0] == '@') { FILE* mapf = fopen(fn+1, "r"); if (mapf == NULL) { LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno)); return -1; } if (sysMapBlockFile(mapf, pMap) != 0) { LOGW("Map of '%s' failed\n", fn); return -1; } fclose(mapf); } else { int fd = open(fn, O_RDONLY, 0); if (fd < 0) { LOGE("Unable to open '%s': %s\n", fn, strerror(errno)); return -1; } if (sysMapFD(fd, pMap) != 0) { LOGE("Map of '%s' failed\n", fn); close(fd); return -1; } close(fd); } return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
int sysMapFile(const char* fn, MemMapping* pMap) { memset(pMap, 0, sizeof(*pMap)); if (fn && fn[0] == '@') { FILE* mapf = fopen(fn+1, "r"); if (mapf == NULL) { LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno)); return -1; } if (sysMapBlockFile(mapf, pMap) != 0) { LOGW("Map of '%s' failed\n", fn); fclose(mapf); return -1; } fclose(mapf); } else { int fd = open(fn, O_RDONLY, 0); if (fd < 0) { LOGE("Unable to open '%s': %s\n", fn, strerror(errno)); return -1; } if (sysMapFD(fd, pMap) != 0) { LOGE("Map of '%s' failed\n", fn); close(fd); return -1; } close(fd); } return 0; }
173,905
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 update_logging() { bool should_log = module_started && (logging_enabled_via_api || stack_config->get_btsnoop_turned_on()); if (should_log == is_logging) return; is_logging = should_log; if (should_log) { btsnoop_net_open(); const char *log_path = stack_config->get_btsnoop_log_path(); if (stack_config->get_btsnoop_should_save_last()) { char last_log_path[PATH_MAX]; snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp()); if (!rename(log_path, last_log_path) && errno != ENOENT) LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno)); } logfile_fd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); if (logfile_fd == INVALID_FD) { LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno)); is_logging = false; return; } write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16); } else { if (logfile_fd != INVALID_FD) close(logfile_fd); logfile_fd = INVALID_FD; btsnoop_net_close(); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void update_logging() { bool should_log = module_started && (logging_enabled_via_api || stack_config->get_btsnoop_turned_on()); if (should_log == is_logging) return; is_logging = should_log; if (should_log) { btsnoop_net_open(); const char *log_path = stack_config->get_btsnoop_log_path(); if (stack_config->get_btsnoop_should_save_last()) { char last_log_path[PATH_MAX]; snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp()); if (!rename(log_path, last_log_path) && errno != ENOENT) LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno)); } logfile_fd = TEMP_FAILURE_RETRY(open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)); if (logfile_fd == INVALID_FD) { LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno)); is_logging = false; return; } TEMP_FAILURE_RETRY(write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16)); } else { if (logfile_fd != INVALID_FD) close(logfile_fd); logfile_fd = INVALID_FD; btsnoop_net_close(); } }
173,473
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 size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
static size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; }
167,118
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: DataReductionProxySettings::DataReductionProxySettings() : unreachable_(false), deferred_initialization_(false), prefs_(nullptr), config_(nullptr), clock_(base::DefaultClock::GetInstance()) {} Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
DataReductionProxySettings::DataReductionProxySettings() : unreachable_(false), deferred_initialization_(false), prefs_(nullptr), config_(nullptr), clock_(base::DefaultClock::GetInstance()) {}
172,550
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 int subpel_avg_variance_ref(const uint8_t *ref, const uint8_t *src, const uint8_t *second_pred, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } 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
unsigned int subpel_avg_variance_ref(const uint8_t *ref,
174,594
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: on_handler_appeared(GDBusConnection *connection, const gchar *name, const gchar *name_owner, gpointer user_data) { struct tcmur_handler *handler = user_data; struct dbus_info *info = handler->opaque; if (info->register_invocation) { info->connection = connection; tcmur_register_handler(handler); dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config)); g_dbus_method_invocation_return_value(info->register_invocation, g_variant_new("(bs)", TRUE, "succeeded")); info->register_invocation = NULL; } } Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS Trying to unregister an internal handler ended up in a SEGFAULT, because the tcmur_handler->opaque was NULL. Way to reproduce: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow we use a newly introduced boolean in struct tcmur_handler for keeping track of external handlers. As suggested by mikechristie adjusting the public data structure is acceptable. CWE ID: CWE-476
on_handler_appeared(GDBusConnection *connection, const gchar *name, const gchar *name_owner, gpointer user_data) { struct tcmur_handler *handler = user_data; struct dbus_info *info = handler->opaque; if (info->register_invocation) { info->connection = connection; tcmur_register_dbus_handler(handler); dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config)); g_dbus_method_invocation_return_value(info->register_invocation, g_variant_new("(bs)", TRUE, "succeeded")); info->register_invocation = NULL; } }
167,631
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 get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } Commit Message: jpeg2000: check log2_cblk dimensions Fixes out of array access Fixes Ticket2895 Found-by: Piotr Bandurski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; }
165,920
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: ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. 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). CWE ID: CWE-125
ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*k); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; }
167,799
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 inline void uipc_wakeup_locked(void) { char sig_on = 1; BTIF_TRACE_EVENT("UIPC SEND WAKE UP"); send(uipc_main.signal_fds[1], &sig_on, sizeof(sig_on), 0); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static inline void uipc_wakeup_locked(void) { char sig_on = 1; BTIF_TRACE_EVENT("UIPC SEND WAKE UP"); TEMP_FAILURE_RETRY(send(uipc_main.signal_fds[1], &sig_on, sizeof(sig_on), 0)); }
173,499
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 IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, bool IsTraceEventArgsWhitelisted( const char* category_group_name, const char* event_name, base::trace_event::ArgumentNameFilterPredicate* arg_filter) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; }
171,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: SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() { return syslogs_lib_.GetDefaultImpl(use_stub_impl_); } 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
SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() {
170,631
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: BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() { DBusThreadManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->RemoveObserver(this); } 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:
BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() { DBusThreadManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->RemoveObserver(this); VLOG(1) << "Unregistering pairing agent"; DBusThreadManager::Get()->GetBluetoothAgentManagerClient()-> UnregisterAgent( dbus::ObjectPath(kAgentPath), base::Bind(&base::DoNothing), base::Bind(&OnUnregisterAgentError)); }
171,215
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 write_output(void) { int fd; struct filter_op *fop; struct filter_header fh; size_t ninst, i; u_char *data; /* conver the tree to an array of filter_op */ ninst = compile_tree(&fop); if (fop == NULL) return -E_NOTHANDLED; /* create the file */ fd = open(EF_GBL_OPTIONS->output_file, O_CREAT | O_RDWR | O_TRUNC | O_BINARY, 0644); ON_ERROR(fd, -1, "Can't create file %s", EF_GBL_OPTIONS->output_file); /* display the message */ fprintf(stdout, " Writing output to \'%s\' ", EF_GBL_OPTIONS->output_file); fflush(stdout); /* compute the header */ fh.magic = htons(EC_FILTER_MAGIC); strncpy(fh.version, EC_VERSION, sizeof(fh.version)); fh.data = sizeof(fh); data = create_data_segment(&fh, fop, ninst); /* write the header */ write(fd, &fh, sizeof(struct filter_header)); /* write the data segment */ write(fd, data, fh.code - fh.data); /* write the instructions */ for (i = 0; i <= ninst; i++) { print_progress_bar(&fop[i]); write(fd, &fop[i], sizeof(struct filter_op)); } close(fd); fprintf(stdout, " done.\n\n"); fprintf(stdout, " -> Script encoded into %d instructions.\n\n", (int)(i - 1)); return E_SUCCESS; } Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782) CWE ID: CWE-125
int write_output(void) { int fd; struct filter_op *fop; struct filter_header fh; size_t ninst, i; u_char *data; /* conver the tree to an array of filter_op */ ninst = compile_tree(&fop); if (fop == NULL) return -E_NOTHANDLED; if (ninst == 0) return -E_INVALID; /* create the file */ fd = open(EF_GBL_OPTIONS->output_file, O_CREAT | O_RDWR | O_TRUNC | O_BINARY, 0644); ON_ERROR(fd, -1, "Can't create file %s", EF_GBL_OPTIONS->output_file); /* display the message */ fprintf(stdout, " Writing output to \'%s\' ", EF_GBL_OPTIONS->output_file); fflush(stdout); /* compute the header */ fh.magic = htons(EC_FILTER_MAGIC); strncpy(fh.version, EC_VERSION, sizeof(fh.version)); fh.data = sizeof(fh); data = create_data_segment(&fh, fop, ninst); /* write the header */ write(fd, &fh, sizeof(struct filter_header)); /* write the data segment */ write(fd, data, fh.code - fh.data); /* write the instructions */ for (i = 0; i <= ninst; i++) { print_progress_bar(&fop[i]); write(fd, &fop[i], sizeof(struct filter_op)); } close(fd); fprintf(stdout, " done.\n\n"); fprintf(stdout, " -> Script encoded into %d instructions.\n\n", (int)(i - 1)); return E_SUCCESS; }
168,338
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 cJSON *cJSON_New_Item( void ) { cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) ); if ( node ) memset( node, 0, sizeof(cJSON) ); return node; } 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 cJSON *cJSON_New_Item( void ) static cJSON *cJSON_New_Item(void) { cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); if (node) memset(node,0,sizeof(cJSON)); return node; }
167,291
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 jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) & 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp); return 0; } 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
static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val) { jas_ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = (tmp & 0x80000000) ? (-JAS_CAST(jas_longlong, (((~tmp) & 0x7fffffff) + 1))) : JAS_CAST(jas_longlong, tmp); return 0; }
168,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: static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"CorruptImage"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,"CorruptImage"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,"invalid parameter"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,"CorruptImage"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,"decoder suspended"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,"user abort"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); break; } default: ThrowReaderException(CorruptImageError,"CorruptImage"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); return(image); } Commit Message: Fixed fd leak for webp coder (patch from #382) CWE ID: CWE-119
static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"CorruptImage"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,"CorruptImage"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,"invalid parameter"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,"CorruptImage"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,"decoder suspended"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,"user abort"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); break; } default: ThrowReaderException(CorruptImageError,"CorruptImage"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(image); }
168,328
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 reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); Element* impl = V8Element::toImpl(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate()); } Commit Message: binding: Removes unused code in templates/attributes.cpp. Faking {{cpp_class}} and {{c8_class}} doesn't make sense. Probably it made sense before the introduction of virtual ScriptWrappable::wrap(). Checking the existence of window->document() doesn't seem making sense to me, and CQ tests seem passing without the check. BUG= Review-Url: https://codereview.chromium.org/2268433002 Cr-Commit-Position: refs/heads/master@{#413375} CWE ID: CWE-189
static void reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate()); }
171,597
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: BluetoothDeviceChromeOS::BluetoothDeviceChromeOS( BluetoothAdapterChromeOS* adapter, const dbus::ObjectPath& object_path) : adapter_(adapter), object_path_(object_path), num_connecting_calls_(0), pairing_delegate_(NULL), pairing_delegate_used_(false), weak_ptr_factory_(this) { } 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:
BluetoothDeviceChromeOS::BluetoothDeviceChromeOS( BluetoothAdapterChromeOS* adapter, const dbus::ObjectPath& object_path) : adapter_(adapter), object_path_(object_path), num_connecting_calls_(0), weak_ptr_factory_(this) { }
171,217
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: QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number, QuicFecGroupNumber fec_group) { header_.packet_sequence_number = number; header_.flags = PACKET_FLAGS_NONE; header_.fec_group = fec_group; QuicFrames frames; QuicFrame frame(&frame1_); frames.push_back(frame); QuicPacket* packet; framer_.ConstructFragementDataPacket(header_, frames, &packet); return packet; } Commit Message: Fix uninitialized access in QuicConnectionHelperTest BUG=159928 Review URL: https://chromiumcodereview.appspot.com/11360153 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number, QuicFecGroupNumber fec_group) { header_.guid = guid_; header_.packet_sequence_number = number; header_.transmission_time = 0; header_.retransmission_count = 0; header_.flags = PACKET_FLAGS_NONE; header_.fec_group = fec_group; QuicFrames frames; QuicFrame frame(&frame1_); frames.push_back(frame); QuicPacket* packet; framer_.ConstructFragementDataPacket(header_, frames, &packet); return packet; }
171,410