text
stringlengths
478
227k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *make_filename_safe(const char *filename TSRMLS_DC) { if (*filename && strncmp(filename, ":memory:", sizeof(":memory:")-1)) { char *fullpath = expand_filepath(filename, NULL TSRMLS_CC); if (!fullpath) { return NULL; } if (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) { efree(fullpath); return NULL; } if (php_check_open_basedir(fullpath TSRMLS_CC)) { efree(fullpath); return NULL; } return fullpath; } return estrdup(filename); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cirrus_bitblt_cputovideo_next(CirrusVGAState * s) { int copy_count; uint8_t *end_ptr; if (s->cirrus_srccounter > 0) { if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) { cirrus_bitblt_common_patterncopy(s, s->cirrus_bltbuf); the_end: s->cirrus_srccounter = 0; cirrus_bitblt_reset(s); } else { /* at least one scan line */ do { (*s->cirrus_rop)(s, s->vram_ptr + s->cirrus_blt_dstaddr, s->cirrus_bltbuf, 0, 0, s->cirrus_blt_width, 1); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, 0, s->cirrus_blt_width, 1); s->cirrus_blt_dstaddr += s->cirrus_blt_dstpitch; s->cirrus_srccounter -= s->cirrus_blt_srcpitch; if (s->cirrus_srccounter <= 0) goto the_end; /* more bytes than needed can be transfered because of word alignment, so we keep them for the next line */ /* XXX: keep alignment to speed up transfer */ end_ptr = s->cirrus_bltbuf + s->cirrus_blt_srcpitch; copy_count = s->cirrus_srcptr_end - end_ptr; memmove(s->cirrus_bltbuf, end_ptr, copy_count); s->cirrus_srcptr = s->cirrus_bltbuf + copy_count; s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch; } while (s->cirrus_srcptr >= s->cirrus_srcptr_end); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ieee80211_rx(struct ieee80211_device *ieee, struct sk_buff *skb, struct ieee80211_rx_stats *rx_stats) { struct net_device *dev = ieee->dev; struct ieee80211_hdr_4addr *hdr; size_t hdrlen; u16 fc, type, stype, sc; struct net_device_stats *stats; unsigned int frag; u8 *payload; u16 ethertype; #ifdef NOT_YET struct net_device *wds = NULL; struct sk_buff *skb2 = NULL; struct net_device *wds = NULL; int frame_authorized = 0; int from_assoc_ap = 0; void *sta = NULL; #endif u8 dst[ETH_ALEN]; u8 src[ETH_ALEN]; struct ieee80211_crypt_data *crypt = NULL; int keyidx = 0; int can_be_decrypted = 0; hdr = (struct ieee80211_hdr_4addr *)skb->data; stats = &ieee->stats; if (skb->len < 10) { printk(KERN_INFO "%s: SKB length < 10\n", dev->name); goto rx_dropped; } fc = le16_to_cpu(hdr->frame_ctl); type = WLAN_FC_GET_TYPE(fc); stype = WLAN_FC_GET_STYPE(fc); sc = le16_to_cpu(hdr->seq_ctl); frag = WLAN_GET_SEQ_FRAG(sc); hdrlen = ieee80211_get_hdrlen(fc); /* Put this code here so that we avoid duplicating it in all * Rx paths. - Jean II */ #ifdef CONFIG_WIRELESS_EXT #ifdef IW_WIRELESS_SPY /* defined in iw_handler.h */ /* If spy monitoring on */ if (ieee->spy_data.spy_number > 0) { struct iw_quality wstats; wstats.updated = 0; if (rx_stats->mask & IEEE80211_STATMASK_RSSI) { wstats.level = rx_stats->rssi; wstats.updated |= IW_QUAL_LEVEL_UPDATED; } else wstats.updated |= IW_QUAL_LEVEL_INVALID; if (rx_stats->mask & IEEE80211_STATMASK_NOISE) { wstats.noise = rx_stats->noise; wstats.updated |= IW_QUAL_NOISE_UPDATED; } else wstats.updated |= IW_QUAL_NOISE_INVALID; if (rx_stats->mask & IEEE80211_STATMASK_SIGNAL) { wstats.qual = rx_stats->signal; wstats.updated |= IW_QUAL_QUAL_UPDATED; } else wstats.updated |= IW_QUAL_QUAL_INVALID; /* Update spy records */ wireless_spy_update(ieee->dev, hdr->addr2, &wstats); } #endif /* IW_WIRELESS_SPY */ #endif /* CONFIG_WIRELESS_EXT */ #ifdef NOT_YET hostap_update_rx_stats(local->ap, hdr, rx_stats); #endif if (ieee->iw_mode == IW_MODE_MONITOR) { stats->rx_packets++; stats->rx_bytes += skb->len; ieee80211_monitor_rx(ieee, skb, rx_stats); return 1; } can_be_decrypted = (is_multicast_ether_addr(hdr->addr1) || is_broadcast_ether_addr(hdr->addr2)) ? ieee->host_mc_decrypt : ieee->host_decrypt; if (can_be_decrypted) { if (skb->len >= hdrlen + 3) { /* Top two-bits of byte 3 are the key index */ keyidx = skb->data[hdrlen + 3] >> 6; } /* ieee->crypt[] is WEP_KEY (4) in length. Given that keyidx * is only allowed 2-bits of storage, no value of keyidx can * be provided via above code that would result in keyidx * being out of range */ crypt = ieee->crypt[keyidx]; #ifdef NOT_YET sta = NULL; /* Use station specific key to override default keys if the * receiver address is a unicast address ("individual RA"). If * bcrx_sta_key parameter is set, station specific key is used * even with broad/multicast targets (this is against IEEE * 802.11, but makes it easier to use different keys with * stations that do not support WEP key mapping). */ if (!(hdr->addr1[0] & 0x01) || local->bcrx_sta_key) (void)hostap_handle_sta_crypto(local, hdr, &crypt, &sta); #endif /* allow NULL decrypt to indicate an station specific override * for default encryption */ if (crypt && (crypt->ops == NULL || crypt->ops->decrypt_mpdu == NULL)) crypt = NULL; if (!crypt && (fc & IEEE80211_FCTL_PROTECTED)) { /* This seems to be triggered by some (multicast?) * frames from other than current BSS, so just drop the * frames silently instead of filling system log with * these reports. */ IEEE80211_DEBUG_DROP("Decryption failed (not set)" " (SA=" MAC_FMT ")\n", MAC_ARG(hdr->addr2)); ieee->ieee_stats.rx_discards_undecryptable++; goto rx_dropped; } } #ifdef NOT_YET if (type != WLAN_FC_TYPE_DATA) { if (type == WLAN_FC_TYPE_MGMT && stype == WLAN_FC_STYPE_AUTH && fc & IEEE80211_FCTL_PROTECTED && ieee->host_decrypt && (keyidx = hostap_rx_frame_decrypt(ieee, skb, crypt)) < 0) { printk(KERN_DEBUG "%s: failed to decrypt mgmt::auth " "from " MAC_FMT "\n", dev->name, MAC_ARG(hdr->addr2)); /* TODO: could inform hostapd about this so that it * could send auth failure report */ goto rx_dropped; } if (ieee80211_rx_frame_mgmt(ieee, skb, rx_stats, type, stype)) goto rx_dropped; else goto rx_exit; } #endif /* drop duplicate 802.11 retransmissions (IEEE 802.11 Chap. 9.29) */ if (sc == ieee->prev_seq_ctl) goto rx_dropped; else ieee->prev_seq_ctl = sc; /* Data frame - extract src/dst addresses */ if (skb->len < IEEE80211_3ADDR_LEN) goto rx_dropped; switch (fc & (IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) { case IEEE80211_FCTL_FROMDS: memcpy(dst, hdr->addr1, ETH_ALEN); memcpy(src, hdr->addr3, ETH_ALEN); break; case IEEE80211_FCTL_TODS: memcpy(dst, hdr->addr3, ETH_ALEN); memcpy(src, hdr->addr2, ETH_ALEN); break; case IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS: if (skb->len < IEEE80211_4ADDR_LEN) goto rx_dropped; memcpy(dst, hdr->addr3, ETH_ALEN); memcpy(src, hdr->addr4, ETH_ALEN); break; case 0: memcpy(dst, hdr->addr1, ETH_ALEN); memcpy(src, hdr->addr2, ETH_ALEN); break; } #ifdef NOT_YET if (hostap_rx_frame_wds(ieee, hdr, fc, &wds)) goto rx_dropped; if (wds) { skb->dev = dev = wds; stats = hostap_get_stats(dev); } if (ieee->iw_mode == IW_MODE_MASTER && !wds && (fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_FROMDS && ieee->stadev && !compare_ether_addr(hdr->addr2, ieee->assoc_ap_addr)) { /* Frame from BSSID of the AP for which we are a client */ skb->dev = dev = ieee->stadev; stats = hostap_get_stats(dev); from_assoc_ap = 1; } #endif dev->last_rx = jiffies; #ifdef NOT_YET if ((ieee->iw_mode == IW_MODE_MASTER || ieee->iw_mode == IW_MODE_REPEAT) && !from_assoc_ap) { switch (hostap_handle_sta_rx(ieee, dev, skb, rx_stats, wds != NULL)) { case AP_RX_CONTINUE_NOT_AUTHORIZED: frame_authorized = 0; break; case AP_RX_CONTINUE: frame_authorized = 1; break; case AP_RX_DROP: goto rx_dropped; case AP_RX_EXIT: goto rx_exit; } } #endif /* Nullfunc frames may have PS-bit set, so they must be passed to * hostap_handle_sta_rx() before being dropped here. */ stype &= ~IEEE80211_STYPE_QOS_DATA; if (stype != IEEE80211_STYPE_DATA && stype != IEEE80211_STYPE_DATA_CFACK && stype != IEEE80211_STYPE_DATA_CFPOLL && stype != IEEE80211_STYPE_DATA_CFACKPOLL) { if (stype != IEEE80211_STYPE_NULLFUNC) IEEE80211_DEBUG_DROP("RX: dropped data frame " "with no data (type=0x%02x, " "subtype=0x%02x, len=%d)\n", type, stype, skb->len); goto rx_dropped; } /* skb: hdr + (possibly fragmented, possibly encrypted) payload */ if ((fc & IEEE80211_FCTL_PROTECTED) && can_be_decrypted && (keyidx = ieee80211_rx_frame_decrypt(ieee, skb, crypt)) < 0) goto rx_dropped; hdr = (struct ieee80211_hdr_4addr *)skb->data; /* skb: hdr + (possibly fragmented) plaintext payload */ // PR: FIXME: hostap has additional conditions in the "if" below: // ieee->host_decrypt && (fc & IEEE80211_FCTL_PROTECTED) && if ((frag != 0) || (fc & IEEE80211_FCTL_MOREFRAGS)) { int flen; struct sk_buff *frag_skb = ieee80211_frag_cache_get(ieee, hdr); IEEE80211_DEBUG_FRAG("Rx Fragment received (%u)\n", frag); if (!frag_skb) { IEEE80211_DEBUG(IEEE80211_DL_RX | IEEE80211_DL_FRAG, "Rx cannot get skb from fragment " "cache (morefrag=%d seq=%u frag=%u)\n", (fc & IEEE80211_FCTL_MOREFRAGS) != 0, WLAN_GET_SEQ_SEQ(sc), frag); goto rx_dropped; } flen = skb->len; if (frag != 0) flen -= hdrlen; if (frag_skb->tail + flen > frag_skb->end) { printk(KERN_WARNING "%s: host decrypted and " "reassembled frame did not fit skb\n", dev->name); ieee80211_frag_cache_invalidate(ieee, hdr); goto rx_dropped; } if (frag == 0) { /* copy first fragment (including full headers) into * beginning of the fragment cache skb */ skb_copy_from_linear_data(skb, skb_put(frag_skb, flen), flen); } else { /* append frame payload to the end of the fragment * cache skb */ skb_copy_from_linear_data_offset(skb, hdrlen, skb_put(frag_skb, flen), flen); } dev_kfree_skb_any(skb); skb = NULL; if (fc & IEEE80211_FCTL_MOREFRAGS) { /* more fragments expected - leave the skb in fragment * cache for now; it will be delivered to upper layers * after all fragments have been received */ goto rx_exit; } /* this was the last fragment and the frame will be * delivered, so remove skb from fragment cache */ skb = frag_skb; hdr = (struct ieee80211_hdr_4addr *)skb->data; ieee80211_frag_cache_invalidate(ieee, hdr); } /* skb: hdr + (possible reassembled) full MSDU payload; possibly still * encrypted/authenticated */ if ((fc & IEEE80211_FCTL_PROTECTED) && can_be_decrypted && ieee80211_rx_frame_decrypt_msdu(ieee, skb, keyidx, crypt)) goto rx_dropped; hdr = (struct ieee80211_hdr_4addr *)skb->data; if (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !ieee->open_wep) { if ( /*ieee->ieee802_1x && */ ieee80211_is_eapol_frame(ieee, skb)) { /* pass unencrypted EAPOL frames even if encryption is * configured */ } else { IEEE80211_DEBUG_DROP("encryption configured, but RX " "frame not encrypted (SA=" MAC_FMT ")\n", MAC_ARG(hdr->addr2)); goto rx_dropped; } } if (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !ieee->open_wep && !ieee80211_is_eapol_frame(ieee, skb)) { IEEE80211_DEBUG_DROP("dropped unencrypted RX data " "frame from " MAC_FMT " (drop_unencrypted=1)\n", MAC_ARG(hdr->addr2)); goto rx_dropped; } /* If the frame was decrypted in hardware, we may need to strip off * any security data (IV, ICV, etc) that was left behind */ if (!can_be_decrypted && (fc & IEEE80211_FCTL_PROTECTED) && ieee->host_strip_iv_icv) { int trimlen = 0; /* Top two-bits of byte 3 are the key index */ if (skb->len >= hdrlen + 3) keyidx = skb->data[hdrlen + 3] >> 6; /* To strip off any security data which appears before the * payload, we simply increase hdrlen (as the header gets * chopped off immediately below). For the security data which * appears after the payload, we use skb_trim. */ switch (ieee->sec.encode_alg[keyidx]) { case SEC_ALG_WEP: /* 4 byte IV */ hdrlen += 4; /* 4 byte ICV */ trimlen = 4; break; case SEC_ALG_TKIP: /* 4 byte IV, 4 byte ExtIV */ hdrlen += 8; /* 8 byte MIC, 4 byte ICV */ trimlen = 12; break; case SEC_ALG_CCMP: /* 8 byte CCMP header */ hdrlen += 8; /* 8 byte MIC */ trimlen = 8; break; } if (skb->len < trimlen) goto rx_dropped; __skb_trim(skb, skb->len - trimlen); if (skb->len < hdrlen) goto rx_dropped; } /* skb: hdr + (possible reassembled) full plaintext payload */ payload = skb->data + hdrlen; ethertype = (payload[6] << 8) | payload[7]; #ifdef NOT_YET /* If IEEE 802.1X is used, check whether the port is authorized to send * the received frame. */ if (ieee->ieee802_1x && ieee->iw_mode == IW_MODE_MASTER) { if (ethertype == ETH_P_PAE) { printk(KERN_DEBUG "%s: RX: IEEE 802.1X frame\n", dev->name); if (ieee->hostapd && ieee->apdev) { /* Send IEEE 802.1X frames to the user * space daemon for processing */ prism2_rx_80211(ieee->apdev, skb, rx_stats, PRISM2_RX_MGMT); ieee->apdevstats.rx_packets++; ieee->apdevstats.rx_bytes += skb->len; goto rx_exit; } } else if (!frame_authorized) { printk(KERN_DEBUG "%s: dropped frame from " "unauthorized port (IEEE 802.1X): " "ethertype=0x%04x\n", dev->name, ethertype); goto rx_dropped; } } #endif /* convert hdr + possible LLC headers into Ethernet header */ if (skb->len - hdrlen >= 8 && ((memcmp(payload, rfc1042_header, SNAP_SIZE) == 0 && ethertype != ETH_P_AARP && ethertype != ETH_P_IPX) || memcmp(payload, bridge_tunnel_header, SNAP_SIZE) == 0)) { /* remove RFC1042 or Bridge-Tunnel encapsulation and * replace EtherType */ skb_pull(skb, hdrlen + SNAP_SIZE); memcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN); memcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN); } else { u16 len; /* Leave Ethernet header part of hdr and full payload */ skb_pull(skb, hdrlen); len = htons(skb->len); memcpy(skb_push(skb, 2), &len, 2); memcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN); memcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN); } #ifdef NOT_YET if (wds && ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_TODS) && skb->len >= ETH_HLEN + ETH_ALEN) { /* Non-standard frame: get addr4 from its bogus location after * the payload */ skb_copy_to_linear_data_offset(skb, ETH_ALEN, skb->data + skb->len - ETH_ALEN, ETH_ALEN); skb_trim(skb, skb->len - ETH_ALEN); } #endif stats->rx_packets++; stats->rx_bytes += skb->len; #ifdef NOT_YET if (ieee->iw_mode == IW_MODE_MASTER && !wds && ieee->ap->bridge_packets) { if (dst[0] & 0x01) { /* copy multicast frame both to the higher layers and * to the wireless media */ ieee->ap->bridged_multicast++; skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2 == NULL) printk(KERN_DEBUG "%s: skb_clone failed for " "multicast frame\n", dev->name); } else if (hostap_is_sta_assoc(ieee->ap, dst)) { /* send frame directly to the associated STA using * wireless media and not passing to higher layers */ ieee->ap->bridged_unicast++; skb2 = skb; skb = NULL; } } if (skb2 != NULL) { /* send to wireless media */ skb2->dev = dev; skb2->protocol = __constant_htons(ETH_P_802_3); skb_reset_mac_header(skb2); skb_reset_network_header(skb2); /* skb2->network_header += ETH_HLEN; */ dev_queue_xmit(skb2); } #endif if (skb) { skb->protocol = eth_type_trans(skb, dev); memset(skb->cb, 0, sizeof(skb->cb)); skb->ip_summed = CHECKSUM_NONE; /* 802.11 crc not sufficient */ if (netif_rx(skb) == NET_RX_DROP) { /* netif_rx always succeeds, but it might drop * the packet. If it drops the packet, we log that * in our stats. */ IEEE80211_DEBUG_DROP ("RX: netif_rx dropped the packet\n"); stats->rx_dropped++; } } rx_exit: #ifdef NOT_YET if (sta) hostap_handle_sta_release(sta); #endif return 1; rx_dropped: stats->rx_dropped++; /* Returning 0 indicates to caller that we have not handled the SKB-- * so it is still allocated and can be used again by underlying * hardware as a DMA target */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames Reported by Chris Evans <scarybeasts@gmail.com>: > The summary is that an evil 80211 frame can crash out a victim's > machine. It only applies to drivers using the 80211 wireless code, and > only then to certain drivers (and even then depends on a card's > firmware not dropping a dubious packet). I must confess I'm not > keeping track of Linux wireless support, and the different protocol > stacks etc. > > Details are as follows: > > ieee80211_rx() does not explicitly check that "skb->len >= hdrlen". > There are other skb->len checks, but not enough to prevent a subtle > off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag > set. > > This leads to integer underflow and crash here: > > if (frag != 0) > flen -= hdrlen; > > (flen is subsequently used as a memcpy length parameter). How about this? Signed-off-by: John W. Linville <linville@tuxdriver.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int shmem_getpage(struct inode *inode, unsigned long idx, struct page **pagep, enum sgp_type sgp, int *type) { struct address_space *mapping = inode->i_mapping; struct shmem_inode_info *info = SHMEM_I(inode); struct shmem_sb_info *sbinfo; struct page *filepage = *pagep; struct page *swappage; swp_entry_t *entry; swp_entry_t swap; int error; if (idx >= SHMEM_MAX_INDEX) return -EFBIG; if (type) *type = 0; /* * Normally, filepage is NULL on entry, and either found * uptodate immediately, or allocated and zeroed, or read * in under swappage, which is then assigned to filepage. * But shmem_readpage and shmem_write_begin pass in a locked * filepage, which may be found not uptodate by other callers * too, and may need to be copied from the swappage read in. */ repeat: if (!filepage) filepage = find_lock_page(mapping, idx); if (filepage && PageUptodate(filepage)) goto done; error = 0; if (sgp == SGP_QUICK) goto failed; spin_lock(&info->lock); shmem_recalc_inode(inode); entry = shmem_swp_alloc(info, idx, sgp); if (IS_ERR(entry)) { spin_unlock(&info->lock); error = PTR_ERR(entry); goto failed; } swap = *entry; if (swap.val) { /* Look it up and read it in.. */ swappage = lookup_swap_cache(swap); if (!swappage) { shmem_swp_unmap(entry); /* here we actually do the io */ if (type && !(*type & VM_FAULT_MAJOR)) { __count_vm_event(PGMAJFAULT); *type |= VM_FAULT_MAJOR; } spin_unlock(&info->lock); swappage = shmem_swapin(info, swap, idx); if (!swappage) { spin_lock(&info->lock); entry = shmem_swp_alloc(info, idx, sgp); if (IS_ERR(entry)) error = PTR_ERR(entry); else { if (entry->val == swap.val) error = -ENOMEM; shmem_swp_unmap(entry); } spin_unlock(&info->lock); if (error) goto failed; goto repeat; } wait_on_page_locked(swappage); page_cache_release(swappage); goto repeat; } /* We have to do this with page locked to prevent races */ if (TestSetPageLocked(swappage)) { shmem_swp_unmap(entry); spin_unlock(&info->lock); wait_on_page_locked(swappage); page_cache_release(swappage); goto repeat; } if (PageWriteback(swappage)) { shmem_swp_unmap(entry); spin_unlock(&info->lock); wait_on_page_writeback(swappage); unlock_page(swappage); page_cache_release(swappage); goto repeat; } if (!PageUptodate(swappage)) { shmem_swp_unmap(entry); spin_unlock(&info->lock); unlock_page(swappage); page_cache_release(swappage); error = -EIO; goto failed; } if (filepage) { shmem_swp_set(info, entry, 0); shmem_swp_unmap(entry); delete_from_swap_cache(swappage); spin_unlock(&info->lock); copy_highpage(filepage, swappage); unlock_page(swappage); page_cache_release(swappage); flush_dcache_page(filepage); SetPageUptodate(filepage); set_page_dirty(filepage); swap_free(swap); } else if (!(error = move_from_swap_cache( swappage, idx, mapping))) { info->flags |= SHMEM_PAGEIN; shmem_swp_set(info, entry, 0); shmem_swp_unmap(entry); spin_unlock(&info->lock); filepage = swappage; swap_free(swap); } else { shmem_swp_unmap(entry); spin_unlock(&info->lock); unlock_page(swappage); page_cache_release(swappage); if (error == -ENOMEM) { /* let kswapd refresh zone for GFP_ATOMICs */ congestion_wait(WRITE, HZ/50); } goto repeat; } } else if (sgp == SGP_READ && !filepage) { shmem_swp_unmap(entry); filepage = find_get_page(mapping, idx); if (filepage && (!PageUptodate(filepage) || TestSetPageLocked(filepage))) { spin_unlock(&info->lock); wait_on_page_locked(filepage); page_cache_release(filepage); filepage = NULL; goto repeat; } spin_unlock(&info->lock); } else { shmem_swp_unmap(entry); sbinfo = SHMEM_SB(inode->i_sb); if (sbinfo->max_blocks) { spin_lock(&sbinfo->stat_lock); if (sbinfo->free_blocks == 0 || shmem_acct_block(info->flags)) { spin_unlock(&sbinfo->stat_lock); spin_unlock(&info->lock); error = -ENOSPC; goto failed; } sbinfo->free_blocks--; inode->i_blocks += BLOCKS_PER_PAGE; spin_unlock(&sbinfo->stat_lock); } else if (shmem_acct_block(info->flags)) { spin_unlock(&info->lock); error = -ENOSPC; goto failed; } if (!filepage) { spin_unlock(&info->lock); filepage = shmem_alloc_page(mapping_gfp_mask(mapping), info, idx); if (!filepage) { shmem_unacct_blocks(info->flags, 1); shmem_free_blocks(inode, 1); error = -ENOMEM; goto failed; } spin_lock(&info->lock); entry = shmem_swp_alloc(info, idx, sgp); if (IS_ERR(entry)) error = PTR_ERR(entry); else { swap = *entry; shmem_swp_unmap(entry); } if (error || swap.val || 0 != add_to_page_cache_lru( filepage, mapping, idx, GFP_ATOMIC)) { spin_unlock(&info->lock); page_cache_release(filepage); shmem_unacct_blocks(info->flags, 1); shmem_free_blocks(inode, 1); filepage = NULL; if (error) goto failed; goto repeat; } info->flags |= SHMEM_PAGEIN; } info->alloced++; spin_unlock(&info->lock); flush_dcache_page(filepage); SetPageUptodate(filepage); } done: if (*pagep != filepage) { *pagep = filepage; if (sgp != SGP_FAULT) unlock_page(filepage); } return 0; failed: if (*pagep != filepage) { unlock_page(filepage); page_cache_release(filepage); } return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage tmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in which shmem_getpage receives the page from its caller instead of allocating. We must cover this case by clear_highpage before SetPageUptodate, as before. Signed-off-by: Hugh Dickins <hugh@veritas.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info, sigset_t *set, struct pt_regs * regs) { struct rt_sigframe __user *frame; struct _fpstate __user *fp = NULL; int err = 0; struct task_struct *me = current; if (used_math()) { fp = get_stack(ka, regs, sizeof(struct _fpstate)); frame = (void __user *)round_down( (unsigned long)fp - sizeof(struct rt_sigframe), 16) - 8; if (!access_ok(VERIFY_WRITE, fp, sizeof(struct _fpstate))) goto give_sigsegv; if (save_i387(fp) < 0) err |= -1; } else frame = get_stack(ka, regs, sizeof(struct rt_sigframe)) - 8; if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame))) goto give_sigsegv; if (ka->sa.sa_flags & SA_SIGINFO) { err |= copy_siginfo_to_user(&frame->info, info); if (err) goto give_sigsegv; } /* Create the ucontext. */ err |= __put_user(0, &frame->uc.uc_flags); err |= __put_user(0, &frame->uc.uc_link); err |= __put_user(me->sas_ss_sp, &frame->uc.uc_stack.ss_sp); err |= __put_user(sas_ss_flags(regs->sp), &frame->uc.uc_stack.ss_flags); err |= __put_user(me->sas_ss_size, &frame->uc.uc_stack.ss_size); err |= setup_sigcontext(&frame->uc.uc_mcontext, regs, set->sig[0], me); err |= __put_user(fp, &frame->uc.uc_mcontext.fpstate); if (sizeof(*set) == 16) { __put_user(set->sig[0], &frame->uc.uc_sigmask.sig[0]); __put_user(set->sig[1], &frame->uc.uc_sigmask.sig[1]); } else err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set)); /* Set up to return from userspace. If provided, use a stub already in userspace. */ /* x86-64 should always use SA_RESTORER. */ if (ka->sa.sa_flags & SA_RESTORER) { err |= __put_user(ka->sa.sa_restorer, &frame->pretcode); } else { /* could use a vstub here */ goto give_sigsegv; } if (err) goto give_sigsegv; #ifdef DEBUG_SIG printk("%d old ip %lx old sp %lx old ax %lx\n", current->pid,regs->ip,regs->sp,regs->ax); #endif /* Set up registers for signal handler */ regs->di = sig; /* In case the signal handler was declared without prototypes */ regs->ax = 0; /* This also works for non SA_SIGINFO handlers because they expect the next argument after the signal number on the stack. */ regs->si = (unsigned long)&frame->info; regs->dx = (unsigned long)&frame->uc; regs->ip = (unsigned long) ka->sa.sa_handler; regs->sp = (unsigned long)frame; /* Set up the CS register to run signal handlers in 64-bit mode, even if the handler happens to be interrupting 32-bit code. */ regs->cs = __USER_CS; /* This, by contrast, has nothing to do with segment registers - see include/asm-x86_64/uaccess.h for details. */ set_fs(USER_DS); regs->flags &= ~X86_EFLAGS_TF; if (test_thread_flag(TIF_SINGLESTEP)) ptrace_notify(SIGTRAP); #ifdef DEBUG_SIG printk("SIG deliver (%s:%d): sp=%p pc=%lx ra=%p\n", current->comm, current->pid, frame, regs->ip, frame->pretcode); #endif return 0; give_sigsegv: force_sigsegv(sig, current); return -EFAULT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'x86: clear DF before calling signal handler The Linux kernel currently does not clear the direction flag before calling a signal handler, whereas the x86/x86-64 ABI requires that. Linux had this behavior/bug forever, but this becomes a real problem with gcc version 4.3, which assumes that the direction flag is correctly cleared at the entry of a function. This patches changes the setup_frame() functions to clear the direction before entering the signal handler. Signed-off-by: Aurelien Jarno <aurelien@aurel32.net> Signed-off-by: Ingo Molnar <mingo@elte.hu> Acked-by: H. Peter Anvin <hpa@zytor.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ipip6_rcv(struct sk_buff *skb) { struct iphdr *iph; struct ip_tunnel *tunnel; if (!pskb_may_pull(skb, sizeof(struct ipv6hdr))) goto out; iph = ip_hdr(skb); read_lock(&ipip6_lock); if ((tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), iph->saddr, iph->daddr)) != NULL) { secpath_reset(skb); skb->mac_header = skb->network_header; skb_reset_network_header(skb); IPCB(skb)->flags = 0; skb->protocol = htons(ETH_P_IPV6); skb->pkt_type = PACKET_HOST; if ((tunnel->dev->priv_flags & IFF_ISATAP) && !isatap_chksrc(skb, iph, tunnel)) { tunnel->stat.rx_errors++; read_unlock(&ipip6_lock); kfree_skb(skb); return 0; } tunnel->stat.rx_packets++; tunnel->stat.rx_bytes += skb->len; skb->dev = tunnel->dev; dst_release(skb->dst); skb->dst = NULL; nf_reset(skb); ipip6_ecn_decapsulate(iph, skb); netif_rx(skb); read_unlock(&ipip6_lock); return 0; } icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); kfree_skb(skb); read_unlock(&ipip6_lock); out: return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'sit: Add missing kfree_skb() on pskb_may_pull() failure. Noticed by Paul Marks <paul@pmarks.net>. Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int len, int write, int force, struct page **pages, struct vm_area_struct **vmas) { int i; unsigned int vm_flags; if (len <= 0) return 0; /* * Require read or write permissions. * If 'force' is set, we only require the "MAY" flags. */ vm_flags = write ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD); vm_flags &= force ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE); i = 0; do { struct vm_area_struct *vma; unsigned int foll_flags; vma = find_extend_vma(mm, start); if (!vma && in_gate_area(tsk, start)) { unsigned long pg = start & PAGE_MASK; struct vm_area_struct *gate_vma = get_gate_vma(tsk); pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (write) /* user gate pages are read-only */ return i ? : -EFAULT; if (pg > TASK_SIZE) pgd = pgd_offset_k(pg); else pgd = pgd_offset_gate(mm, pg); BUG_ON(pgd_none(*pgd)); pud = pud_offset(pgd, pg); BUG_ON(pud_none(*pud)); pmd = pmd_offset(pud, pg); if (pmd_none(*pmd)) return i ? : -EFAULT; pte = pte_offset_map(pmd, pg); if (pte_none(*pte)) { pte_unmap(pte); return i ? : -EFAULT; } if (pages) { struct page *page = vm_normal_page(gate_vma, start, *pte); pages[i] = page; if (page) get_page(page); } pte_unmap(pte); if (vmas) vmas[i] = gate_vma; i++; start += PAGE_SIZE; len--; continue; } if (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP)) || !(vm_flags & vma->vm_flags)) return i ? : -EFAULT; if (is_vm_hugetlb_page(vma)) { i = follow_hugetlb_page(mm, vma, pages, vmas, &start, &len, i, write); continue; } foll_flags = FOLL_TOUCH; if (pages) foll_flags |= FOLL_GET; if (!write && !(vma->vm_flags & VM_LOCKED) && (!vma->vm_ops || !vma->vm_ops->fault)) foll_flags |= FOLL_ANON; do { struct page *page; /* * If tsk is ooming, cut off its access to large memory * allocations. It has a pending SIGKILL, but it can't * be processed until returning to user space. */ if (unlikely(test_tsk_thread_flag(tsk, TIF_MEMDIE))) return -ENOMEM; if (write) foll_flags |= FOLL_WRITE; cond_resched(); while (!(page = follow_page(vma, start, foll_flags))) { int ret; ret = handle_mm_fault(mm, vma, start, foll_flags & FOLL_WRITE); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return i ? i : -ENOMEM; else if (ret & VM_FAULT_SIGBUS) return i ? i : -EFAULT; BUG(); } if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; /* * The VM_FAULT_WRITE bit tells us that * do_wp_page has broken COW when necessary, * even if maybe_mkwrite decided not to set * pte_write. We can thus safely do subsequent * page lookups as if they were reads. */ if (ret & VM_FAULT_WRITE) foll_flags &= ~FOLL_WRITE; cond_resched(); } if (IS_ERR(page)) return i ? i : PTR_ERR(page); if (pages) { pages[i] = page; flush_anon_page(vma, page, start); flush_dcache_page(page); } if (vmas) vmas[i] = vma; i++; start += PAGE_SIZE; len--; } while (len && start < vma->vm_end); } while (len); return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix ZERO_PAGE breakage with vmware Commit 89f5b7da2a6bad2e84670422ab8192382a5aeb9f ("Reinstate ZERO_PAGE optimization in 'get_user_pages()' and fix XIP") broke vmware, as reported by Jeff Chua: "This broke vmware 6.0.4. Jun 22 14:53:03.845: vmx| NOT_IMPLEMENTED /build/mts/release/bora-93057/bora/vmx/main/vmmonPosix.c:774" and the reason seems to be that there's an old bug in how we handle do FOLL_ANON on VM_SHARED areas in get_user_pages(), but since it only triggered if the whole page table was missing, nobody had apparently hit it before. The recent changes to 'follow_page()' made the FOLL_ANON logic trigger not just for whole missing page tables, but for individual pages as well, and exposed this problem. This fixes it by making the test for when FOLL_ANON is used more careful, and also makes the code easier to read and understand by moving the logic to a separate inline function. Reported-and-tested-by: Jeff Chua <jeff.chua.linux@gmail.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void diff_change(struct diff_options *options, unsigned old_mode, unsigned new_mode, const unsigned char *old_sha1, const unsigned char *new_sha1, const char *base, const char *path) { char concatpath[PATH_MAX]; struct diff_filespec *one, *two; if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode)) return; if (DIFF_OPT_TST(options, REVERSE_DIFF)) { unsigned tmp; const unsigned char *tmp_c; tmp = old_mode; old_mode = new_mode; new_mode = tmp; tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c; } if (!path) path = ""; sprintf(concatpath, "%s%s", base, path); if (options->prefix && strncmp(concatpath, options->prefix, options->prefix_length)) return; one = alloc_filespec(concatpath); two = alloc_filespec(concatpath); fill_filespec(one, old_sha1, old_mode); fill_filespec(two, new_sha1, new_mode); diff_queue(&diff_queued_diff, one, two); DIFF_OPT_SET(options, HAS_CHANGES); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff If PATH_MAX on your system is smaller than a path stored, it may cause buffer overflow and stack corruption in diff_addremove() and diff_change() functions when running git-diff Signed-off-by: Dmitry Potapov <dpotapov@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void syscall_vma_close(struct vm_area_struct *vma) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] i386 vDSO: use install_special_mapping This patch uses install_special_mapping for the i386 vDSO setup, consolidating duplicated code. Signed-off-by: Roland McGrath <roland@redhat.com> Cc: Ingo Molnar <mingo@elte.hu> Cc: Paul Mackerras <paulus@samba.org> Cc: Benjamin Herrenschmidt <benh@kernel.crashing.org> Cc: Andi Kleen <ak@suse.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab) { int i; jas_icctagtabent_t *tagtabent; if (tagtab->ents) { jas_free(tagtab->ents); tagtab->ents = 0; } if (jas_iccgetuint32(in, &tagtab->numents)) goto error; if (!(tagtab->ents = jas_malloc(tagtab->numents * sizeof(jas_icctagtabent_t)))) goto error; tagtabent = tagtab->ents; for (i = 0; i < JAS_CAST(long, tagtab->numents); ++i) { if (jas_iccgetuint32(in, &tagtabent->tag) || jas_iccgetuint32(in, &tagtabent->off) || jas_iccgetuint32(in, &tagtabent->len)) goto error; ++tagtabent; } return 0; error: if (tagtab->ents) { jas_free(tagtab->ents); tagtab->ents = 0; } return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; assert(m->buf_); if (!(buf = jas_realloc(m->buf_, bufsize * sizeof(unsigned char)))) { return -1; } m->buf_ = buf; m->bufsize_ = bufsize; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int rlvlno; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; jpc_dec_prc_t *prc; int bndno; jpc_tsfb_band_t *bnd; int bandno; jpc_dec_ccp_t *ccp; int prccnt; jpc_dec_cblk_t *cblk; int cblkcnt; uint_fast32_t tlprcxstart; uint_fast32_t tlprcystart; uint_fast32_t brprcxend; uint_fast32_t brprcyend; uint_fast32_t tlcbgxstart; uint_fast32_t tlcbgystart; uint_fast32_t brcbgxend; uint_fast32_t brcbgyend; uint_fast32_t cbgxstart; uint_fast32_t cbgystart; uint_fast32_t cbgxend; uint_fast32_t cbgyend; uint_fast32_t tlcblkxstart; uint_fast32_t tlcblkystart; uint_fast32_t brcblkxend; uint_fast32_t brcblkyend; uint_fast32_t cblkxstart; uint_fast32_t cblkystart; uint_fast32_t cblkxend; uint_fast32_t cblkyend; uint_fast32_t tmpxstart; uint_fast32_t tmpystart; uint_fast32_t tmpxend; uint_fast32_t tmpyend; jpc_dec_cp_t *cp; jpc_tsfb_band_t bnds[64]; jpc_pchg_t *pchg; int pchgno; jpc_dec_cmpt_t *cmpt; cp = tile->cp; tile->realmode = 0; if (cp->mctid == JPC_MCT_ICT) { tile->realmode = 1; } for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { ccp = &tile->cp->ccps[compno]; if (ccp->qmfbid == JPC_COX_INS) { tile->realmode = 1; } tcomp->numrlvls = ccp->numrlvls; if (!(tcomp->rlvls = jas_malloc(tcomp->numrlvls * sizeof(jpc_dec_rlvl_t)))) { return -1; } if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, cmpt->vstep)))) { return -1; } if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, tcomp->numrlvls - 1))) { return -1; } { jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds); } for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { rlvl->bands = 0; rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, tcomp->numrlvls - 1 - rlvlno); rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, tcomp->numrlvls - 1 - rlvlno); rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, tcomp->numrlvls - 1 - rlvlno); rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, tcomp->numrlvls - 1 - rlvlno); rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, rlvl->prcheightexpn) << rlvl->prcheightexpn; brprcxend = JPC_CEILDIVPOW2(rlvl->xend, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; brprcyend = JPC_CEILDIVPOW2(rlvl->yend, rlvl->prcheightexpn) << rlvl->prcheightexpn; rlvl->numhprcs = (brprcxend - tlprcxstart) >> rlvl->prcwidthexpn; rlvl->numvprcs = (brprcyend - tlprcystart) >> rlvl->prcheightexpn; rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { rlvl->bands = 0; rlvl->numprcs = 0; rlvl->numhprcs = 0; rlvl->numvprcs = 0; continue; } if (!rlvlno) { tlcbgxstart = tlprcxstart; tlcbgystart = tlprcystart; brcbgxend = brprcxend; brcbgyend = brprcyend; rlvl->cbgwidthexpn = rlvl->prcwidthexpn; rlvl->cbgheightexpn = rlvl->prcheightexpn; } else { tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; } rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, rlvl->cbgwidthexpn); rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, rlvl->cbgheightexpn); rlvl->numbands = (!rlvlno) ? 1 : 3; if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_dec_band_t)))) { return -1; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); bnd = &bnds[bndno]; band->orient = bnd->orient; band->stepsize = ccp->stepsizes[bndno]; band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, tcomp->numrlvls - 1, rlvlno, band->orient); band->absstepsize = jpc_calcabsstepsize(band->stepsize, cmpt->prec + band->analgain); band->numbps = ccp->numguardbits + JPC_QCX_GETEXPN(band->stepsize) - 1; band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? (JPC_PREC - 1 - band->numbps) : ccp->roishift; band->data = 0; band->prcs = 0; if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { continue; } if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend); jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); assert(rlvl->numprcs); if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_dec_prc_t)))) { return -1; } /************************************************/ cbgxstart = tlcbgxstart; cbgystart = tlcbgystart; for (prccnt = rlvl->numprcs, prc = band->prcs; prccnt > 0; --prccnt, ++prc) { cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data))); prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data))); prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data))); prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data))); if (prc->xend > prc->xstart && prc->yend > prc->ystart) { tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; brcblkxend = JPC_CEILDIVPOW2(prc->xend, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; brcblkyend = JPC_CEILDIVPOW2(prc->yend, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; prc->numhcblks = (brcblkxend - tlcblkxstart) >> rlvl->cblkwidthexpn; prc->numvcblks = (brcblkyend - tlcblkystart) >> rlvl->cblkheightexpn; prc->numcblks = prc->numhcblks * prc->numvcblks; assert(prc->numcblks > 0); if (!(prc->incltagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->numimsbstagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_dec_cblk_t)))) { return -1; } cblkxstart = cbgxstart; cblkystart = cbgystart; for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) { cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); tmpxstart = JAS_MAX(cblkxstart, prc->xstart); tmpystart = JAS_MAX(cblkystart, prc->ystart); tmpxend = JAS_MIN(cblkxend, prc->xend); tmpyend = JAS_MIN(cblkyend, prc->yend); if (tmpxend > tmpxstart && tmpyend > tmpystart) { cblk->firstpassno = -1; cblk->mqdec = 0; cblk->nulldec = 0; cblk->flags = 0; cblk->numpasses = 0; cblk->segs.head = 0; cblk->segs.tail = 0; cblk->curseg = 0; cblk->numimsbs = 0; cblk->numlenbits = 3; cblk->flags = 0; if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend); ++cblk; --cblkcnt; } cblkxstart += 1 << rlvl->cblkwidthexpn; if (cblkxstart >= cbgxend) { cblkxstart = cbgxstart; cblkystart += 1 << rlvl->cblkheightexpn; } } } else { prc->cblks = 0; prc->incltagtree = 0; prc->numimsbstagtree = 0; } cbgxstart += 1 << rlvl->cbgwidthexpn; if (cbgxstart >= brcbgxend) { cbgxstart = tlcbgxstart; cbgystart += 1 << rlvl->cbgheightexpn; } } /********************************************/ } } } if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { return -1; } for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); ++pchgno) { pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); assert(pchg); jpc_pi_addpchg(tile->pi, pchg); } jpc_pi_init(tile->pi); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp, jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos) { uint_fast16_t bandno; uint_fast16_t gblbandno; uint_fast16_t rlvlno; jpc_tsfb_band_t *bandinfo; jpc_enc_tcmpt_t *tcmpt; uint_fast32_t prcno; jpc_enc_prc_t *prc; tcmpt = rlvl->tcmpt; band->data = 0; band->prcs = 0; band->rlvl = rlvl; /* Deduce the resolution level and band number. */ rlvlno = rlvl - rlvl->tcmpt->rlvls; bandno = band - rlvl->bands; gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); bandinfo = &bandinfos[gblbandno]; if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) { if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { goto error; } jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart, bandinfo->locystart, bandinfo->locxend, bandinfo->locyend); jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart); } band->orient = bandinfo->orient; band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno, band->orient); band->numbps = 0; band->absstepsize = 0; band->stepsize = 0; band->synweight = bandinfo->synenergywt; if (band->data) { if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_enc_prc_t)))) { goto error; } for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { prc->cblks = 0; prc->incltree = 0; prc->nlibtree = 0; prc->savincltree = 0; prc->savnlibtree = 0; prc->band = band; } for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { if (!prc_create(prc, cp, band)) { goto error; } } } return band; error: band_destroy(band); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg) { int i; int newmaxpchgs; jpc_pchg_t **newpchgs; if (pchgno < 0) { pchgno = pchglist->numpchgs; } if (pchglist->numpchgs >= pchglist->maxpchgs) { newmaxpchgs = pchglist->maxpchgs + 128; if (!(newpchgs = jas_realloc(pchglist->pchgs, newmaxpchgs * sizeof(jpc_pchg_t *)))) { return -1; } pchglist->maxpchgs = newmaxpchgs; pchglist->pchgs = newpchgs; } for (i = pchglist->numpchgs; i > pchgno; --i) { pchglist->pchgs[i] = pchglist->pchgs[i - 1]; } pchglist->pchgs[pchgno] = pchg; ++pchglist->numpchgs; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void *jas_calloc(size_t nmemb, size_t size) { void *ptr; size_t n; n = nmemb * size; if (!(ptr = jas_malloc(n * sizeof(char)))) { return 0; } memset(ptr, 0, n); return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jas_stream_t *jas_stream_memopen(char *buf, int bufsize) { jas_stream_t *stream; jas_stream_memobj_t *obj; if (!(stream = jas_stream_create())) { return 0; } /* A stream associated with a memory buffer is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Since the stream data is already resident in memory, buffering is not necessary. */ /* But... It still may be faster to use buffering anyways. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a memory stream. */ stream->ops_ = &jas_stream_memops; /* Allocate memory for the underlying memory stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { jas_stream_destroy(stream); return 0; } stream->obj_ = (void *) obj; /* Initialize a few important members of the memory stream object. */ obj->myalloc_ = 0; obj->buf_ = 0; /* If the buffer size specified is nonpositive, then the buffer is allocated internally and automatically grown as needed. */ if (bufsize <= 0) { obj->bufsize_ = 1024; obj->growable_ = 1; } else { obj->bufsize_ = bufsize; obj->growable_ = 0; } if (buf) { obj->buf_ = (unsigned char *) buf; } else { obj->buf_ = jas_malloc(obj->bufsize_ * sizeof(char)); obj->myalloc_ = 1; } if (!obj->buf_) { jas_stream_close(stream); return 0; } if (bufsize > 0 && buf) { /* If a buffer was supplied by the caller and its length is positive, make the associated buffer data appear in the stream initially. */ obj->len_ = bufsize; } else { /* The stream is initially empty. */ obj->len_ = 0; } obj->pos_ = 0; return stream; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: generic_file_splice_write_nolock(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { struct address_space *mapping = out->f_mapping; struct inode *inode = mapping->host; ssize_t ret; int err; ret = __splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_file); if (ret > 0) { *ppos += ret; /* * If file or inode is SYNC and we actually wrote some data, * sync it. */ if (unlikely((out->f_flags & O_SYNC) || IS_SYNC(inode))) { err = generic_osync_inode(inode, mapping, OSYNC_METADATA|OSYNC_DATA); if (err) ret = err; } } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] Remove SUID when splicing into an inode Originally from Mark Fasheh <mark.fasheh@oracle.com> generic_file_splice_write() does not remove S_ISUID or S_ISGID. This is inconsistent with the way we generally write to files. Signed-off-by: Mark Fasheh <mark.fasheh@oracle.com> Signed-off-by: Jens Axboe <jens.axboe@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int sctp_process_init(struct sctp_association *asoc, sctp_cid_t cid, const union sctp_addr *peer_addr, sctp_init_chunk_t *peer_init, gfp_t gfp) { union sctp_params param; struct sctp_transport *transport; struct list_head *pos, *temp; char *cookie; /* We must include the address that the INIT packet came from. * This is the only address that matters for an INIT packet. * When processing a COOKIE ECHO, we retrieve the from address * of the INIT from the cookie. */ /* This implementation defaults to making the first transport * added as the primary transport. The source address seems to * be a a better choice than any of the embedded addresses. */ if (peer_addr) { if(!sctp_assoc_add_peer(asoc, peer_addr, gfp, SCTP_ACTIVE)) goto nomem; } /* Process the initialization parameters. */ sctp_walk_params(param, peer_init, init_hdr.params) { if (!sctp_process_param(asoc, param, peer_addr, gfp)) goto clean_up; } /* AUTH: After processing the parameters, make sure that we * have all the required info to potentially do authentications. */ if (asoc->peer.auth_capable && (!asoc->peer.peer_random || !asoc->peer.peer_hmacs)) asoc->peer.auth_capable = 0; /* In a non-backward compatible mode, if the peer claims * support for ADD-IP but not AUTH, the ADD-IP spec states * that we MUST ABORT the association. Section 6. The section * also give us an option to silently ignore the packet, which * is what we'll do here. */ if (!sctp_addip_noauth && (asoc->peer.asconf_capable && !asoc->peer.auth_capable)) { asoc->peer.addip_disabled_mask |= (SCTP_PARAM_ADD_IP | SCTP_PARAM_DEL_IP | SCTP_PARAM_SET_PRIMARY); asoc->peer.asconf_capable = 0; goto clean_up; } /* Walk list of transports, removing transports in the UNKNOWN state. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); if (transport->state == SCTP_UNKNOWN) { sctp_assoc_rm_peer(asoc, transport); } } /* The fixed INIT headers are always in network byte * order. */ asoc->peer.i.init_tag = ntohl(peer_init->init_hdr.init_tag); asoc->peer.i.a_rwnd = ntohl(peer_init->init_hdr.a_rwnd); asoc->peer.i.num_outbound_streams = ntohs(peer_init->init_hdr.num_outbound_streams); asoc->peer.i.num_inbound_streams = ntohs(peer_init->init_hdr.num_inbound_streams); asoc->peer.i.initial_tsn = ntohl(peer_init->init_hdr.initial_tsn); /* Apply the upper bounds for output streams based on peer's * number of inbound streams. */ if (asoc->c.sinit_num_ostreams > ntohs(peer_init->init_hdr.num_inbound_streams)) { asoc->c.sinit_num_ostreams = ntohs(peer_init->init_hdr.num_inbound_streams); } if (asoc->c.sinit_max_instreams > ntohs(peer_init->init_hdr.num_outbound_streams)) { asoc->c.sinit_max_instreams = ntohs(peer_init->init_hdr.num_outbound_streams); } /* Copy Initiation tag from INIT to VT_peer in cookie. */ asoc->c.peer_vtag = asoc->peer.i.init_tag; /* Peer Rwnd : Current calculated value of the peer's rwnd. */ asoc->peer.rwnd = asoc->peer.i.a_rwnd; /* Copy cookie in case we need to resend COOKIE-ECHO. */ cookie = asoc->peer.cookie; if (cookie) { asoc->peer.cookie = kmemdup(cookie, asoc->peer.cookie_len, gfp); if (!asoc->peer.cookie) goto clean_up; } /* RFC 2960 7.2.1 The initial value of ssthresh MAY be arbitrarily * high (for example, implementations MAY use the size of the receiver * advertised window). */ list_for_each_entry(transport, &asoc->peer.transport_addr_list, transports) { transport->ssthresh = asoc->peer.i.a_rwnd; } /* Set up the TSN tracking pieces. */ sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_SIZE, asoc->peer.i.initial_tsn); /* RFC 2960 6.5 Stream Identifier and Stream Sequence Number * * The stream sequence number in all the streams shall start * from 0 when the association is established. Also, when the * stream sequence number reaches the value 65535 the next * stream sequence number shall be set to 0. */ /* Allocate storage for the negotiated streams if it is not a temporary * association. */ if (!asoc->temp) { int error; asoc->ssnmap = sctp_ssnmap_new(asoc->c.sinit_max_instreams, asoc->c.sinit_num_ostreams, gfp); if (!asoc->ssnmap) goto clean_up; error = sctp_assoc_set_id(asoc, gfp); if (error) goto clean_up; } /* ADDIP Section 4.1 ASCONF Chunk Procedures * * When an endpoint has an ASCONF signaled change to be sent to the * remote endpoint it should do the following: * ... * A2) A serial number should be assigned to the Chunk. The serial * number should be a monotonically increasing number. All serial * numbers are defined to be initialized at the start of the * association to the same value as the Initial TSN. */ asoc->peer.addip_serial = asoc->peer.i.initial_tsn - 1; return 1; clean_up: /* Release the transport structures. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); list_del_init(pos); sctp_transport_free(transport); } asoc->peer.transport_count = 0; nomem: return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'sctp: Fix oops when INIT-ACK indicates that peer doesn't support AUTH If INIT-ACK is received with SupportedExtensions parameter which indicates that the peer does not support AUTH, the packet will be silently ignore, and sctp_process_init() do cleanup all of the transports in the association. When T1-Init timer is expires, OOPS happen while we try to choose a different init transport. The solution is to only clean up the non-active transports, i.e the ones that the peer added. However, that introduces a problem with sctp_connectx(), because we don't mark the proper state for the transports provided by the user. So, we'll simply mark user-provided transports as ACTIVE. That will allow INIT retransmissions to work properly in the sctp_connectx() context and prevent the crash. Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void destroy_watch(struct inotify_watch *watch) { struct audit_chunk *chunk = container_of(watch, struct audit_chunk, watch); free_chunk(chunk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int blk_fill_sghdr_rq(struct request_queue *q, struct request *rq, struct sg_io_hdr *hdr, fmode_t mode) { if (copy_from_user(rq->cmd, hdr->cmdp, hdr->cmd_len)) return -EFAULT; if (blk_verify_command(&q->cmd_filter, rq->cmd, mode & FMODE_WRITE)) return -EPERM; /* * fill in request structure */ rq->cmd_len = hdr->cmd_len; rq->cmd_type = REQ_TYPE_BLOCK_PC; rq->timeout = msecs_to_jiffies(hdr->timeout); if (!rq->timeout) rq->timeout = q->sg_timeout; if (!rq->timeout) rq->timeout = BLK_DEFAULT_SG_TIMEOUT; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Enforce a minimum SG_IO timeout There's no point in having too short SG_IO timeouts, since if the command does end up timing out, we'll end up through the reset sequence that is several seconds long in order to abort the command that timed out. As a result, shorter timeouts than a few seconds simply do not make sense, as the recovery would be longer than the timeout itself. Add a BLK_MIN_SG_TIMEOUT to match the existign BLK_DEFAULT_SG_TIMEOUT. Suggested-by: Alan Cox <alan@lxorguk.ukuu.org.uk> Acked-by: Tejun Heo <tj@kernel.org> Acked-by: Jens Axboe <jens.axboe@oracle.com> Cc: Jeff Garzik <jeff@garzik.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ms_adpcm_run_pull (_AFmoduleinst *module) { ms_adpcm_data *d = (ms_adpcm_data *) module->modspec; AFframecount frames2read = module->outc->nframes; AFframecount nframes = 0; int i, framesPerBlock, blockCount; ssize_t blocksRead, bytesDecoded; framesPerBlock = d->samplesPerBlock / d->track->f.channelCount; assert(module->outc->nframes % framesPerBlock == 0); blockCount = module->outc->nframes / framesPerBlock; /* Read the compressed frames. */ blocksRead = af_fread(module->inc->buf, d->blockAlign, blockCount, d->fh); /* Decompress into module->outc. */ for (i=0; i<blockCount; i++) { bytesDecoded = ms_adpcm_decode_block(d, (uint8_t *) module->inc->buf + i * d->blockAlign, (int16_t *) module->outc->buf + i * d->samplesPerBlock); nframes += framesPerBlock; } d->track->nextfframe += nframes; if (blocksRead > 0) d->track->fpos_next_frame += blocksRead * d->blockAlign; assert(af_ftell(d->fh) == d->track->fpos_next_frame); /* If we got EOF from read, then we return the actual amount read. Complain only if there should have been more frames in the file. */ if (d->track->totalfframes != -1 && nframes != frames2read) { /* Report error if we haven't already */ if (d->track->filemodhappy) { _af_error(AF_BAD_READ, "file missing data -- read %d frames, should be %d", d->track->nextfframe, d->track->totalfframes); d->track->filemodhappy = AF_FALSE; } } module->outc->nframes = nframes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ms_adpcm_reset1 (_AFmoduleinst *i) { ms_adpcm_data *d = (ms_adpcm_data *) i->modspec; AFframecount nextTrackFrame; int framesPerBlock; framesPerBlock = d->samplesPerBlock / d->track->f.channelCount; nextTrackFrame = d->track->nextfframe; d->track->nextfframe = (nextTrackFrame / framesPerBlock) * framesPerBlock; d->framesToIgnore = nextTrackFrame - d->track->nextfframe; /* postroll = frames2ignore */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __acquires(kernel_lock) { struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -EINVAL; int blocksize; int db_count; int i; int needs_recovery, has_huge_files; int features; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; unlock_kernel(); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { printk(KERN_ERR "EXT4-fs: unable to set blocksize\n"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { printk(KERN_ERR "EXT4-fs: unable to read superblock\n"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) set_opt(sbi->s_mount_opt, GRPID); if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT4_FS_XATTR if (def_mount_opts & EXT4_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (def_mount_opts & EXT4_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) sbi->s_mount_opt |= EXT4_MOUNT_JOURNAL_DATA; else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) sbi->s_mount_opt |= EXT4_MOUNT_ORDERED_DATA; else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) sbi->s_mount_opt |= EXT4_MOUNT_WRITEBACK_DATA; if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; set_opt(sbi->s_mount_opt, RESERVATION); set_opt(sbi->s_mount_opt, BARRIER); /* * turn on extents feature by default in ext4 filesystem * only if feature flag already set by mkfs or tune2fs. * Use -o noextents to turn it off */ if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) set_opt(sbi->s_mount_opt, EXTENTS); else ext4_warning(sb, __func__, "extents feature not enabled on this filesystem, " "use tune2fs."); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ set_opt(sbi->s_mount_opt, DELALLOC); if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | ((sbi->s_mount_opt & EXT4_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) printk(KERN_WARNING "EXT4-fs warning: feature flags set on rev 0 fs, " "running e2fsck is recommended\n"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ features = EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT4_FEATURE_INCOMPAT_SUPP); if (features) { printk(KERN_ERR "EXT4-fs: %s: couldn't mount because of " "unsupported optional features (%x).\n", sb->s_id, (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) & ~EXT4_FEATURE_INCOMPAT_SUPP)); goto failed_mount; } features = EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT4_FEATURE_RO_COMPAT_SUPP); if (!(sb->s_flags & MS_RDONLY) && features) { printk(KERN_ERR "EXT4-fs: %s: couldn't mount RDWR because of " "unsupported optional features (%x).\n", sb->s_id, (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) & ~EXT4_FEATURE_RO_COMPAT_SUPP)); goto failed_mount; } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); if (has_huge_files) { /* * Large file size enabled file system can only be * mount if kernel is build with CONFIG_LBD */ if (sizeof(root->i_blocks) < sizeof(u64) && !(sb->s_flags & MS_RDONLY)) { printk(KERN_ERR "EXT4-fs: %s: Filesystem with huge " "files cannot be mounted read-write " "without CONFIG_LBD.\n", sb->s_id); goto failed_mount; } } blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { printk(KERN_ERR "EXT4-fs: Unsupported filesystem blocksize %d on %s.\n", blocksize, sb->s_id); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { printk(KERN_ERR "EXT4-fs: bad block size %d.\n", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { printk(KERN_ERR "EXT4-fs: Can't read superblock on 2nd try.\n"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { printk(KERN_ERR "EXT4-fs: Magic mismatch, very weird !\n"); goto failed_mount; } } sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { printk(KERN_ERR "EXT4-fs: unsupported inode size: %d\n", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { printk(KERN_ERR "EXT4-fs: unsupported descriptor size %lu\n", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { printk(KERN_ERR "EXT4-fs: #blocks per group too big: %lu\n", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { printk(KERN_ERR "EXT4-fs: #inodes per group too big: %lu\n", sbi->s_inodes_per_group); goto failed_mount; } if (ext4_blocks_count(es) > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) { printk(KERN_ERR "EXT4-fs: filesystem on %s:" " too large to mount safely\n", sb->s_id); if (sizeof(sector_t) < 8) printk(KERN_WARNING "EXT4-fs: CONFIG_LBD not " "enabled\n"); goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* ensure blocks_count calculation below doesn't sign-extend */ if (ext4_blocks_count(es) + EXT4_BLOCKS_PER_GROUP(sb) < le32_to_cpu(es->s_first_data_block) + 1) { printk(KERN_WARNING "EXT4-fs: bad geometry: block count %llu, " "first data block %u, blocks per group %lu\n", ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); sbi->s_groups_count = blocks_count; db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { printk(KERN_ERR "EXT4-fs: not enough memory\n"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); if (sbi->s_proc) proc_create_data("inode_readahead_blks", 0644, sbi->s_proc, &ext4_ui_proc_fops, &sbi->s_inode_readahead_blks); #endif bgl_lock_init(&sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { printk(KERN_ERR "EXT4-fs: " "can't read group descriptor %d\n", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb)) { printk(KERN_ERR "EXT4-fs: group descriptors corrupted!\n"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { printk(KERN_ERR "EXT4-fs: unable to initialize " "flex_bg meta info!\n"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { printk(KERN_ERR "EXT4-fs: insufficient memory\n"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); /* * set up enough so that it can read an inode */ sb->s_op = &ext4_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; if (!(sb->s_flags & MS_RDONLY) && EXT4_SB(sb)->s_journal->j_failed_commit) { printk(KERN_CRIT "EXT4-fs error (device %s): " "ext4_fill_super: Journal transaction " "%u is corrupt\n", sb->s_id, EXT4_SB(sb)->s_journal->j_failed_commit); if (test_opt(sb, ERRORS_RO)) { printk(KERN_CRIT "Mounting filesystem read-only\n"); sb->s_flags |= MS_RDONLY; EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS; es->s_state |= cpu_to_le16(EXT4_ERROR_FS); } if (test_opt(sb, ERRORS_PANIC)) { EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS; es->s_state |= cpu_to_le16(EXT4_ERROR_FS); ext4_commit_super(sb, es, 1); goto failed_mount4; } } } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { printk(KERN_ERR "EXT4-fs: required journal recovery " "suppressed and not mounted read-only\n"); goto failed_mount4; } else { clear_opt(sbi->s_mount_opt, DATA_FLAGS); set_opt(sbi->s_mount_opt, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { printk(KERN_ERR "ext4: Failed to set 64-bit journal feature\n"); goto failed_mount4; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sbi->s_mount_opt, ORDERED_DATA); else set_opt(sbi->s_mount_opt, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { printk(KERN_ERR "EXT4-fs: Journal does not support " "requested data journaling mode\n"); goto failed_mount4; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); no_journal: if (test_opt(sb, NOBH)) { if (!(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)) { printk(KERN_WARNING "EXT4-fs: Ignoring nobh option - " "its supported only with writeback mode\n"); clear_opt(sbi->s_mount_opt, NOBH); } } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { printk(KERN_ERR "EXT4-fs: get root inode failed\n"); ret = PTR_ERR(root); goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); printk(KERN_ERR "EXT4-fs: corrupt root inode, run e2fsck\n"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { printk(KERN_ERR "EXT4-fs: get root dentry failed\n"); iput(root); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; printk(KERN_INFO "EXT4-fs: required extra inode space not" "available.\n"); } if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) { printk(KERN_WARNING "EXT4-fs: Ignoring delalloc option - " "requested data journaling mode\n"); clear_opt(sbi->s_mount_opt, DELALLOC); } else if (test_opt(sb, DELALLOC)) printk(KERN_INFO "EXT4-fs: delayed allocation enabled\n"); ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { printk(KERN_ERR "EXT4-fs: failed to initalize mballoc (%d)\n", err); goto failed_mount4; } /* * akpm: core read_super() calls in here with the superblock locked. * That deadlocks, because orphan cleanup needs to lock the superblock * in numerous places. Here we just pop the lock - it's relatively * harmless, because we are now ready to accept write_super() requests, * and aviro says that's the only reason for hanging onto the * superblock lock. */ EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { printk(KERN_INFO "EXT4-fs: recovery complete.\n"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = " journalled data mode"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = " ordered data mode"; else descr = " writeback data mode"; } else descr = "out journal"; printk(KERN_INFO "EXT4-fs: mounted filesystem %s with%s\n", sb->s_id, descr); lock_kernel(); return 0; cantfind_ext4: if (!silent) printk(KERN_ERR "VFS: Can't find ext4 filesystem on dev %s.\n", sb->s_id); goto failed_mount; failed_mount4: printk(KERN_ERR "EXT4-fs (device %s): mount failed\n", sb->s_id); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry("inode_readahead_blks", sbi->s_proc); remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi); lock_kernel(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'ext4: Add sanity checks for the superblock before mounting the filesystem This avoids insane superblock configurations that could lead to kernel oops due to null pointer derefences. http://bugzilla.kernel.org/show_bug.cgi?id=12371 Thanks to David Maciejak at Fortinet's FortiGuard Global Security Research Team who discovered this bug independently (but at approximately the same time) as Thiemo Nagel, who submitted the patch. Signed-off-by: Thiemo Nagel <thiemo.nagel@ph.tum.de> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Cc: stable@kernel.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int nfs4_path_walk(struct nfs_server *server, struct nfs_fh *mntfh, const char *path) { struct nfs_fsinfo fsinfo; struct nfs_fattr fattr; struct nfs_fh lastfh; struct qstr name; int ret; dprintk("--> nfs4_path_walk(,,%s)\n", path); fsinfo.fattr = &fattr; nfs_fattr_init(&fattr); /* Eat leading slashes */ while (*path == '/') path++; /* Start by getting the root filehandle from the server */ ret = server->nfs_client->rpc_ops->getroot(server, mntfh, &fsinfo); if (ret < 0) { dprintk("nfs4_get_root: getroot error = %d\n", -ret); return ret; } if (fattr.type != NFDIR) { printk(KERN_ERR "nfs4_get_root:" " getroot encountered non-directory\n"); return -ENOTDIR; } /* FIXME: It is quite valid for the server to return a referral here */ if (fattr.valid & NFS_ATTR_FATTR_V4_REFERRAL) { printk(KERN_ERR "nfs4_get_root:" " getroot obtained referral\n"); return -EREMOTE; } next_component: dprintk("Next: %s\n", path); /* extract the next bit of the path */ if (!*path) goto path_walk_complete; name.name = path; while (*path && *path != '/') path++; name.len = path - (const char *) name.name; eat_dot_dir: while (*path == '/') path++; if (path[0] == '.' && (path[1] == '/' || !path[1])) { path += 2; goto eat_dot_dir; } /* FIXME: Why shouldn't the user be able to use ".." in the path? */ if (path[0] == '.' && path[1] == '.' && (path[2] == '/' || !path[2]) ) { printk(KERN_ERR "nfs4_get_root:" " Mount path contains reference to \"..\"\n"); return -EINVAL; } /* lookup the next FH in the sequence */ memcpy(&lastfh, mntfh, sizeof(lastfh)); dprintk("LookupFH: %*.*s [%s]\n", name.len, name.len, name.name, path); ret = server->nfs_client->rpc_ops->lookupfh(server, &lastfh, &name, mntfh, &fattr); if (ret < 0) { dprintk("nfs4_get_root: getroot error = %d\n", -ret); return ret; } if (fattr.type != NFDIR) { printk(KERN_ERR "nfs4_get_root:" " lookupfh encountered non-directory\n"); return -ENOTDIR; } /* FIXME: Referrals are quite valid here too */ if (fattr.valid & NFS_ATTR_FATTR_V4_REFERRAL) { printk(KERN_ERR "nfs4_get_root:" " lookupfh obtained referral\n"); return -EREMOTE; } goto next_component; path_walk_complete: memcpy(&server->fsid, &fattr.fsid, sizeof(server->fsid)); dprintk("<-- nfs4_path_walk() = 0\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup() It doesn't look as if the NFS file name limit is being initialised correctly in the struct nfs_server. Make sure that we limit whatever is being set in nfs_probe_fsinfo() and nfs_init_server(). Also ensure that readdirplus and nfs4_path_walk respect our file name limits. Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: size_t util_path_encode(char *s, size_t len) { char t[(len * 3)+1]; size_t i, j; for (i = 0, j = 0; s[i] != '\0'; i++) { if (s[i] == '/') { memcpy(&t[j], "\\x2f", 4); j += 4; } else if (s[i] == '\\') { memcpy(&t[j], "\\x5c", 4); j += 4; } else { t[j] = s[i]; j++; } } if (len == 0) return j; i = (j < len - 1) ? j : len - 1; memcpy(s, t, i); s[i] = '\0'; return j; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'path_encode: fix max length calculation Sebastian Krahmer wrote: > it should reserve 4 times not 3 times len :)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat, unsigned char *data, struct list_head *auth_tok_list, struct ecryptfs_auth_tok **new_auth_tok, size_t *packet_size, size_t max_packet_size) { size_t body_size; struct ecryptfs_auth_tok_list_item *auth_tok_list_item; size_t length_size; int rc = 0; (*packet_size) = 0; (*new_auth_tok) = NULL; /** *This format is inspired by OpenPGP; see RFC 2440 * packet tag 3 * * Tag 3 identifier (1 byte) * Max Tag 3 packet size (max 3 bytes) * Version (1 byte) * Cipher code (1 byte) * S2K specifier (1 byte) * Hash identifier (1 byte) * Salt (ECRYPTFS_SALT_SIZE) * Hash iterations (1 byte) * Encrypted key (arbitrary) * * (ECRYPTFS_SALT_SIZE + 7) minimum packet size */ if (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) { printk(KERN_ERR "Max packet size too large\n"); rc = -EINVAL; goto out; } if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) { printk(KERN_ERR "First byte != 0x%.2x; invalid packet\n", ECRYPTFS_TAG_3_PACKET_TYPE); rc = -EINVAL; goto out; } /* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or * at end of function upon failure */ auth_tok_list_item = kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL); if (!auth_tok_list_item) { printk(KERN_ERR "Unable to allocate memory\n"); rc = -ENOMEM; goto out; } (*new_auth_tok) = &auth_tok_list_item->auth_tok; rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size, &length_size); if (rc) { printk(KERN_WARNING "Error parsing packet length; rc = [%d]\n", rc); goto out_free; } if (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) { printk(KERN_WARNING "Invalid body size ([%td])\n", body_size); rc = -EINVAL; goto out_free; } (*packet_size) += length_size; if (unlikely((*packet_size) + body_size > max_packet_size)) { printk(KERN_ERR "Packet size exceeds max\n"); rc = -EINVAL; goto out_free; } (*new_auth_tok)->session_key.encrypted_key_size = (body_size - (ECRYPTFS_SALT_SIZE + 5)); if (unlikely(data[(*packet_size)++] != 0x04)) { printk(KERN_WARNING "Unknown version number [%d]\n", data[(*packet_size) - 1]); rc = -EINVAL; goto out_free; } ecryptfs_cipher_code_to_string(crypt_stat->cipher, (u16)data[(*packet_size)]); /* A little extra work to differentiate among the AES key * sizes; see RFC2440 */ switch(data[(*packet_size)++]) { case RFC2440_CIPHER_AES_192: crypt_stat->key_size = 24; break; default: crypt_stat->key_size = (*new_auth_tok)->session_key.encrypted_key_size; } ecryptfs_init_crypt_ctx(crypt_stat); if (unlikely(data[(*packet_size)++] != 0x03)) { printk(KERN_WARNING "Only S2K ID 3 is currently supported\n"); rc = -ENOSYS; goto out_free; } /* TODO: finish the hash mapping */ switch (data[(*packet_size)++]) { case 0x01: /* See RFC2440 for these numbers and their mappings */ /* Choose MD5 */ memcpy((*new_auth_tok)->token.password.salt, &data[(*packet_size)], ECRYPTFS_SALT_SIZE); (*packet_size) += ECRYPTFS_SALT_SIZE; /* This conversion was taken straight from RFC2440 */ (*new_auth_tok)->token.password.hash_iterations = ((u32) 16 + (data[(*packet_size)] & 15)) << ((data[(*packet_size)] >> 4) + 6); (*packet_size)++; /* Friendly reminder: * (*new_auth_tok)->session_key.encrypted_key_size = * (body_size - (ECRYPTFS_SALT_SIZE + 5)); */ memcpy((*new_auth_tok)->session_key.encrypted_key, &data[(*packet_size)], (*new_auth_tok)->session_key.encrypted_key_size); (*packet_size) += (*new_auth_tok)->session_key.encrypted_key_size; (*new_auth_tok)->session_key.flags &= ~ECRYPTFS_CONTAINS_DECRYPTED_KEY; (*new_auth_tok)->session_key.flags |= ECRYPTFS_CONTAINS_ENCRYPTED_KEY; (*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */ break; default: ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: " "[%d]\n", data[(*packet_size) - 1]); rc = -ENOSYS; goto out_free; } (*new_auth_tok)->token_type = ECRYPTFS_PASSWORD; /* TODO: Parametarize; we might actually want userspace to * decrypt the session key. */ (*new_auth_tok)->session_key.flags &= ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT); (*new_auth_tok)->session_key.flags &= ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT); list_add(&auth_tok_list_item->list, auth_tok_list); goto out; out_free: (*new_auth_tok) = NULL; memset(auth_tok_list_item, 0, sizeof(struct ecryptfs_auth_tok_list_item)); kmem_cache_free(ecryptfs_auth_tok_list_item_cache, auth_tok_list_item); out: if (rc) (*packet_size) = 0; return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'eCryptfs: parse_tag_3_packet check tag 3 packet encrypted key size The parse_tag_3_packet function does not check if the tag 3 packet contains a encrypted key size larger than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES. Signed-off-by: Ramon de Carvalho Valle <ramon@risesecurity.org> [tyhicks@linux.vnet.ibm.com: Added printk newline and changed goto to out_free] Signed-off-by: Tyler Hicks <tyhicks@linux.vnet.ibm.com> Cc: stable@kernel.org (2.6.27 and 30) Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int raw_getname(struct socket *sock, struct sockaddr *uaddr, int *len, int peer) { struct sockaddr_can *addr = (struct sockaddr_can *)uaddr; struct sock *sk = sock->sk; struct raw_sock *ro = raw_sk(sk); if (peer) return -EOPNOTSUPP; addr->can_family = AF_CAN; addr->can_ifindex = ro->ifindex; *len = sizeof(*addr); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'can: Fix raw_getname() leak raw_getname() can leak 10 bytes of kernel memory to user (two bytes hole between can_family and can_ifindex, 8 bytes at the end of sockaddr_can structure) Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Acked-by: Oliver Hartkopp <oliver@hartkopp.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tcf_add_notify(struct tc_action *a, u32 pid, u32 seq, int event, u16 flags) { struct tcamsg *t; struct nlmsghdr *nlh; struct sk_buff *skb; struct rtattr *x; unsigned char *b; int err = 0; skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) return -ENOBUFS; b = (unsigned char *)skb->tail; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr*) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); if (tcf_action_dump(skb, a, 0, 0) < 0) goto rtattr_failure; x->rta_len = skb->tail - (u8*)x; nlh->nlmsg_len = skb->tail - b; NETLINK_CB(skb).dst_groups = RTMGRP_TC; err = rtnetlink_send(skb, pid, RTMGRP_TC, flags&NLM_F_ECHO); if (err > 0) err = 0; return err; rtattr_failure: nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tca_action_flush(struct rtattr *rta, struct nlmsghdr *n, u32 pid) { struct sk_buff *skb; unsigned char *b; struct nlmsghdr *nlh; struct tcamsg *t; struct netlink_callback dcb; struct rtattr *x; struct rtattr *tb[TCA_ACT_MAX+1]; struct rtattr *kind; struct tc_action *a = create_a(0); int err = -EINVAL; if (a == NULL) { printk("tca_action_flush: couldnt create tc_action\n"); return err; } skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { printk("tca_action_flush: failed skb alloc\n"); kfree(a); return -ENOBUFS; } b = (unsigned char *)skb->tail; if (rtattr_parse_nested(tb, TCA_ACT_MAX, rta) < 0) goto err_out; kind = tb[TCA_ACT_KIND-1]; a->ops = tc_lookup_action(kind); if (a->ops == NULL) goto err_out; nlh = NLMSG_PUT(skb, pid, n->nlmsg_seq, RTM_DELACTION, sizeof(*t)); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr *) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); err = a->ops->walk(skb, &dcb, RTM_DELACTION, a); if (err < 0) goto rtattr_failure; x->rta_len = skb->tail - (u8 *) x; nlh->nlmsg_len = skb->tail - b; nlh->nlmsg_flags |= NLM_F_ROOT; module_put(a->ops->owner); kfree(a); err = rtnetlink_send(skb, pid, RTMGRP_TC, n->nlmsg_flags&NLM_F_ECHO); if (err > 0) return 0; return err; rtattr_failure: module_put(a->ops->owner); nlmsg_failure: err_out: kfree_skb(skb); kfree(a); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char ** argv) { int c; unsigned long flags = MS_MANDLOCK; char * orgoptions = NULL; char * share_name = NULL; const char * ipaddr = NULL; char * uuid = NULL; char * mountpoint = NULL; char * options = NULL; char * optionstail; char * resolved_path = NULL; char * temp; char * dev_name; int rc = 0; int rsize = 0; int wsize = 0; int nomtab = 0; int uid = 0; int gid = 0; int optlen = 0; int orgoptlen = 0; size_t options_size = 0; size_t current_len; int retry = 0; /* set when we have to retry mount with uppercase */ struct addrinfo *addrhead = NULL, *addr; struct utsname sysinfo; struct mntent mountent; struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; FILE * pmntfile; /* setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); */ if(argc && argv) thisprogram = argv[0]; else mount_cifs_usage(stderr); if(thisprogram == NULL) thisprogram = "mount.cifs"; uname(&sysinfo); /* BB add workstation name and domain and pass down */ /* #ifdef _GNU_SOURCE fprintf(stderr, " node: %s machine: %s sysname %s domain %s\n", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname); #endif */ if(argc > 2) { dev_name = argv[1]; share_name = strndup(argv[1], MAX_UNC_LEN); if (share_name == NULL) { fprintf(stderr, "%s: %s", argv[0], strerror(ENOMEM)); exit(EX_SYSERR); } mountpoint = argv[2]; } else if (argc == 2) { if ((strcmp(argv[1], "-V") == 0) || (strcmp(argv[1], "--version") == 0)) { print_cifs_mount_version(); exit(0); } if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "-?") == 0) || (strcmp(argv[1], "--help") == 0)) mount_cifs_usage(stdout); mount_cifs_usage(stderr); } else { mount_cifs_usage(stderr); } /* add sharename in opts string as unc= parm */ while ((c = getopt_long (argc, argv, "afFhilL:no:O:rsSU:vVwt:", longopts, NULL)) != -1) { switch (c) { /* No code to do the following options yet */ /* case 'l': list_with_volumelabel = 1; break; case 'L': volumelabel = optarg; break; */ /* case 'a': ++mount_all; break; */ case '?': case 'h': /* help */ mount_cifs_usage(stdout); case 'n': ++nomtab; break; case 'b': #ifdef MS_BIND flags |= MS_BIND; #else fprintf(stderr, "option 'b' (MS_BIND) not supported\n"); #endif break; case 'm': #ifdef MS_MOVE flags |= MS_MOVE; #else fprintf(stderr, "option 'm' (MS_MOVE) not supported\n"); #endif break; case 'o': orgoptions = strdup(optarg); break; case 'r': /* mount readonly */ flags |= MS_RDONLY; break; case 'U': uuid = optarg; break; case 'v': ++verboseflag; break; case 'V': print_cifs_mount_version(); exit (0); case 'w': flags &= ~MS_RDONLY; break; case 'R': rsize = atoi(optarg) ; break; case 'W': wsize = atoi(optarg); break; case '1': if (isdigit(*optarg)) { char *ep; uid = strtoul(optarg, &ep, 10); if (*ep) { fprintf(stderr, "bad uid value \"%s\"\n", optarg); exit(EX_USAGE); } } else { struct passwd *pw; if (!(pw = getpwnam(optarg))) { fprintf(stderr, "bad user name \"%s\"\n", optarg); exit(EX_USAGE); } uid = pw->pw_uid; endpwent(); } break; case '2': if (isdigit(*optarg)) { char *ep; gid = strtoul(optarg, &ep, 10); if (*ep) { fprintf(stderr, "bad gid value \"%s\"\n", optarg); exit(EX_USAGE); } } else { struct group *gr; if (!(gr = getgrnam(optarg))) { fprintf(stderr, "bad user name \"%s\"\n", optarg); exit(EX_USAGE); } gid = gr->gr_gid; endpwent(); } break; case 'u': got_user = 1; user_name = optarg; break; case 'd': domain_name = optarg; /* BB fix this - currently ignored */ got_domain = 1; break; case 'p': if(mountpassword == NULL) mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if(mountpassword) { got_password = 1; strlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1); } break; case 'S': get_password_from_file(0 /* stdin */,NULL); break; case 't': break; case 'f': ++fakemnt; break; default: fprintf(stderr, "unknown mount option %c\n",c); mount_cifs_usage(stderr); } } if((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) { mount_cifs_usage(stderr); } /* make sure mountpoint is legit */ rc = check_mountpoint(thisprogram, mountpoint); if (rc) goto mount_exit; /* sanity check for unprivileged mounts */ if (getuid()) { rc = check_fstab(thisprogram, mountpoint, dev_name, &orgoptions); if (rc) goto mount_exit; /* enable any default user mount flags */ flags |= CIFS_SETUID_FLAGS; } if (getenv("PASSWD")) { if(mountpassword == NULL) mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if(mountpassword) { strlcpy(mountpassword,getenv("PASSWD"),MOUNT_PASSWD_SIZE+1); got_password = 1; } } else if (getenv("PASSWD_FD")) { get_password_from_file(atoi(getenv("PASSWD_FD")),NULL); } else if (getenv("PASSWD_FILE")) { get_password_from_file(0, getenv("PASSWD_FILE")); } if (orgoptions && parse_options(&orgoptions, &flags)) { rc = EX_USAGE; goto mount_exit; } if (getuid()) { #if !CIFS_LEGACY_SETUID_CHECK if (!(flags & (MS_USERS|MS_USER))) { fprintf(stderr, "%s: permission denied\n", thisprogram); rc = EX_USAGE; goto mount_exit; } #endif /* !CIFS_LEGACY_SETUID_CHECK */ if (geteuid()) { fprintf(stderr, "%s: not installed setuid - \"user\" " "CIFS mounts not supported.", thisprogram); rc = EX_FAIL; goto mount_exit; } } flags &= ~(MS_USERS|MS_USER); addrhead = addr = parse_server(&share_name); if((addrhead == NULL) && (got_ip == 0)) { fprintf(stderr, "No ip address specified and hostname not found\n"); rc = EX_USAGE; goto mount_exit; } /* BB save off path and pop after mount returns? */ resolved_path = (char *)malloc(PATH_MAX+1); if(resolved_path) { /* Note that if we can not canonicalize the name, we get another chance to see if it is valid when we chdir to it */ if (realpath(mountpoint, resolved_path)) { mountpoint = resolved_path; } } if(got_user == 0) { /* Note that the password will not be retrieved from the USER env variable (ie user%password form) as there is already a PASSWD environment varaible */ if (getenv("USER")) user_name = strdup(getenv("USER")); if (user_name == NULL) user_name = getusername(); got_user = 1; } if(got_password == 0) { char *tmp_pass = getpass("Password: "); /* BB obsolete sys call but no good replacement yet. */ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if (!tmp_pass || !mountpassword) { fprintf(stderr, "Password not entered, exiting\n"); exit(EX_USAGE); } strlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1); got_password = 1; } /* FIXME launch daemon (handles dfs name resolution and credential change) remember to clear parms and overwrite password field before launching */ if(orgoptions) { optlen = strlen(orgoptions); orgoptlen = optlen; } else optlen = 0; if(share_name) optlen += strlen(share_name) + 4; else { fprintf(stderr, "No server share name specified\n"); fprintf(stderr, "\nMounting the DFS root for server not implemented yet\n"); exit(EX_USAGE); } if(user_name) optlen += strlen(user_name) + 6; optlen += MAX_ADDRESS_LEN + 4; if(mountpassword) optlen += strlen(mountpassword) + 6; mount_retry: SAFE_FREE(options); options_size = optlen + 10 + DOMAIN_SIZE; options = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain= , domain name itself was counted as part of the length username string above */); if(options == NULL) { fprintf(stderr, "Could not allocate memory for mount options\n"); exit(EX_SYSERR); } strlcpy(options, "unc=", options_size); strlcat(options,share_name,options_size); /* scan backwards and reverse direction of slash */ temp = strrchr(options, '/'); if(temp > options + 6) *temp = '\\'; if(user_name) { /* check for syntax like user=domain\user */ if(got_domain == 0) domain_name = check_for_domain(&user_name); strlcat(options,",user=",options_size); strlcat(options,user_name,options_size); } if(retry == 0) { if(domain_name) { /* extra length accounted for in option string above */ strlcat(options,",domain=",options_size); strlcat(options,domain_name,options_size); } } strlcat(options,",ver=",options_size); strlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size); if(orgoptions) { strlcat(options,",",options_size); strlcat(options,orgoptions,options_size); } if(prefixpath) { strlcat(options,",prefixpath=",options_size); strlcat(options,prefixpath,options_size); /* no need to cat the / */ } /* convert all '\\' to '/' in share portion so that /proc/mounts looks pretty */ replace_char(dev_name, '\\', '/', strlen(share_name)); if (!got_ip && addr) { strlcat(options, ",ip=", options_size); current_len = strnlen(options, options_size); optionstail = options + current_len; switch (addr->ai_addr->sa_family) { case AF_INET6: addr6 = (struct sockaddr_in6 *) addr->ai_addr; ipaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, optionstail, options_size - current_len); break; case AF_INET: addr4 = (struct sockaddr_in *) addr->ai_addr; ipaddr = inet_ntop(AF_INET, &addr4->sin_addr, optionstail, options_size - current_len); break; default: ipaddr = NULL; } /* if the address looks bogus, try the next one */ if (!ipaddr) { addr = addr->ai_next; if (addr) goto mount_retry; rc = EX_SYSERR; goto mount_exit; } } if (addr->ai_addr->sa_family == AF_INET6 && addr6->sin6_scope_id) { strlcat(options, "%", options_size); current_len = strnlen(options, options_size); optionstail = options + current_len; snprintf(optionstail, options_size - current_len, "%u", addr6->sin6_scope_id); } if(verboseflag) fprintf(stderr, "\nmount.cifs kernel mount options: %s", options); if (mountpassword) { /* * Commas have to be doubled, or else they will * look like the parameter separator */ if(retry == 0) check_for_comma(&mountpassword); strlcat(options,",pass=",options_size); strlcat(options,mountpassword,options_size); if (verboseflag) fprintf(stderr, ",pass=********"); } if (verboseflag) fprintf(stderr, "\n"); if (!fakemnt && mount(dev_name, mountpoint, cifs_fstype, flags, options)) { switch (errno) { case ECONNREFUSED: case EHOSTUNREACH: if (addr) { addr = addr->ai_next; if (addr) goto mount_retry; } break; case ENODEV: fprintf(stderr, "mount error: cifs filesystem not supported by the system\n"); break; case ENXIO: if(retry == 0) { retry = 1; if (uppercase_string(dev_name) && uppercase_string(share_name) && uppercase_string(prefixpath)) { fprintf(stderr, "retrying with upper case share name\n"); goto mount_retry; } } } fprintf(stderr, "mount error(%d): %s\n", errno, strerror(errno)); fprintf(stderr, "Refer to the mount.cifs(8) manual page (e.g. man " "mount.cifs)\n"); rc = EX_FAIL; goto mount_exit; } if (nomtab) goto mount_exit; atexit(unlock_mtab); rc = lock_mtab(); if (rc) { fprintf(stderr, "cannot lock mtab"); goto mount_exit; } pmntfile = setmntent(MOUNTED, "a+"); if (!pmntfile) { fprintf(stderr, "could not update mount table\n"); unlock_mtab(); rc = EX_FILEIO; goto mount_exit; } mountent.mnt_fsname = dev_name; mountent.mnt_dir = mountpoint; mountent.mnt_type = (char *)(void *)cifs_fstype; mountent.mnt_opts = (char *)malloc(220); if(mountent.mnt_opts) { char * mount_user = getusername(); memset(mountent.mnt_opts,0,200); if(flags & MS_RDONLY) strlcat(mountent.mnt_opts,"ro",220); else strlcat(mountent.mnt_opts,"rw",220); if(flags & MS_MANDLOCK) strlcat(mountent.mnt_opts,",mand",220); if(flags & MS_NOEXEC) strlcat(mountent.mnt_opts,",noexec",220); if(flags & MS_NOSUID) strlcat(mountent.mnt_opts,",nosuid",220); if(flags & MS_NODEV) strlcat(mountent.mnt_opts,",nodev",220); if(flags & MS_SYNCHRONOUS) strlcat(mountent.mnt_opts,",sync",220); if(mount_user) { if(getuid() != 0) { strlcat(mountent.mnt_opts, ",user=", 220); strlcat(mountent.mnt_opts, mount_user, 220); } } } mountent.mnt_freq = 0; mountent.mnt_passno = 0; rc = addmntent(pmntfile,&mountent); endmntent(pmntfile); unlock_mtab(); SAFE_FREE(mountent.mnt_opts); if (rc) rc = EX_FILEIO; mount_exit: if(mountpassword) { int len = strlen(mountpassword); memset(mountpassword,0,len); SAFE_FREE(mountpassword); } if (addrhead) freeaddrinfo(addrhead); SAFE_FREE(options); SAFE_FREE(orgoptions); SAFE_FREE(resolved_path); SAFE_FREE(share_name); exit(rc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'mount.cifs: take extra care that mountpoint isn't changed during mount It's possible to trick mount.cifs into mounting onto the wrong directory by replacing the mountpoint with a symlink to a directory. mount.cifs attempts to check the validity of the mountpoint, but there's still a possible race between those checks and the mount(2) syscall. To guard against this, chdir to the mountpoint very early, and only deal with it as "." from then on out. Signed-off-by: Jeff Layton <jlayton@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dispose (GObject *object) { NMAGConfSettingsPrivate *priv = NMA_GCONF_SETTINGS_GET_PRIVATE (object); if (priv->disposed) return; priv->disposed = TRUE; g_hash_table_destroy (priv->pending_changes); if (priv->read_connections_id) { g_source_remove (priv->read_connections_id); priv->read_connections_id = 0; } gconf_client_notify_remove (priv->client, priv->conf_notify_id); gconf_client_remove_dir (priv->client, GCONF_PATH_CONNECTIONS, NULL); g_slist_foreach (priv->connections, (GFunc) g_object_unref, NULL); g_slist_free (priv->connections); g_object_unref (priv->client); G_OBJECT_CLASS (nma_gconf_settings_parent_class)->dispose (object); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'applet: fix dbus connection refcounting after 8627880e07c8345f69ed639325280c7f62a8f894'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: add_one_setting (GHashTable *settings, NMConnection *connection, NMSetting *setting, GError **error) { GHashTable *secrets; g_return_val_if_fail (settings != NULL, FALSE); g_return_val_if_fail (connection != NULL, FALSE); g_return_val_if_fail (setting != NULL, FALSE); g_return_val_if_fail (error != NULL, FALSE); g_return_val_if_fail (*error == NULL, FALSE); utils_fill_connection_certs (connection); secrets = nm_setting_to_hash (setting); utils_clear_filled_connection_certs (connection); if (secrets) { g_hash_table_insert (settings, g_strdup (nm_setting_get_name (setting)), secrets); } else { g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INTERNAL_ERROR, "%s.%d (%s): failed to hash setting '%s'.", __FILE__, __LINE__, __func__, nm_setting_get_name (setting)); } return secrets ? TRUE : FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _hb_ot_layout_init (hb_face_t *face) { hb_ot_layout_t *layout = &face->ot_layout; layout->gdef_blob = Sanitizer<GDEF>::sanitize (hb_face_get_table (face, HB_OT_TAG_GDEF)); layout->gdef = &Sanitizer<GDEF>::lock_instance (layout->gdef_blob); layout->gsub_blob = Sanitizer<GSUB>::sanitize (hb_face_get_table (face, HB_OT_TAG_GSUB)); layout->gsub = &Sanitizer<GSUB>::lock_instance (layout->gsub_blob); layout->gpos_blob = Sanitizer<GPOS>::sanitize (hb_face_get_table (face, HB_OT_TAG_GPOS)); layout->gpos = &Sanitizer<GPOS>::lock_instance (layout->gpos_blob); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': '[HB/GDEF] Fix bug in building synthetic GDEF table'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int Server::authenticate(QString &name, const QString &pw, const QStringList &emails, const QString &certhash, bool bStrongCert, const QList<QSslCertificate> &certs) { int res = -2; emit authenticateSig(res, name, certs, certhash, bStrongCert, pw); if (res != -2) { // External authentication handled it. Ignore certificate completely. if (res != -1) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; int lchan=readLastChannel(res); if (lchan < 0) lchan = 0; SQLPREP("REPLACE INTO `%1users` (`server_id`, `user_id`, `name`, `lastchannel`) VALUES (?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(res); query.addBindValue(name); query.addBindValue(lchan); SQLEXEC(); } if (res >= 0) { qhUserNameCache.remove(res); qhUserIDCache.remove(name); } return res; } TransactionHolder th; QSqlQuery &query = *th.qsqQuery; SQLPREP("SELECT `user_id`,`name`,`pw` FROM `%1users` WHERE `server_id` = ? AND `name` like ?"); query.addBindValue(iServerNum); query.addBindValue(name); SQLEXEC(); if (query.next()) { res = -1; QString storedpw = query.value(2).toString(); QString hashedpw = QString::fromLatin1(sha1(pw).toHex()); if (! storedpw.isEmpty() && (storedpw == hashedpw)) { name = query.value(1).toString(); res = query.value(0).toInt(); } else if (query.value(0).toInt() == 0) { return -1; } } // No password match. Try cert or email match, but only for non-SuperUser. if (!certhash.isEmpty() && (res < 0)) { SQLPREP("SELECT `user_id` FROM `%1user_info` WHERE `server_id` = ? AND `key` = ? AND `value` = ?"); query.addBindValue(iServerNum); query.addBindValue(ServerDB::User_Hash); query.addBindValue(certhash); SQLEXEC(); if (query.next()) { res = query.value(0).toInt(); } else if (bStrongCert) { foreach(const QString &email, emails) { if (! email.isEmpty()) { query.addBindValue(iServerNum); query.addBindValue(ServerDB::User_Email); query.addBindValue(email); SQLEXEC(); if (query.next()) { res = query.value(0).toInt(); break; } } } } if (res > 0) { SQLPREP("SELECT `name` FROM `%1users` WHERE `server_id` = ? AND `user_id` = ?"); query.addBindValue(iServerNum); query.addBindValue(res); SQLEXEC(); if (! query.next()) { res = -1; } else { name = query.value(0).toString(); } } } if (! certhash.isEmpty() && (res > 0)) { SQLPREP("REPLACE INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (?, ?, ?, ?)"); query.addBindValue(iServerNum); query.addBindValue(res); query.addBindValue(ServerDB::User_Hash); query.addBindValue(certhash); SQLEXEC(); if (! emails.isEmpty()) { query.addBindValue(iServerNum); query.addBindValue(res); query.addBindValue(ServerDB::User_Email); query.addBindValue(emails.at(0)); SQLEXEC(); } } if (res >= 0) { qhUserNameCache.remove(res); qhUserIDCache.remove(name); } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash on long usernames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long keyctl_session_to_parent(void) { #ifdef TIF_NOTIFY_RESUME struct task_struct *me, *parent; const struct cred *mycred, *pcred; struct cred *cred, *oldcred; key_ref_t keyring_r; int ret; keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK); if (IS_ERR(keyring_r)) return PTR_ERR(keyring_r); /* our parent is going to need a new cred struct, a new tgcred struct * and new security data, so we allocate them here to prevent ENOMEM in * our parent */ ret = -ENOMEM; cred = cred_alloc_blank(); if (!cred) goto error_keyring; cred->tgcred->session_keyring = key_ref_to_ptr(keyring_r); keyring_r = NULL; me = current; write_lock_irq(&tasklist_lock); parent = me->real_parent; ret = -EPERM; /* the parent mustn't be init and mustn't be a kernel thread */ if (parent->pid <= 1 || !parent->mm) goto not_permitted; /* the parent must be single threaded */ if (!thread_group_empty(parent)) goto not_permitted; /* the parent and the child must have different session keyrings or * there's no point */ mycred = current_cred(); pcred = __task_cred(parent); if (mycred == pcred || mycred->tgcred->session_keyring == pcred->tgcred->session_keyring) goto already_same; /* the parent must have the same effective ownership and mustn't be * SUID/SGID */ if (pcred->uid != mycred->euid || pcred->euid != mycred->euid || pcred->suid != mycred->euid || pcred->gid != mycred->egid || pcred->egid != mycred->egid || pcred->sgid != mycred->egid) goto not_permitted; /* the keyrings must have the same UID */ if (pcred->tgcred->session_keyring->uid != mycred->euid || mycred->tgcred->session_keyring->uid != mycred->euid) goto not_permitted; /* if there's an already pending keyring replacement, then we replace * that */ oldcred = parent->replacement_session_keyring; /* the replacement session keyring is applied just prior to userspace * restarting */ parent->replacement_session_keyring = cred; cred = NULL; set_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME); write_unlock_irq(&tasklist_lock); if (oldcred) put_cred(oldcred); return 0; already_same: ret = 0; not_permitted: write_unlock_irq(&tasklist_lock); put_cred(cred); return ret; error_keyring: key_ref_put(keyring_r); return ret; #else /* !TIF_NOTIFY_RESUME */ /* * To be removed when TIF_NOTIFY_RESUME has been implemented on * m68k/xtensa */ #warning TIF_NOTIFY_RESUME not implemented return -EOPNOTSUPP; #endif /* !TIF_NOTIFY_RESUME */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Fix RCU no-lock warning in keyctl_session_to_parent() There's an protected access to the parent process's credentials in the middle of keyctl_session_to_parent(). This results in the following RCU warning: =================================================== [ INFO: suspicious rcu_dereference_check() usage. ] --------------------------------------------------- security/keys/keyctl.c:1291 invoked rcu_dereference_check() without protection! other info that might help us debug this: rcu_scheduler_active = 1, debug_locks = 0 1 lock held by keyctl-session-/2137: #0: (tasklist_lock){.+.+..}, at: [<ffffffff811ae2ec>] keyctl_session_to_parent+0x60/0x236 stack backtrace: Pid: 2137, comm: keyctl-session- Not tainted 2.6.36-rc2-cachefs+ #1 Call Trace: [<ffffffff8105606a>] lockdep_rcu_dereference+0xaa/0xb3 [<ffffffff811ae379>] keyctl_session_to_parent+0xed/0x236 [<ffffffff811af77e>] sys_keyctl+0xb4/0xb6 [<ffffffff81001eab>] system_call_fastpath+0x16/0x1b The code should take the RCU read lock to make sure the parents credentials don't go away, even though it's holding a spinlock and has IRQ disabled. Signed-off-by: David Howells <dhowells@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __vmx_load_host_state(struct vcpu_vmx *vmx) { unsigned long flags; if (!vmx->host_state.loaded) return; ++vmx->vcpu.stat.host_state_reload; vmx->host_state.loaded = 0; if (vmx->host_state.fs_reload_needed) kvm_load_fs(vmx->host_state.fs_sel); if (vmx->host_state.gs_ldt_reload_needed) { kvm_load_ldt(vmx->host_state.ldt_sel); /* * If we have to reload gs, we must take care to * preserve our gs base. */ local_irq_save(flags); kvm_load_gs(vmx->host_state.gs_sel); #ifdef CONFIG_X86_64 wrmsrl(MSR_GS_BASE, vmcs_readl(HOST_GS_BASE)); #endif local_irq_restore(flags); } reload_tss(); #ifdef CONFIG_X86_64 if (is_long_mode(&vmx->vcpu)) { rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base); } #endif if (current_thread_info()->status & TS_USEDFPU) clts(); load_gdt(&__get_cpu_var(host_gdt)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt kvm reloads the host's fs and gs blindly, however the underlying segment descriptors may be invalid due to the user modifying the ldt after loading them. Fix by using the safe accessors (loadsegment() and load_gs_index()) instead of home grown unsafe versions. This is CVE-2010-3698. KVM-Stable-Tag. Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: */ static xmlNodePtr xmlXPathNextPrecedingInternal(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) { if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL); if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) || (ctxt->context->node->type == XML_NAMESPACE_DECL)) return(NULL); if (cur == NULL) { cur = ctxt->context->node; if (cur == NULL) return (NULL); ctxt->ancestor = cur->parent; } if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE)) cur = cur->prev; while (cur->prev == NULL) { cur = cur->parent; if (cur == NULL) return (NULL); if (cur == ctxt->context->doc->children) return (NULL); if (cur != ctxt->ancestor) return (cur); ctxt->ancestor = cur->parent; } cur = cur->prev; while (cur->last != NULL) cur = cur->last; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix a change of semantic on XPath preceding and following axis This was introduced in the prevous fix, while preceding-sibling and following sibling axis are empty for attributes and namespaces, preceding and following axis should still work based on the parent element. However the parent element is not available for a namespace node, so we keep the axis empty in that case.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void flush_stack(struct sock **stack, unsigned int count, struct sk_buff *skb, unsigned int final) { unsigned int i; struct sock *sk; struct sk_buff *skb1; for (i = 0; i < count; i++) { skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC); sk = stack[i]; if (skb1) { bh_lock_sock(sk); if (!sock_owned_by_user(sk)) udpv6_queue_rcv_skb(sk, skb1); else if (sk_add_backlog(sk, skb1)) { kfree_skb(skb1); bh_unlock_sock(sk); goto drop; } bh_unlock_sock(sk); continue; } drop: atomic_inc(&sk->sk_drops); UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, IS_UDPLITE(sk)); UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account Current socket backlog limit is not enough to really stop DDOS attacks, because user thread spend many time to process a full backlog each round, and user might crazy spin on socket lock. We should add backlog size and receive_queue size (aka rmem_alloc) to pace writers, and let user run without being slow down too much. Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in stress situations. Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp receiver can now process ~200.000 pps (instead of ~100 pps before the patch) on a 8 core machine. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: readconf_main(void) { int sep = 0; struct stat statbuf; uschar *s, *filename; uschar *list = config_main_filelist; /* Loop through the possible file names */ while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)) != NULL) { /* Cut out all the fancy processing unless specifically wanted */ #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID) uschar *suffix = filename + Ustrlen(filename); /* Try for the node-specific file if a node name exists */ #ifdef CONFIGURE_FILE_USE_NODE struct utsname uts; if (uname(&uts) >= 0) { #ifdef CONFIGURE_FILE_USE_EUID sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename); config_file = Ufopen(filename, "rb"); if (config_file == NULL) #endif /* CONFIGURE_FILE_USE_EUID */ { sprintf(CS suffix, ".%.256s", uts.nodename); config_file = Ufopen(filename, "rb"); } } #endif /* CONFIGURE_FILE_USE_NODE */ /* Otherwise, try the generic name, possibly with the euid added */ #ifdef CONFIGURE_FILE_USE_EUID if (config_file == NULL) { sprintf(CS suffix, ".%ld", (long int)original_euid); config_file = Ufopen(filename, "rb"); } #endif /* CONFIGURE_FILE_USE_EUID */ /* Finally, try the unadorned name */ if (config_file == NULL) { *suffix = 0; config_file = Ufopen(filename, "rb"); } #else /* if neither defined */ /* This is the common case when the fancy processing is not included. */ config_file = Ufopen(filename, "rb"); #endif /* If the file does not exist, continue to try any others. For any other error, break out (and die). */ if (config_file != NULL || errno != ENOENT) break; } /* On success, save the name for verification; config_filename is used when logging configuration errors (it changes for .included files) whereas config_main_filename is the name shown by -bP. Failure to open a configuration file is a serious disaster. */ if (config_file != NULL) { config_filename = config_main_filename = string_copy(filename); } else { if (filename == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): " "%s", config_main_filelist); else log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno, "configuration file %s", filename)); } /* Check the status of the file we have opened, unless it was specified on the command line, in which case privilege was given away at the start. */ if (!config_changed) { if (fstat(fileno(config_file), &statbuf) != 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s", big_buffer); if ((statbuf.st_uid != root_uid /* owner not root */ #ifdef CONFIGURE_OWNER && statbuf.st_uid != config_uid /* owner not the special one */ #endif ) || /* or */ (statbuf.st_gid != root_gid /* group not root & */ #ifdef CONFIGURE_GROUP && statbuf.st_gid != config_gid /* group not the special one */ #endif && (statbuf.st_mode & 020) != 0) || /* group writeable */ /* or */ ((statbuf.st_mode & 2) != 0)) /* world writeable */ log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the " "wrong owner, group, or mode", big_buffer); } /* Process the main configuration settings. They all begin with a lower case letter. If we see something starting with an upper case letter, it is taken as a macro definition. */ while ((s = get_config_line()) != NULL) { if (isupper(s[0])) read_macro_assignment(s); else if (Ustrncmp(s, "domainlist", 10) == 0) read_named_list(&domainlist_anchor, &domainlist_count, MAX_NAMED_LIST, s+10, US"domain list"); else if (Ustrncmp(s, "hostlist", 8) == 0) read_named_list(&hostlist_anchor, &hostlist_count, MAX_NAMED_LIST, s+8, US"host list"); else if (Ustrncmp(s, US"addresslist", 11) == 0) read_named_list(&addresslist_anchor, &addresslist_count, MAX_NAMED_LIST, s+11, US"address list"); else if (Ustrncmp(s, US"localpartlist", 13) == 0) read_named_list(&localpartlist_anchor, &localpartlist_count, MAX_NAMED_LIST, s+13, US"local part list"); else (void) readconf_handle_option(s, optionlist_config, optionlist_config_size, NULL, US"main option \"%s\" unknown"); } /* If local_sender_retain is set, local_from_check must be unset. */ if (local_sender_retain && local_from_check) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and " "local_sender_retain are set; this combination is not allowed"); /* If the timezone string is empty, set it to NULL, implying no TZ variable wanted. */ if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL; /* The max retry interval must not be greater than 24 hours. */ if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60; /* remote_max_parallel must be > 0 */ if (remote_max_parallel <= 0) remote_max_parallel = 1; /* Save the configured setting of freeze_tell, so we can re-instate it at the start of a new SMTP message. */ freeze_tell_config = freeze_tell; /* The primary host name may be required for expansion of spool_directory and log_file_path, so make sure it is set asap. It is obtained from uname(), but if that yields an unqualified value, make a FQDN by using gethostbyname to canonize it. Some people like upper case letters in their host names, so we don't force the case. */ if (primary_hostname == NULL) { uschar *hostname; struct utsname uts; if (uname(&uts) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name"); hostname = US uts.nodename; if (Ustrchr(hostname, '.') == NULL) { int af = AF_INET; struct hostent *hostdata; #if HAVE_IPV6 if (!disable_ipv6 && (dns_ipv4_lookup == NULL || match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN, TRUE, NULL) != OK)) af = AF_INET6; #else af = AF_INET; #endif for (;;) { #if HAVE_IPV6 #if HAVE_GETIPNODEBYNAME int error_num; hostdata = getipnodebyname(CS hostname, af, 0, &error_num); #else hostdata = gethostbyname2(CS hostname, af); #endif #else hostdata = gethostbyname(CS hostname); #endif if (hostdata != NULL) { hostname = US hostdata->h_name; break; } if (af == AF_INET) break; af = AF_INET; } } primary_hostname = string_copy(hostname); } /* Set up default value for smtp_active_hostname */ smtp_active_hostname = primary_hostname; /* If spool_directory wasn't set in the build-time configuration, it must have got set above. Of course, writing to the log may not work if log_file_path is not set, but it will at least get to syslog or somewhere, with any luck. */ if (*spool_directory == 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot " "proceed"); /* Expand the spool directory name; it may, for example, contain the primary host name. Same comment about failure. */ s = expand_string(spool_directory); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory " "\"%s\": %s", spool_directory, expand_string_message); spool_directory = s; /* Expand log_file_path, which must contain "%s" in any component that isn't the null string or "syslog". It is also allowed to contain one instance of %D. However, it must NOT contain % followed by anything else. */ if (*log_file_path != 0) { uschar *ss, *sss; int sep = ':'; /* Fixed for log file path */ s = expand_string(log_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path " "\"%s\": %s", log_file_path, expand_string_message); ss = s; while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL) { uschar *t; if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue; t = Ustrstr(sss, "%s"); if (t == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not " "contain \"%%s\"", sss); *t = 'X'; t = Ustrchr(sss, '%'); if (t != NULL) { if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains " "unexpected \"%%\" character", s); } } log_file_path = s; } /* Interpret syslog_facility into an integer argument for 'ident' param to openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the leading "log_". */ if (syslog_facility_str != NULL) { int i; uschar *s = syslog_facility_str; if ((Ustrlen(syslog_facility_str) >= 4) && (strncmpic(syslog_facility_str, US"log_", 4) == 0)) s += 4; for (i = 0; i < syslog_list_size; i++) { if (strcmpic(s, syslog_list[i].name) == 0) { syslog_facility = syslog_list[i].value; break; } } if (i >= syslog_list_size) { log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "failed to interpret syslog_facility \"%s\"", syslog_facility_str); } } /* Expand pid_file_path */ if (*pid_file_path != 0) { s = expand_string(pid_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path " "\"%s\": %s", pid_file_path, expand_string_message); pid_file_path = s; } /* Compile the regex for matching a UUCP-style "From_" line in an incoming message. */ regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE); /* Unpick the SMTP rate limiting options, if set */ if (smtp_ratelimit_mail != NULL) { unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold, &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit); } if (smtp_ratelimit_rcpt != NULL) { unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold, &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit); } /* The qualify domains default to the primary host name */ if (qualify_domain_sender == NULL) qualify_domain_sender = primary_hostname; if (qualify_domain_recipient == NULL) qualify_domain_recipient = qualify_domain_sender; /* Setting system_filter_user in the configuration sets the gid as well if a name is given, but a numerical value does not. */ if (system_filter_uid_set && !system_filter_gid_set) { struct passwd *pw = getpwuid(system_filter_uid); if (pw == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld", (long int)system_filter_uid); system_filter_gid = pw->pw_gid; system_filter_gid_set = TRUE; } /* If the errors_reply_to field is set, check that it is syntactically valid and ensure it contains a domain. */ if (errors_reply_to != NULL) { uschar *errmess; int start, end, domain; uschar *recipient = parse_extract_address(errors_reply_to, &errmess, &start, &end, &domain, FALSE); if (recipient == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "error in errors_reply_to (%s): %s", errors_reply_to, errmess); if (domain == 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "errors_reply_to (%s) does not contain a domain", errors_reply_to); } /* If smtp_accept_queue or smtp_accept_max_per_host is set, then smtp_accept_max must also be set. */ if (smtp_accept_max == 0 && (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL)) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "smtp_accept_max must be set if smtp_accept_queue or " "smtp_accept_max_per_host is set"); /* Set up the host number if anything is specified. It is an expanded string so that it can be computed from the host name, for example. We do this last so as to ensure that everything else is set up before the expansion. */ if (host_number_string != NULL) { uschar *end; uschar *s = expand_string(host_number_string); long int n = Ustrtol(s, &end, 0); while (isspace(*end)) end++; if (*end != 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number value is not a number: %s", s); if (n > LOCALHOST_MAX) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number is greater than the maximum allowed value (%d)", LOCALHOST_MAX); host_number = n; } #ifdef SUPPORT_TLS /* If tls_verify_hosts is set, tls_verify_certificates must also be set */ if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) && tls_verify_certificates == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "tls_%sverify_hosts is set, but tls_verify_certificates is not set", (tls_verify_hosts != NULL)? "" : "try_"); /* If openssl_options is set, validate it */ if (openssl_options != NULL) { # ifdef USE_GNUTLS log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options is set but we're using GnuTLS"); # else long dummy; if (!(tls_openssl_options_parse(openssl_options, &dummy))) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options parse error: %s", openssl_options); # endif } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Check configure file permissions even for non-default files if still privileged (Bug 1044, CVE-2010-4345)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: strip_leading_slashes (char *name, int strip_leading) { int s = strip_leading; char *p, *n; for (p = n = name; *p; p++) { if (ISSLASH (*p)) { while (ISSLASH (p[1])) p++; if (strip_leading < 0 || --s >= 0) n = p+1; } } if ((strip_leading < 0 || s <= 0) && *n) { memmove (name, n, strlen (n) + 1); return true; } else return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Do not let a malicious patch create files above current directory This addresses CVE-2010-4651, reported by Jakub Wilk. https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2010-4651 * src/util.c (strip_leading_slashes): Reject absolute file names and file names containing a component of "..". * tests/bad-filenames: New file. Test for this. * tests/Makefile.am (TESTS): Add it. Improvements by Andreas Gruenbacher.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct kmem_cache *ccid_kmem_cache_create(int obj_size, char *slab_name_fmt, const char *fmt,...) { struct kmem_cache *slab; va_list args; va_start(args, fmt); vsnprintf(slab_name_fmt, sizeof(slab_name_fmt), fmt, args); va_end(args); slab = kmem_cache_create(slab_name_fmt, sizeof(struct ccid) + obj_size, 0, SLAB_HWCACHE_ALIGN, NULL); return slab; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'dccp: fix bug in cache allocation This fixes a bug introduced in commit de4ef86cfce60d2250111f34f8a084e769f23b16 ("dccp: fix dccp rmmod when kernel configured to use slub", 17 Jan): the vsnprintf used sizeof(slab_name_fmt), which became truncated to 4 bytes, since slab_name_fmt is now a 4-byte pointer and no longer a 32-character array. This lead to error messages such as FATAL: Error inserting dccp: No buffer space available >> kernel: [ 1456.341501] kmem_cache_create: duplicate cache cci generated due to the truncation after the 3rd character. Fixed for the moment by introducing a symbolic constant. Tested to fix the bug. Signed-off-by: Gerrit Renker <gerrit@erg.abdn.ac.uk> Acked-by: Neil Horman <nhorman@tuxdriver.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case IPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case IPT_SO_GET_REVISION_MATCH: case IPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; int target; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } if (cmd == IPT_SO_GET_REVISION_TARGET) target = 1; else target = 0; try_then_request_module(xt_find_revision(AF_INET, rev.name, rev.revision, target, &ret), "ipt_%s", rev.name); break; } default: duprintf("do_ipt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'netfilter: ip_tables: fix infoleak to userspace Structures ipt_replace, compat_ipt_replace, and xt_get_revision are copied from userspace. Fields of these structs that are zero-terminated strings are not checked. When they are used as argument to a format string containing "%s" in request_module(), some sensitive information is leaked to userspace via argument of spawned modprobe process. The first and the third bugs were introduced before the git epoch; the second was introduced in 2722971c (v2.6.17-rc1). To trigger the bug one should have CAP_NET_ADMIN. Signed-off-by: Vasiliy Kulikov <segoon@openwall.com> Signed-off-by: Patrick McHardy <kaber@trash.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static rsRetVal qAddDirect(qqueue_t *pThis, void* pUsr) { batch_t singleBatch; batch_obj_t batchObj; DEFiRet; //TODO: init batchObj (states _OK and new fields -- CHECK) ASSERT(pThis != NULL); /* calling the consumer is quite different here than it is from a worker thread */ /* we need to provide the consumer's return value back to the caller because in direct * mode the consumer probably has a lot to convey (which get's lost in the other modes * because they are asynchronous. But direct mode is deliberately synchronous. * rgerhards, 2008-02-12 * We use our knowledge about the batch_t structure below, but without that, we * pay a too-large performance toll... -- rgerhards, 2009-04-22 */ memset(&batchObj, 0, sizeof(batch_obj_t)); memset(&singleBatch, 0, sizeof(batch_t)); batchObj.state = BATCH_STATE_RDY; batchObj.pUsrp = (obj_t*) pUsr; batchObj.bFilterOK = 1; singleBatch.nElem = 1; /* there always is only one in direct mode */ singleBatch.pElem = &batchObj; iRet = pThis->pConsumer(pThis->pUsr, &singleBatch, &pThis->bShutdownImmediate); objDestruct(pUsr); RETiRet; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'bugfix: memory leak when $RepeatedMsgReduction on was used bug tracker: http://bugzilla.adiscon.com/show_bug.cgi?id=225'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb) { g_assert (mb); if (mb->mhandle) mono_runtime_free_method ( mono_object_get_domain ((MonoObject*)mb), mb->mhandle); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods. * reflection.c: Use a reference queue to cleanup dynamic methods instead of finalization. * runtime.c: Shutdown the dynamic method queue before runtime cleanup begins. * DynamicMethod.cs: No longer finalizable. * icall-def.h: Remove unused dynamic method icall. Fixes #660422 Implement a reference queue API. * gc.c: A reference queue allows one to queue callbcks for when objects are collected. It allows for safe cleanup of objects that can only be done when it is effectively collected. The major difference with regular finalization is that the collector makes sure the object was collected - and can't be resurrected. * gc-internal.h: Export entrypoints for the new API.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: thunar_transfer_job_copy_node (ThunarTransferJob *job, ThunarTransferNode *node, GFile *target_file, GFile *target_parent_file, GList **target_file_list_return, GError **error) { ThunarThumbnailCache *thumbnail_cache; ThunarApplication *application; ThunarJobResponse response; GFileInfo *info; GError *err = NULL; GFile *real_target_file = NULL; gchar *base_name; _thunar_return_if_fail (THUNAR_IS_TRANSFER_JOB (job)); _thunar_return_if_fail (node != NULL && G_IS_FILE (node->source_file)); _thunar_return_if_fail (target_file == NULL || node->next == NULL); _thunar_return_if_fail ((target_file == NULL && target_parent_file != NULL) || (target_file != NULL && target_parent_file == NULL)); _thunar_return_if_fail (error == NULL || *error == NULL); /* The caller can either provide a target_file or a target_parent_file, but not both. The toplevel * transfer_nodes (for which next is NULL) should be called with target_file, to get proper behavior * wrt restoring files from the trash. Other transfer_nodes will be called with target_parent_file. */ /* take a reference on the thumbnail cache */ application = thunar_application_get (); thumbnail_cache = thunar_application_get_thumbnail_cache (application); g_object_unref (application); for (; err == NULL && node != NULL; node = node->next) { /* guess the target file for this node (unless already provided) */ if (G_LIKELY (target_file == NULL)) { base_name = g_file_get_basename (node->source_file); target_file = g_file_get_child (target_parent_file, base_name); g_free (base_name); } else target_file = g_object_ref (target_file); /* query file info */ info = g_file_query_info (node->source_file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, exo_job_get_cancellable (EXO_JOB (job)), &err); /* abort on error or cancellation */ if (info == NULL) { g_object_unref (target_file); break; } /* update progress information */ exo_job_info_message (EXO_JOB (job), g_file_info_get_display_name (info)); retry_copy: /* copy the item specified by this node (not recursively) */ real_target_file = thunar_transfer_job_copy_file (job, node->source_file, target_file, &err); if (G_LIKELY (real_target_file != NULL)) { /* node->source_file == real_target_file means to skip the file */ if (G_LIKELY (node->source_file != real_target_file)) { /* notify the thumbnail cache of the copy operation */ thunar_thumbnail_cache_copy_file (thumbnail_cache, node->source_file, real_target_file); /* check if we have children to copy */ if (node->children != NULL) { /* copy all children of this node */ thunar_transfer_job_copy_node (job, node->children, NULL, real_target_file, NULL, &err); /* free resources allocted for the children */ thunar_transfer_node_free (node->children); node->children = NULL; } /* check if the child copy failed */ if (G_UNLIKELY (err != NULL)) { /* outa here, freeing the target paths */ g_object_unref (real_target_file); g_object_unref (target_file); break; } /* add the real target file to the return list */ if (G_LIKELY (target_file_list_return != NULL)) { *target_file_list_return = thunar_g_file_list_prepend (*target_file_list_return, real_target_file); } retry_remove: /* try to remove the source directory if we are on copy+remove fallback for move */ if (job->type == THUNAR_TRANSFER_JOB_MOVE) { if (g_file_delete (node->source_file, exo_job_get_cancellable (EXO_JOB (job)), &err)) { /* notify the thumbnail cache of the delete operation */ thunar_thumbnail_cache_delete_file (thumbnail_cache, node->source_file); } else { /* ask the user to retry */ response = thunar_job_ask_skip (THUNAR_JOB (job), "%s", err->message); /* reset the error */ g_clear_error (&err); /* check whether to retry */ if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY)) goto retry_remove; } } } g_object_unref (real_target_file); } else if (err != NULL) { /* we can only skip if there is space left on the device */ if (err->domain != G_IO_ERROR || err->code != G_IO_ERROR_NO_SPACE) { /* ask the user to skip this node and all subnodes */ response = thunar_job_ask_skip (THUNAR_JOB (job), "%s", err->message); /* reset the error */ g_clear_error (&err); /* check whether to retry */ if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY)) goto retry_copy; } } /* release the guessed target file */ g_object_unref (target_file); target_file = NULL; /* release file info */ g_object_unref (info); } /* release the thumbnail cache */ g_object_unref (thumbnail_cache); /* propagate error if we failed or the job was cancelled */ if (G_UNLIKELY (err != NULL)) g_propagate_error (error, err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-134'], 'message': 'Don't interpret file display names as format strings This avoids a segfault when copying/moving files containing "%" formatters in their name. Signed-off-by: Jannis Pohlmann <jannis@xfce.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg) { struct option_set **opt_list = arg; char *opt, *val, *endptr; char *str; const struct dhcp_optflag *optflag; struct dhcp_optflag bin_optflag; unsigned optcode; int retval, length; char buffer[8] ALIGNED(4); uint16_t *result_u16 = (uint16_t *) buffer; uint32_t *result_u32 = (uint32_t *) buffer; /* Cheat, the only *const* str possible is "" */ str = (char *) const_str; opt = strtok(str, " \t="); if (!opt) return 0; optcode = bb_strtou(opt, NULL, 0); if (!errno && optcode < 255) { /* Raw (numeric) option code */ bin_optflag.flags = OPTION_BIN; bin_optflag.code = optcode; optflag = &bin_optflag; } else { optflag = &dhcp_optflags[udhcp_option_idx(opt)]; } retval = 0; do { val = strtok(NULL, ", \t"); if (!val) break; length = dhcp_option_lengths[optflag->flags & OPTION_TYPE_MASK]; retval = 0; opt = buffer; /* new meaning for variable opt */ switch (optflag->flags & OPTION_TYPE_MASK) { case OPTION_IP: retval = udhcp_str2nip(val, buffer); break; case OPTION_IP_PAIR: retval = udhcp_str2nip(val, buffer); val = strtok(NULL, ", \t/-"); if (!val) retval = 0; if (retval) retval = udhcp_str2nip(val, buffer + 4); break; case OPTION_STRING: #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: #endif length = strnlen(val, 254); if (length > 0) { opt = val; retval = 1; } break; // case OPTION_BOOLEAN: { // static const char no_yes[] ALIGN1 = "no\0yes\0"; // buffer[0] = retval = index_in_strings(no_yes, val); // retval++; /* 0 - bad; 1: "no" 2: "yes" */ // break; // } case OPTION_U8: buffer[0] = strtoul(val, &endptr, 0); retval = (endptr[0] == '\0'); break; /* htonX are macros in older libc's, using temp var * in code below for safety */ /* TODO: use bb_strtoX? */ case OPTION_U16: { unsigned long tmp = strtoul(val, &endptr, 0); *result_u16 = htons(tmp); retval = (endptr[0] == '\0' /*&& tmp < 0x10000*/); break; } // case OPTION_S16: { // long tmp = strtol(val, &endptr, 0); // *result_u16 = htons(tmp); // retval = (endptr[0] == '\0'); // break; // } case OPTION_U32: { unsigned long tmp = strtoul(val, &endptr, 0); *result_u32 = htonl(tmp); retval = (endptr[0] == '\0'); break; } case OPTION_S32: { long tmp = strtol(val, &endptr, 0); *result_u32 = htonl(tmp); retval = (endptr[0] == '\0'); break; } case OPTION_BIN: /* handled in attach_option() */ opt = val; retval = 1; default: break; } if (retval) attach_option(opt_list, optflag, opt, length); } while (retval && optflag->flags & OPTION_LIST); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'udhcpc: sanitize hostnames in incoming packets. Closes 3979. The following options are replaced with string "bad" if they contain malformed hostname: HOST_NAME, DOMAIN_NAME, NIS_DOMAIN, TFTP_SERVER_NAME function old new delta xmalloc_optname_optval 850 888 +38 attach_option 440 443 +3 len_of_option_as_string 13 14 +1 dhcp_option_lengths 13 14 +1 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 4/0 up/down: 43/0) Total: 43 bytes Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: png_error_callback(png_structp png_read_ptr, png_const_charp error_msg) { LoadContext* lc; lc = png_get_error_ptr(png_read_ptr); lc->fatal_error_occurred = TRUE; /* I don't trust libpng to call the error callback only once, * so check for already-set error */ if (lc->error && *lc->error == NULL) { g_set_error (lc->error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("Fatal error reading PNG image file: %s"), error_msg); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <jrb@redhat.com> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: new_context (void) { GifContext *context; context = g_new0 (GifContext, 1); context->animation = g_object_new (GDK_TYPE_PIXBUF_GIF_ANIM, NULL); context->frame = NULL; context->file = NULL; context->state = GIF_START; context->prepare_func = NULL; context->update_func = NULL; context->user_data = NULL; context->buf = NULL; context->amount_needed = 0; context->gif89.transparent = -1; context->gif89.delay_time = -1; context->gif89.input_flag = -1; context->gif89.disposal = -1; return context; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <jrb@redhat.com> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ssize_t tpm_read(struct file *file, char __user *buf, size_t size, loff_t *off) { struct tpm_chip *chip = file->private_data; ssize_t ret_size; del_singleshot_timer_sync(&chip->user_read_timer); flush_work_sync(&chip->work); ret_size = atomic_read(&chip->data_pending); atomic_set(&chip->data_pending, 0); if (ret_size > 0) { /* relay data */ if (size < ret_size) ret_size = size; mutex_lock(&chip->buffer_mutex); if (copy_to_user(buf, chip->data_buffer, ret_size)) ret_size = -EFAULT; mutex_unlock(&chip->buffer_mutex); } return ret_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'TPM: Zero buffer after copying to userspace Since the buffer might contain security related data it might be a good idea to zero the buffer after we have copied it to userspace. This got assigned CVE-2011-1162. Signed-off-by: Rajiv Andrade <srajiv@linux.vnet.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline long div_long_long_rem_signed(const long long dividend, const long divisor, long *remainder) { long res; if (unlikely(dividend < 0)) { res = -div_long_long_rem(-dividend, divisor, remainder); *remainder = -(*remainder); } else res = div_long_long_rem(dividend, divisor, remainder); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <zippel@linux-m68k.org> Cc: Ralf Baechle <ralf@linux-mips.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: john stultz <johnstul@us.ibm.com> Cc: Christoph Lameter <clameter@sgi.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: */ static xmlXPathParserContextPtr xmlXPathCompParserContext(xmlXPathCompExprPtr comp, xmlXPathContextPtr ctxt) { xmlXPathParserContextPtr ret; ret = (xmlXPathParserContextPtr) xmlMalloc(sizeof(xmlXPathParserContext)); if (ret == NULL) { xmlXPathErrMemory(ctxt, "creating evaluation context\n"); return(NULL); } memset(ret, 0 , (size_t) sizeof(xmlXPathParserContext)); /* Allocate the value stack */ ret->valueTab = (xmlXPathObjectPtr *) xmlMalloc(10 * sizeof(xmlXPathObjectPtr)); if (ret->valueTab == NULL) { xmlFree(ret); xmlXPathErrMemory(ctxt, "creating evaluation context\n"); return(NULL); } ret->valueNr = 0; ret->valueMax = 10; ret->value = NULL; ret->context = ctxt; ret->comp = comp; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation Add a mechanism of frame for XPath evaluation when entering a function or a scoped evaluation, also fix a potential problem in predicate evaluation.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf) { SCSIRequest *req = &r->req; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); uint64_t nb_sectors; int buflen = 0; switch (req->cmd.buf[0]) { case TEST_UNIT_READY: if (s->tray_open || !bdrv_is_inserted(s->bs)) goto not_ready; break; case INQUIRY: buflen = scsi_disk_emulate_inquiry(req, outbuf); if (buflen < 0) goto illegal_request; break; case MODE_SENSE: case MODE_SENSE_10: buflen = scsi_disk_emulate_mode_sense(r, outbuf); if (buflen < 0) goto illegal_request; break; case READ_TOC: buflen = scsi_disk_emulate_read_toc(req, outbuf); if (buflen < 0) goto illegal_request; break; case RESERVE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RESERVE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case RELEASE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RELEASE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case START_STOP: if (scsi_disk_emulate_start_stop(r) < 0) { return -1; } break; case ALLOW_MEDIUM_REMOVAL: s->tray_locked = req->cmd.buf[4] & 1; bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1); break; case READ_CAPACITY_10: /* The normal LEN field for this command is zero. */ memset(outbuf, 0, 8); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; /* Clip to 2TB, instead of returning capacity modulo 2TB. */ if (nb_sectors > UINT32_MAX) nb_sectors = UINT32_MAX; outbuf[0] = (nb_sectors >> 24) & 0xff; outbuf[1] = (nb_sectors >> 16) & 0xff; outbuf[2] = (nb_sectors >> 8) & 0xff; outbuf[3] = nb_sectors & 0xff; outbuf[4] = 0; outbuf[5] = 0; outbuf[6] = s->cluster_size * 2; outbuf[7] = 0; buflen = 8; break; case GET_CONFIGURATION: memset(outbuf, 0, 8); /* ??? This should probably return much more information. For now just return the basic header indicating the CD-ROM profile. */ outbuf[7] = 8; // CD-ROM buflen = 8; break; case SERVICE_ACTION_IN_16: /* Service Action In subcommands. */ if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) { DPRINTF("SAI READ CAPACITY(16)\n"); memset(outbuf, 0, req->cmd.xfer); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; outbuf[0] = (nb_sectors >> 56) & 0xff; outbuf[1] = (nb_sectors >> 48) & 0xff; outbuf[2] = (nb_sectors >> 40) & 0xff; outbuf[3] = (nb_sectors >> 32) & 0xff; outbuf[4] = (nb_sectors >> 24) & 0xff; outbuf[5] = (nb_sectors >> 16) & 0xff; outbuf[6] = (nb_sectors >> 8) & 0xff; outbuf[7] = nb_sectors & 0xff; outbuf[8] = 0; outbuf[9] = 0; outbuf[10] = s->cluster_size * 2; outbuf[11] = 0; outbuf[12] = 0; outbuf[13] = get_physical_block_exp(&s->qdev.conf); /* set TPE bit if the format supports discard */ if (s->qdev.conf.discard_granularity) { outbuf[14] = 0x80; } /* Protection, exponent and lowest lba field left blank. */ buflen = req->cmd.xfer; break; } DPRINTF("Unsupported Service Action In\n"); goto illegal_request; case VERIFY_10: break; default: scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return -1; } return buflen; not_ready: if (s->tray_open || !bdrv_is_inserted(s->bs)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); } else { scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY)); } return -1; illegal_request: if (r->req.status == -1) { scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); } return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int open_group(char *name, int has_prefix, struct backend **ret, int *postable /* used for LIST ACTIVE only */) { char mailboxname[MAX_MAILBOX_BUFFER]; int r = 0; char *acl, *newserver; struct backend *backend_next = NULL; /* close local group */ if (group_state) index_close(&group_state); if (!has_prefix) { snprintf(mailboxname, sizeof(mailboxname), "%s%s", newsprefix, name); name = mailboxname; } if (!r) r = mlookup(name, &newserver, &acl, NULL); if (!r && acl) { int myrights = cyrus_acl_myrights(nntp_authstate, acl); if (postable) *postable = myrights & ACL_POST; if (!postable && /* allow limited 'r' for LIST ACTIVE */ !(myrights & ACL_READ)) { r = (myrights & ACL_LOOKUP) ? IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT; } } if (r) return r; if (newserver) { /* remote group */ backend_next = proxy_findserver(newserver, &nntp_protocol, nntp_userid ? nntp_userid : "anonymous", &backend_cached, &backend_current, NULL, nntp_in); if (!backend_next) return IMAP_SERVER_UNAVAILABLE; *ret = backend_next; } else { /* local group */ struct index_init init; memset(&init, 0, sizeof(struct index_init)); init.userid = nntp_userid; init.authstate = nntp_authstate; r = index_open(name, &init, &group_state); if (r) return r; if (ret) *ret = NULL; } syslog(LOG_DEBUG, "open: user %s opened %s", nntp_userid ? nntp_userid : "anonymous", name); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes Discovered by Stefan Cornelius, Secunia Research The vulnerability is caused due to the access restriction for certain commands only checking whether or not variable "nntp_userid" is non-NULL, without performing additional checks to verify that a complete, successful authentication actually took place. The variable "nntp_userid" can be set to point to a string holding the username (changing it to a non-NULL, thus allowing attackers to bypass the checks) by sending an "AUTHINFO USER" command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO PASS" command is received. This can be exploited to bypass the authentication mechanism and allows access to e.g. the "NEWNEWS" or the "LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a following "AUTHINFO PASS" command.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *getusername(void) { char *username = NULL; struct passwd *password = getpwuid(getuid()); if (password) username = password->pw_name; return username; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'mount.cifs: guard against signals by unprivileged users If mount.cifs is setuid root, then the unprivileged user who runs the program can send the mount.cifs process a signal and kill it. This is not a huge problem unless we happen to be updating the mtab at the time, in which case the mtab lockfiles might not get cleaned up. To remedy this, have the privileged mount.cifs process set its real uid to the effective uid (usually, root). This prevents unprivileged users from being able to signal the process. While we're at it, also mask off signals while we're updating the mtab. This leaves a SIGKILL by root as the only way to interrupt the mtab update, but there's really nothing we can do about that. Signed-off-by: Jeff Layton <jlayton@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int _assemble_line(FILE *f, char *buffer, int buf_len) { char *p = buffer; char *s, *os; int used = 0; /* loop broken with a 'break' when a non-'\\n' ended line is read */ D(("called.")); for (;;) { if (used >= buf_len) { /* Overflow */ D(("_assemble_line: overflow")); return -1; } if (fgets(p, buf_len - used, f) == NULL) { if (used) { /* Incomplete read */ return -1; } else { /* EOF */ return 0; } } /* skip leading spaces --- line may be blank */ s = p + strspn(p, " \n\t"); if (*s && (*s != '#')) { os = s; /* * we are only interested in characters before the first '#' * character */ while (*s && *s != '#') ++s; if (*s == '#') { *s = '\0'; used += strlen(os); break; /* the line has been read */ } s = os; /* * Check for backslash by scanning back from the end of * the entered line, the '\n' has been included since * normally a line is terminated with this * character. fgets() should only return one though! */ s += strlen(s); while (s > os && ((*--s == ' ') || (*s == '\t') || (*s == '\n'))); /* check if it ends with a backslash */ if (*s == '\\') { *s = '\0'; /* truncate the line here */ used += strlen(os); p = s; /* there is more ... */ } else { /* End of the line! */ used += strlen(os); break; /* this is the complete line */ } } else { /* Nothing in this line */ /* Don't move p */ } } return used; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pam_env: correctly count leading whitespace when parsing environment file * modules/pam_env/pam_env.c (_assemble_line): Correctly count leading whitespace. Fixes CVE-2011-3148. Bug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/pam/+bug/874469'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tor_tls_context_init(int is_public_server, crypto_pk_env_t *client_identity, crypto_pk_env_t *server_identity, unsigned int key_lifetime) { int rv1 = 0; int rv2 = 0; if (is_public_server) { tor_tls_context_t *new_ctx; tor_tls_context_t *old_ctx; tor_assert(server_identity != NULL); rv1 = tor_tls_context_init_one(&server_tls_context, server_identity, key_lifetime); if (rv1 >= 0) { new_ctx = server_tls_context; tor_tls_context_incref(new_ctx); old_ctx = client_tls_context; client_tls_context = new_ctx; if (old_ctx != NULL) { tor_tls_context_decref(old_ctx); } } } else { if (server_identity != NULL) { rv1 = tor_tls_context_init_one(&server_tls_context, server_identity, key_lifetime); } else { tor_tls_context_t *old_ctx = server_tls_context; server_tls_context = NULL; if (old_ctx != NULL) { tor_tls_context_decref(old_ctx); } } rv2 = tor_tls_context_init_one(&client_tls_context, client_identity, key_lifetime); } return rv1 < rv2 ? rv1 : rv2; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't send a certificate chain on outgoing TLS connections from non-relays'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } *session_data_size = psession.size; if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'gnutls_session_get_data: fix possible buffer overflow The test to avoid the buffer overflow was always false because session_data_size was set at the wrong place. This problem has been introduced by this commit: |commit ad4ed44c65e753e6d3a00104c049dd81826ccbf3 |Author: Nikos Mavrogiannopoulos <nmav@gnutls.org> |Date: Mon Nov 7 22:24:48 2005 +0000 | | This is the initial commit in the 1.3 branch. Ported from the PSK branch: | * PSK ciphersuites have been added. | * The session resumption data are now system independent. Signed-off-by: Nikos Mavrogiannopoulos <nmav@gnutls.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlDictComputeFastQKey(const xmlChar *prefix, int plen, const xmlChar *name, int len) { unsigned long value = 0L; if (plen == 0) value += 30 * (unsigned long) ':'; else value += 30 * (*prefix); if (len > 10) { value += name[len - (plen + 1 + 1)]; len = 10; if (plen > 10) plen = 10; } switch (plen) { case 10: value += prefix[9]; case 9: value += prefix[8]; case 8: value += prefix[7]; case 7: value += prefix[6]; case 6: value += prefix[5]; case 5: value += prefix[4]; case 4: value += prefix[3]; case 3: value += prefix[2]; case 2: value += prefix[1]; case 1: value += prefix[0]; default: break; } len -= plen; if (len > 0) { value += (unsigned long) ':'; len--; } switch (len) { case 10: value += name[9]; case 9: value += name[8]; case 8: value += name[7]; case 7: value += name[6]; case 6: value += name[5]; case 5: value += name[4]; case 4: value += name[3]; case 3: value += name[2]; case 2: value += name[1]; case 1: value += name[0]; default: break; } return(value); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void preempt_conditional_sti(struct pt_regs *regs) { inc_preempt_count(); if (regs->flags & X86_EFLAGS_IF) local_irq_enable(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'x86: Do not disable preemption in int3 on 32bit Preemption must be disabled before enabling interrupts in do_trap on x86_64 because the stack in use for int3 and debug is a per CPU stack set by th IST. But 32bit does not have an IST and the stack still belongs to the current task and there is no problem in scheduling out the task. Keep preemption enabled on X86_32 when enabling interrupts for do_trap(). The name of the function is changed from preempt_conditional_sti/cli() to conditional_sti/cli_ist(), to annotate that this function is used when the stack is on the IST. Cc: stable-rt@vger.kernel.org Signed-off-by: Steven Rostedt <rostedt@goodmis.org> Signed-off-by: Thomas Gleixner <tglx@linutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: log2vis_utf8 (PyObject * string, int unicode_length, FriBidiParType base_direction, int clean, int reordernsm) { FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ char *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyObject *result = NULL; /* failure */ /* Allocate fribidi unicode buffers */ logical = PyMem_New (FriBidiChar, unicode_length + 1); if (logical == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } visual = PyMem_New (FriBidiChar, unicode_length + 1); if (visual == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); fribidi_utf8_to_unicode (PyString_AS_STRING (string), PyString_GET_SIZE (string), logical); if (!fribidi_log2vis (logical, unicode_length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) fribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL); /* Allocate fribidi UTF-8 buffer */ visual_utf8 = PyMem_New(char, (unicode_length * 4)+1); if (visual_utf8 == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate UTF-8 buffer"); goto cleanup; } /* Encode the reordered string and create result string */ new_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8); result = PyString_FromStringAndSize (visual_utf8, new_len); if (result == NULL) /* XXX does it raise any error? */ goto cleanup; cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); PyMem_Del (visual_utf8); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GnashImage::GnashImage(size_t width, size_t height, ImageType type, ImageLocation location) : _type(type), _location(location), _width(width), _height(height) { const size_t max = std::numeric_limits<boost::int32_t>::max(); if (size() > max) { throw std::bad_alloc(); } _data.reset(new value_type[size()]); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix crash in GnashImage.cpp'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mem_cgroup_move_charge_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { int ret = 0; struct vm_area_struct *vma = walk->private; pte_t *pte; spinlock_t *ptl; split_huge_page_pmd(walk->mm, pmd); retry: pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; addr += PAGE_SIZE) { pte_t ptent = *(pte++); union mc_target target; int type; struct page *page; struct page_cgroup *pc; swp_entry_t ent; if (!mc.precharge) break; type = is_target_pte_for_mc(vma, addr, ptent, &target); switch (type) { case MC_TARGET_PAGE: page = target.page; if (isolate_lru_page(page)) goto put; pc = lookup_page_cgroup(page); if (!mem_cgroup_move_account(page, 1, pc, mc.from, mc.to, false)) { mc.precharge--; /* we uncharge from mc.from later. */ mc.moved_charge++; } putback_lru_page(page); put: /* is_target_pte_for_mc() gets the page */ put_page(page); break; case MC_TARGET_SWAP: ent = target.ent; if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to, false)) { mc.precharge--; /* we fixup refcnts and charges later. */ mc.moved_swap++; } break; default: break; } } pte_unmap_unlock(pte - 1, ptl); cond_resched(); if (addr != end) { /* * We have consumed all precharges we got in can_attach(). * We try charge one by one, but don't do any additional * charges to mc.to if we have failed in charge once in attach() * phase. */ ret = mem_cgroup_do_precharge(1); if (!ret) goto retry; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [akpm@linux-foundation.org: checkpatch fixes] Reported-by: Ulrich Obergfell <uobergfe@redhat.com> Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Dave Jones <davej@redhat.com> Acked-by: Larry Woodman <lwoodman@redhat.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: <stable@vger.kernel.org> [2.6.38+] Cc: Mark Salter <msalter@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, size_t count) { size_t i; cdf_timestamp_t tp; struct timespec ts; char buf[64]; const char *str = NULL; const char *s; int len; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf, info[i].pi_s16) == -1) return -1; break; case CDF_SIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf, info[i].pi_s32) == -1) return -1; break; case CDF_UNSIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf, info[i].pi_u32) == -1) return -1; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: len = info[i].pi_str.s_len; if (len > 1) { char vbuf[1024]; size_t j, k = 1; if (info[i].pi_type == CDF_LENGTH32_WSTRING) k++; s = info[i].pi_str.s_buf; for (j = 0; j < sizeof(vbuf) && len--; j++, s += k) { if (*s == '\0') break; if (isprint((unsigned char)*s)) vbuf[j] = *s; } if (j == sizeof(vbuf)) --j; vbuf[j] = '\0'; if (NOTMIME(ms)) { if (vbuf[0]) { if (file_printf(ms, ", %s: %s", buf, vbuf) == -1) return -1; } } else if (info[i].pi_id == CDF_PROPERTY_NAME_OF_APPLICATION) { if (strstr(vbuf, "Word")) str = "msword"; else if (strstr(vbuf, "Excel")) str = "vnd.ms-excel"; else if (strstr(vbuf, "Powerpoint")) str = "vnd.ms-powerpoint"; else if (strstr(vbuf, "Crystal Reports")) str = "x-rpt"; } } break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp != 0) { if (tp < 1000000000000000LL) { char tbuf[64]; cdf_print_elapsed_time(tbuf, sizeof(tbuf), tp); if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, tbuf) == -1) return -1; } else { char *c, *ec; cdf_timestamp_to_timespec(&ts, tp); c = cdf_ctime(&ts.tv_sec); if ((ec = strchr(c, '\n')) != NULL) *ec = '\0'; if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, c) == -1) return -1; } } break; case CDF_CLIPBOARD: break; default: return -1; } } if (!NOTMIME(ms)) { if (str == NULL) return 0; if (file_printf(ms, "application/%s", str) == -1) return -1; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': '- add float and double types - fix debug printf formats - fix short stream sizes - don't fail if we don't know about a type'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos > ss * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos, ss * sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bounds checks again.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int kvm_iommu_map_guest(struct kvm *kvm) { int r; if (!iommu_present(&pci_bus_type)) { printk(KERN_ERR "%s: iommu not found\n", __func__); return -ENODEV; } kvm->arch.iommu_domain = iommu_domain_alloc(&pci_bus_type); if (!kvm->arch.iommu_domain) return -ENOMEM; if (!allow_unsafe_assigned_interrupts && !iommu_domain_has_cap(kvm->arch.iommu_domain, IOMMU_CAP_INTR_REMAP)) { printk(KERN_WARNING "%s: No interrupt remapping support," " disallowing device assignment." " Re-enble with \"allow_unsafe_assigned_interrupts=1\"" " module option.\n", __func__); iommu_domain_free(kvm->arch.iommu_domain); kvm->arch.iommu_domain = NULL; return -EPERM; } r = kvm_iommu_map_memslots(kvm); if (r) goto out_unmap; return 0; out_unmap: kvm_iommu_unmap_memslots(kvm); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'KVM: lock slots_lock around device assignment As pointed out by Jason Baron, when assigning a device to a guest we first set the iommu domain pointer, which enables mapping and unmapping of memory slots to the iommu. This leaves a window where this path is enabled, but we haven't synchronized the iommu mappings to the existing memory slots. Thus a slot being removed at that point could send us down unexpected code paths removing non-existent pinnings and iommu mappings. Take the slots_lock around creating the iommu domain and initial mappings as well as around iommu teardown to avoid this race. Signed-off-by: Alex Williamson <alex.williamson@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_bitmap_file_data (FILE *fstream, guint *width, guint *height, guchar **data, int *x_hot, int *y_hot) { guchar *bits = NULL; /* working variable */ char line[MAX_SIZE]; /* input line from file */ int size; /* number of bytes of data */ char name_and_type[MAX_SIZE]; /* an input line */ char *type; /* for parsing */ int value; /* from an input line */ int version10p; /* boolean, old format */ int padding; /* to handle alignment */ int bytes_per_line; /* per scanline of data */ guint ww = 0; /* width */ guint hh = 0; /* height */ int hx = -1; /* x hotspot */ int hy = -1; /* y hotspot */ /* first time initialization */ if (!initialized) { init_hex_table (); } /* error cleanup and return macro */ #define RETURN(code) { g_free (bits); return code; } while (fgets (line, MAX_SIZE, fstream)) { if (strlen (line) == MAX_SIZE-1) RETURN (FALSE); if (sscanf (line,"#define %s %d",name_and_type,&value) == 2) { if (!(type = strrchr (name_and_type, '_'))) type = name_and_type; else { type++; } if (!strcmp ("width", type)) ww = (unsigned int) value; if (!strcmp ("height", type)) hh = (unsigned int) value; if (!strcmp ("hot", type)) { if (type-- == name_and_type || type-- == name_and_type) continue; if (!strcmp ("x_hot", type)) hx = value; if (!strcmp ("y_hot", type)) hy = value; } continue; } if (sscanf (line, "static short %s = {", name_and_type) == 1) version10p = 1; else if (sscanf (line,"static const unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf (line,"static unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf (line, "static const char %s = {", name_and_type) == 1) version10p = 0; else if (sscanf (line, "static char %s = {", name_and_type) == 1) version10p = 0; else continue; if (!(type = strrchr (name_and_type, '_'))) type = name_and_type; else type++; if (strcmp ("bits[]", type)) continue; if (!ww || !hh) RETURN (FALSE); if ((ww % 16) && ((ww % 16) < 9) && version10p) padding = 1; else padding = 0; bytes_per_line = (ww+7)/8 + padding; size = bytes_per_line * hh; bits = g_malloc (size); if (version10p) { unsigned char *ptr; int bytes; for (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) { if ((value = next_int (fstream)) < 0) RETURN (FALSE); *(ptr++) = value; if (!padding || ((bytes+2) % bytes_per_line)) *(ptr++) = value >> 8; } } else { unsigned char *ptr; int bytes; for (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) { if ((value = next_int (fstream)) < 0) RETURN (FALSE); *ptr=value; } } break; } if (!bits) RETURN (FALSE); *data = bits; *width = ww; *height = hh; if (x_hot) *x_hot = hx; if (y_hot) *y_hot = hy; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Avoid an integer overflow in the xbm loader At the same time, reject some silly input, such as negative width or height. https://bugzilla.gnome.org/show_bug.cgi?id=672811'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k) { void *result; size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; DCL_LOCK_STATE; if (SMALL_OBJ(lb)) return(GC_generic_malloc((word)lb, k)); lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); LOCK(); result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; if (0 == result) { GC_oom_func oom_fn = GC_oom_fn; UNLOCK(); return((*oom_fn)(lb)); } else { UNLOCK(); if (init && !GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } return(result); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix allocation size overflows due to rounding. * malloc.c (GC_generic_malloc): Check if the allocation size is rounded to a smaller value. * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: handle_subnets_accessed(CMD_Request *rx_message, CMD_Reply *tx_message) { int i, j; unsigned long ns, bits_specd; IPAddr ip; CLG_Status result; ns = ntohl(rx_message->data.subnets_accessed.n_subnets); tx_message->status = htons(STT_SUCCESS); tx_message->reply = htons(RPY_SUBNETS_ACCESSED); tx_message->data.subnets_accessed.n_subnets = htonl(ns); for (i=0; i<ns; i++) { UTI_IPNetworkToHost(&rx_message->data.subnets_accessed.subnets[i].ip, &ip); bits_specd = ntohl(rx_message->data.subnets_accessed.subnets[i].bits_specd); UTI_IPHostToNetwork(&ip, &tx_message->data.subnets_accessed.subnets[i].ip); tx_message->data.subnets_accessed.subnets[i].bits_specd = htonl(bits_specd); result = CLG_GetSubnetBitmap(&ip, bits_specd, tx_message->data.subnets_accessed.subnets[i].bitmap); switch (result) { case CLG_SUCCESS: case CLG_EMPTYSUBNET: /* Flip endianness of each 4 byte word. Don't care if subnet is empty - just return an all-zero bitmap. */ for (j=0; j<8; j++) { FLIPL(tx_message->data.subnets_accessed.subnets[i].bitmap[j]); } break; case CLG_BADSUBNET: tx_message->status = htons(STT_BADSUBNET); return; case CLG_INACTIVE: tx_message->status = htons(STT_INACTIVE); return; default: assert(0); break; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Don't send uninitialized data in command replies The RPY_SUBNETS_ACCESSED and RPY_CLIENT_ACCESSES command replies can contain uninitalized data from stack when the client logging is disabled or a bad subnet is requested. These commands were never used by chronyc and they require the client to be authenticated since version 1.25.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void _out_result(conn_t out, nad_t nad) { int attr; jid_t from, to; char *rkey; int rkeylen; attr = nad_find_attr(nad, 0, -1, "from", NULL); if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid from on db result packet"); nad_free(nad); return; } attr = nad_find_attr(nad, 0, -1, "to", NULL); if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid to on db result packet"); jid_free(from); nad_free(nad); return; } rkey = s2s_route_key(NULL, to->domain, from->domain); rkeylen = strlen(rkey); /* key is valid */ if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0) { log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : ""); xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */ log_debug(ZONE, "%s valid, flushing queue", rkey); /* flush the queue */ out_flush_route_queue(out->s2s, rkey, rkeylen); free(rkey); jid_free(from); jid_free(to); nad_free(nad); return; } /* invalid */ log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey); /* close connection */ log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port); /* report stream error */ sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed"); /* close the stream */ sx_close(out->s); /* bounce queue */ out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE); free(rkey); jid_free(from); jid_free(to); nad_free(nad); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed possibility of Unsolicited Dialback Attacks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int inet_sk_rebuild_header(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0); __be32 daddr; int err; /* Route is OK, nothing to do. */ if (rt) return 0; /* Reroute. */ daddr = inet->inet_daddr; if (inet->opt && inet->opt->srr) daddr = inet->opt->faddr; rt = ip_route_output_ports(sock_net(sk), sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (!IS_ERR(rt)) { err = 0; sk_setup_caps(sk, &rt->dst); } else { err = PTR_ERR(rt); /* Routing failed... */ sk->sk_route_caps = 0; /* * Other protocols have to map its equivalent state to TCP_SYN_SENT. * DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme */ if (!sysctl_ip_dynaddr || sk->sk_state != TCP_SYN_SENT || (sk->sk_userlocks & SOCK_BINDADDR_LOCK) || (err = inet_sk_reselect_saddr(sk)) != 0) sk->sk_err_soft = -err; } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static 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; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void cipso_v4_req_delattr(struct request_sock *req) { struct ip_options *opt; struct inet_request_sock *req_inet; req_inet = inet_rsk(req); opt = req_inet->opt; if (opt == NULL || opt->cipso == 0) return; cipso_v4_delopt(&req_inet->opt); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process (GeglOperation *operation, GeglBuffer *output, const GeglRectangle *result, gint level) { GeglChantO *o = GEGL_CHANT_PROPERTIES (operation); FILE *fp; pnm_struct img; GeglRectangle rect = {0,0,0,0}; gboolean ret = FALSE; fp = (!strcmp (o->path, "-") ? stdin : fopen (o->path,"rb")); if (!fp) return FALSE; if (!ppm_load_read_header (fp, &img)) goto out; rect.height = img.height; rect.width = img.width; /* Allocating Array Size */ img.data = (guchar*) g_malloc (img.numsamples * img.bpc); switch (img.bpc) { case 1: gegl_buffer_get (output, &rect, 1.0, babl_format ("R'G'B' u8"), img.data, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE); break; case 2: gegl_buffer_get (output, &rect, 1.0, babl_format ("R'G'B' u16"), img.data, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE); break; default: g_warning ("%s: Programmer stupidity error", G_STRLOC); } ppm_load_read_image (fp, &img); switch (img.bpc) { case 1: gegl_buffer_set (output, &rect, 0, babl_format ("R'G'B' u8"), img.data, GEGL_AUTO_ROWSTRIDE); break; case 2: gegl_buffer_set (output, &rect, 0, babl_format ("R'G'B' u16"), img.data, GEGL_AUTO_ROWSTRIDE); break; default: g_warning ("%s: Programmer stupidity error", G_STRLOC); } g_free (img.data); ret = TRUE; out: if (stdin != fp) fclose (fp); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'ppm-load: CVE-2012-4433: don't overflow memory allocation Carefully selected width/height values could cause the size of a later allocation to overflow, resulting in a buffer much too small to store the data which would then written beyond its end.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xsltAttrTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target, xmlAttrPtr attr) { const xmlChar *value; xmlAttrPtr ret; if ((ctxt == NULL) || (attr == NULL) || (target == NULL) || (target->type != XML_ELEMENT_NODE)) return(NULL); if (attr->type != XML_ATTRIBUTE_NODE) return(NULL); /* * Skip all XSLT attributes. */ #ifdef XSLT_REFACTORED if (attr->psvi == xsltXSLTAttrMarker) return(NULL); #else if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) return(NULL); #endif /* * Get the value. */ if (attr->children != NULL) { if ((attr->children->type != XML_TEXT_NODE) || (attr->children->next != NULL)) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: The children of an attribute node of a " "literal result element are not in the expected form.\n"); return(NULL); } value = attr->children->content; if (value == NULL) value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); } else value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); /* * Overwrite duplicates. */ ret = target->properties; while (ret != NULL) { if (((attr->ns != NULL) == (ret->ns != NULL)) && xmlStrEqual(ret->name, attr->name) && ((attr->ns == NULL) || xmlStrEqual(ret->ns->href, attr->ns->href))) { break; } ret = ret->next; } if (ret != NULL) { /* free the existing value */ xmlFreeNodeList(ret->children); ret->children = ret->last = NULL; /* * Adjust ns-prefix if needed. */ if ((ret->ns != NULL) && (! xmlStrEqual(ret->ns->prefix, attr->ns->prefix))) { ret->ns = xsltGetNamespace(ctxt, attr->parent, attr->ns, target); } } else { /* create a new attribute */ if (attr->ns != NULL) ret = xmlNewNsProp(target, xsltGetNamespace(ctxt, attr->parent, attr->ns, target), attr->name, NULL); else ret = xmlNewNsProp(target, NULL, attr->name, NULL); } /* * Set the value. */ if (ret != NULL) { xmlNodePtr text; text = xmlNewText(NULL); if (text != NULL) { ret->last = ret->children = text; text->parent = (xmlNodePtr) ret; text->doc = ret->doc; if (attr->psvi != NULL) { /* * Evaluate the Attribute Value Template. */ xmlChar *val; val = xsltEvalAVT(ctxt, attr->psvi, attr->parent); if (val == NULL) { /* * TODO: Damn, we need an easy mechanism to report * qualified names! */ if (attr->ns) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to evaluate the AVT " "of attribute '{%s}%s'.\n", attr->ns->href, attr->name); } else { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to evaluate the AVT " "of attribute '%s'.\n", attr->name); } text->content = xmlStrdup(BAD_CAST ""); } else { text->content = val; } } else if ((ctxt->internalized) && (target != NULL) && (target->doc != NULL) && (target->doc->dict == ctxt->dict)) { text->content = (xmlChar *) value; } else { text->content = xmlStrdup(value); } } } else { if (attr->ns) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to create attribute '{%s}%s'.\n", attr->ns->href, attr->name); } else { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to create attribute '%s'.\n", attr->name); } } return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fix a dictionary string usage Raised in chromium, but also affecting xsltproc Also updated AUTHORS to list Chris and other contributors'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int load_script(struct linux_binprm *bprm) { const char *i_arg, *i_name; char *cp; struct file *file; char interp[BINPRM_BUF_SIZE]; int retval; if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!') || (bprm->recursion_depth > BINPRM_MAX_RECURSION)) return -ENOEXEC; /* * This section does the #! interpretation. * Sorta complicated, but hopefully it will work. -TYT */ bprm->recursion_depth++; allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; bprm->buf[BINPRM_BUF_SIZE - 1] = '\0'; if ((cp = strchr(bprm->buf, '\n')) == NULL) cp = bprm->buf+BINPRM_BUF_SIZE-1; *cp = '\0'; while (cp > bprm->buf) { cp--; if ((*cp == ' ') || (*cp == '\t')) *cp = '\0'; else break; } for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++); if (*cp == '\0') return -ENOEXEC; /* No interpreter name found */ i_name = cp; i_arg = NULL; for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++) /* nothing */ ; while ((*cp == ' ') || (*cp == '\t')) *cp++ = '\0'; if (*cp) i_arg = cp; strcpy (interp, i_name); /* * OK, we've parsed out the interpreter name and * (optional) argument. * Splice in (1) the interpreter's name for argv[0] * (2) (optional) argument to interpreter * (3) filename of shell script (replace argv[0]) * * This is done in reverse order, because of how the * user environment and arguments are stored. */ retval = remove_arg_zero(bprm); if (retval) return retval; retval = copy_strings_kernel(1, &bprm->interp, bprm); if (retval < 0) return retval; bprm->argc++; if (i_arg) { retval = copy_strings_kernel(1, &i_arg, bprm); if (retval < 0) return retval; bprm->argc++; } retval = copy_strings_kernel(1, &i_name, bprm); if (retval) return retval; bprm->argc++; bprm->interp = interp; /* * OK, now restart the process with the interpreter's dentry. */ file = open_exec(interp); if (IS_ERR(file)) return PTR_ERR(file); bprm->file = file; retval = prepare_binprm(bprm); if (retval < 0) return retval; return search_binary_handler(bprm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'exec: use -ELOOP for max recursion depth To avoid an explosion of request_module calls on a chain of abusive scripts, fail maximum recursion with -ELOOP instead of -ENOEXEC. As soon as maximum recursion depth is hit, the error will fail all the way back up the chain, aborting immediately. This also has the side-effect of stopping the user's shell from attempting to reexecute the top-level file as a shell script. As seen in the dash source: if (cmd != path_bshell && errno == ENOEXEC) { *argv-- = cmd; *argv = cmd = path_bshell; goto repeat; } The above logic was designed for running scripts automatically that lacked the "#!" header, not to re-try failed recursion. On a legitimate -ENOEXEC, things continue to behave as the shell expects. Additionally, when tracking recursion, the binfmt handlers should not be involved. The recursion being tracked is the depth of calls through search_binary_handler(), so that function should be exclusively responsible for tracking the depth. Signed-off-by: Kees Cook <keescook@chromium.org> Cc: halfdog <me@halfdog.net> Cc: P J P <ppandit@redhat.com> Cc: Alexander Viro <viro@zeniv.linux.org.uk> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: irc_color_decode (const char *string, int keep_colors) { unsigned char *out, *ptr_string; int out_length, length, out_pos; char str_fg[3], str_bg[3], str_color[128], str_key[128]; const char *remapped_color; int fg, bg, bold, reverse, italic, underline, rc; out_length = (strlen (string) * 2) + 1; out = malloc (out_length); if (!out) return NULL; bold = 0; reverse = 0; italic = 0; underline = 0; ptr_string = (unsigned char *)string; out[0] = '\0'; while (ptr_string && ptr_string[0]) { switch (ptr_string[0]) { case IRC_COLOR_BOLD_CHAR: if (keep_colors) strcat ((char *)out, weechat_color((bold) ? "-bold" : "bold")); bold ^= 1; ptr_string++; break; case IRC_COLOR_RESET_CHAR: if (keep_colors) strcat ((char *)out, weechat_color("reset")); bold = 0; reverse = 0; italic = 0; underline = 0; ptr_string++; break; case IRC_COLOR_FIXED_CHAR: ptr_string++; break; case IRC_COLOR_REVERSE_CHAR: case IRC_COLOR_REVERSE2_CHAR: if (keep_colors) strcat ((char *)out, weechat_color((reverse) ? "-reverse" : "reverse")); reverse ^= 1; ptr_string++; break; case IRC_COLOR_ITALIC_CHAR: if (keep_colors) strcat ((char *)out, weechat_color((italic) ? "-italic" : "italic")); italic ^= 1; ptr_string++; break; case IRC_COLOR_UNDERLINE_CHAR: if (keep_colors) strcat ((char *)out, weechat_color((underline) ? "-underline" : "underline")); underline ^= 1; ptr_string++; break; case IRC_COLOR_COLOR_CHAR: ptr_string++; str_fg[0] = '\0'; str_bg[0] = '\0'; if (isdigit (ptr_string[0])) { str_fg[0] = ptr_string[0]; str_fg[1] = '\0'; ptr_string++; if (isdigit (ptr_string[0])) { str_fg[1] = ptr_string[0]; str_fg[2] = '\0'; ptr_string++; } } if ((ptr_string[0] == ',') && (isdigit (ptr_string[1]))) { ptr_string++; str_bg[0] = ptr_string[0]; str_bg[1] = '\0'; ptr_string++; if (isdigit (ptr_string[0])) { str_bg[1] = ptr_string[0]; str_bg[2] = '\0'; ptr_string++; } } if (keep_colors) { if (str_fg[0] || str_bg[0]) { fg = -1; bg = -1; if (str_fg[0]) { rc = sscanf (str_fg, "%d", &fg); if ((rc != EOF) && (rc >= 1)) { fg %= IRC_NUM_COLORS; } } if (str_bg[0]) { rc = sscanf (str_bg, "%d", &bg); if ((rc != EOF) && (rc >= 1)) { bg %= IRC_NUM_COLORS; } } /* search "fg,bg" in hashtable of remapped colors */ snprintf (str_key, sizeof (str_key), "%d,%d", fg, bg); remapped_color = weechat_hashtable_get ( irc_config_hashtable_color_mirc_remap, str_key); if (remapped_color) { snprintf (str_color, sizeof (str_color), "|%s", remapped_color); } else { snprintf (str_color, sizeof (str_color), "|%s%s%s", (fg >= 0) ? irc_color_to_weechat[fg] : "", (bg >= 0) ? "," : "", (bg >= 0) ? irc_color_to_weechat[bg] : ""); } strcat ((char *)out, weechat_color(str_color)); } else strcat ((char *)out, weechat_color("resetcolor")); } break; default: length = weechat_utf8_char_size ((char *)ptr_string); if (length == 0) length = 1; out_pos = strlen ((char *)out); memcpy (out + out_pos, ptr_string, length); out[out_pos + length] = '\0'; ptr_string += length; break; } } return (char *)out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'irc: fix crash when decoding IRC colors in strings (bug #37704)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: e1000_receive(NetClientState *nc, const uint8_t *buf, size_t size) { E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque; struct e1000_rx_desc desc; dma_addr_t base; unsigned int n, rdt; uint32_t rdh_start; uint16_t vlan_special = 0; uint8_t vlan_status = 0, vlan_offset = 0; uint8_t min_buf[MIN_BUF_SIZE]; size_t desc_offset; size_t desc_size; size_t total_size; if (!(s->mac_reg[RCTL] & E1000_RCTL_EN)) return -1; /* Pad to minimum Ethernet frame length */ if (size < sizeof(min_buf)) { memcpy(min_buf, buf, size); memset(&min_buf[size], 0, sizeof(min_buf) - size); buf = min_buf; size = sizeof(min_buf); } /* Discard oversized packets if !LPE and !SBP. */ if (size > MAXIMUM_ETHERNET_VLAN_SIZE && !(s->mac_reg[RCTL] & E1000_RCTL_LPE) && !(s->mac_reg[RCTL] & E1000_RCTL_SBP)) { return size; } if (!receive_filter(s, buf, size)) return size; if (vlan_enabled(s) && is_vlan_packet(s, buf)) { vlan_special = cpu_to_le16(be16_to_cpup((uint16_t *)(buf + 14))); memmove((uint8_t *)buf + 4, buf, 12); vlan_status = E1000_RXD_STAT_VP; vlan_offset = 4; size -= 4; } rdh_start = s->mac_reg[RDH]; desc_offset = 0; total_size = size + fcs_len(s); if (!e1000_has_rxbufs(s, total_size)) { set_ics(s, 0, E1000_ICS_RXO); return -1; } do { desc_size = total_size - desc_offset; if (desc_size > s->rxbuf_size) { desc_size = s->rxbuf_size; } base = rx_desc_base(s) + sizeof(desc) * s->mac_reg[RDH]; pci_dma_read(&s->dev, base, &desc, sizeof(desc)); desc.special = vlan_special; desc.status |= (vlan_status | E1000_RXD_STAT_DD); if (desc.buffer_addr) { if (desc_offset < size) { size_t copy_size = size - desc_offset; if (copy_size > s->rxbuf_size) { copy_size = s->rxbuf_size; } pci_dma_write(&s->dev, le64_to_cpu(desc.buffer_addr), buf + desc_offset + vlan_offset, copy_size); } desc_offset += desc_size; desc.length = cpu_to_le16(desc_size); if (desc_offset >= total_size) { desc.status |= E1000_RXD_STAT_EOP | E1000_RXD_STAT_IXSM; } else { /* Guest zeroing out status is not a hardware requirement. Clear EOP in case guest didn't do it. */ desc.status &= ~E1000_RXD_STAT_EOP; } } else { // as per intel docs; skip descriptors with null buf addr DBGOUT(RX, "Null RX descriptor!!\n"); } pci_dma_write(&s->dev, base, &desc, sizeof(desc)); if (++s->mac_reg[RDH] * sizeof(desc) >= s->mac_reg[RDLEN]) s->mac_reg[RDH] = 0; /* see comment in start_xmit; same here */ if (s->mac_reg[RDH] == rdh_start) { DBGOUT(RXERR, "RDH wraparound @%x, RDT %x, RDLEN %x\n", rdh_start, s->mac_reg[RDT], s->mac_reg[RDLEN]); set_ics(s, 0, E1000_ICS_RXO); return -1; } } while (desc_offset < total_size); s->mac_reg[GPRC]++; s->mac_reg[TPR]++; /* TOR - Total Octets Received: * This register includes bytes received in a packet from the <Destination * Address> field through the <CRC> field, inclusively. */ n = s->mac_reg[TORL] + size + /* Always include FCS length. */ 4; if (n < s->mac_reg[TORL]) s->mac_reg[TORH]++; s->mac_reg[TORL] = n; n = E1000_ICS_RXT0; if ((rdt = s->mac_reg[RDT]) < s->mac_reg[RDH]) rdt += s->mac_reg[RDLEN] / sizeof(desc); if (((rdt - s->mac_reg[RDH]) * sizeof(desc)) <= s->mac_reg[RDLEN] >> s->rxbuf_min_shift) n |= E1000_ICS_RXDMT0; set_ics(s, 0, n); return size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'e1000: Discard oversized packets based on SBP|LPE Discard packets longer than 16384 when !SBP to match the hardware behavior. Signed-off-by: Michael Contreras <michael@inetric.com> Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: charclass_index (charclass const s) { int i; for (i = 0; i < dfa->cindex; ++i) if (equal(s, dfa->charclasses[i])) return i; REALLOC_IF_NECESSARY(dfa->charclasses, dfa->calloc, dfa->cindex + 1); ++dfa->cindex; copyset(s, dfa->charclasses[i]); return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc. These problems mostly occur because the code attempts to stuff sizes into int or into unsigned int; this doesn't work on most 64-bit hosts and the errors can lead to core dumps. * NEWS: Document this. * src/dfa.c (token): Typedef to ptrdiff_t, since the enum's range could be as small as -128 .. 127 on practical hosts. (position.index): Now size_t, not unsigned int. (leaf_set.elems): Now size_t *, not unsigned int *. (dfa_state.hash, struct mb_char_classes.nchars, .nch_classes) (.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex) (.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets): (.mbcsets_alloc): Now size_t, not int. (dfa_state.first_end): Now token, not int. (state_num): New type. (struct mb_char_classes.cset): Now ptrdiff_t, not int. (struct dfa.utf8_anychar_classes): Now token[5], not int[5]. (struct dfa.sindex, .salloc, .tralloc): Now state_num, not int. (struct dfa.trans, .realtrans, .fails): Now state_num **, not int **. (struct dfa.newlines): Now state_num *, not int *. (prtok): Don't assume 'token' is no wider than int. (lexleft, parens, depth): Now size_t, not int. (charclass_index, nsubtoks) (parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete) (state_index, epsclosure, state_separate_contexts) (dfaanalyze, dfastate, build_state, realloc_trans_if_necessary) (transit_state_singlebyte, match_anychar, match_mb_charset) (check_matching_with_multibyte_ops, transit_state_consume_1char) (transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree) (freelist, enlist, addlists, inboth, dfamust): Don't assume indexes fit in 'int'. (lex): Avoid overflow in string-to-{hi,lo} conversions. (dfaanalyze): Redo indexing so that it works with size_t values, which cannot go negative. * src/dfa.h (dfaexec): Count argument is now size_t *, not int *. (dfastate): State numbers are now ptrdiff_t, not int. * src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM. (kwset_exact_matches): Now size_t, not int. (EGexecute): Don't assume indexes fit in 'int'. Check for overflow before converting a ptrdiff_t to a regoff_t, as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX). Check for memory exhaustion in re_search rather than treating it merely as failure to match; use xalloc_die () to report any error. * src/kwset.c (struct trie.accepting): Now size_t, not unsigned int. (struct kwset.words): Now ptrdiff_t, not int. * src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: match_anychar (struct dfa *d, int s, position pos, int idx) { int context; wchar_t wc; int mbclen; wc = inputwcs[idx]; mbclen = (mblen_buf[idx] == 0)? 1 : mblen_buf[idx]; /* Check syntax bits. */ if (wc == (wchar_t)eolbyte) { if (!(syntax_bits & RE_DOT_NEWLINE)) return 0; } else if (wc == (wchar_t)'\0') { if (syntax_bits & RE_DOT_NOT_NULL) return 0; } context = wchar_context(wc); if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].context, context)) return 0; return mbclen; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc. These problems mostly occur because the code attempts to stuff sizes into int or into unsigned int; this doesn't work on most 64-bit hosts and the errors can lead to core dumps. * NEWS: Document this. * src/dfa.c (token): Typedef to ptrdiff_t, since the enum's range could be as small as -128 .. 127 on practical hosts. (position.index): Now size_t, not unsigned int. (leaf_set.elems): Now size_t *, not unsigned int *. (dfa_state.hash, struct mb_char_classes.nchars, .nch_classes) (.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex) (.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets): (.mbcsets_alloc): Now size_t, not int. (dfa_state.first_end): Now token, not int. (state_num): New type. (struct mb_char_classes.cset): Now ptrdiff_t, not int. (struct dfa.utf8_anychar_classes): Now token[5], not int[5]. (struct dfa.sindex, .salloc, .tralloc): Now state_num, not int. (struct dfa.trans, .realtrans, .fails): Now state_num **, not int **. (struct dfa.newlines): Now state_num *, not int *. (prtok): Don't assume 'token' is no wider than int. (lexleft, parens, depth): Now size_t, not int. (charclass_index, nsubtoks) (parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete) (state_index, epsclosure, state_separate_contexts) (dfaanalyze, dfastate, build_state, realloc_trans_if_necessary) (transit_state_singlebyte, match_anychar, match_mb_charset) (check_matching_with_multibyte_ops, transit_state_consume_1char) (transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree) (freelist, enlist, addlists, inboth, dfamust): Don't assume indexes fit in 'int'. (lex): Avoid overflow in string-to-{hi,lo} conversions. (dfaanalyze): Redo indexing so that it works with size_t values, which cannot go negative. * src/dfa.h (dfaexec): Count argument is now size_t *, not int *. (dfastate): State numbers are now ptrdiff_t, not int. * src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM. (kwset_exact_matches): Now size_t, not int. (EGexecute): Don't assume indexes fit in 'int'. Check for overflow before converting a ptrdiff_t to a regoff_t, as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX). Check for memory exhaustion in re_search rather than treating it merely as failure to match; use xalloc_die () to report any error. * src/kwset.c (struct trie.accepting): Now size_t, not unsigned int. (struct kwset.words): Now ptrdiff_t, not int. * src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: EGexecute (char const *buf, size_t size, size_t *match_size, char const *start_ptr) { char const *buflim, *beg, *end, *match, *best_match, *mb_start; char eol = eolbyte; int backref, start, len, best_len; struct kwsmatch kwsm; size_t i, ret_val; if (MB_CUR_MAX > 1) { if (match_icase) { /* mbtolower adds a NUL byte at the end. That will provide space for the sentinel byte dfaexec may add. */ char *case_buf = mbtolower (buf, &size); if (start_ptr) start_ptr = case_buf + (start_ptr - buf); buf = case_buf; } } mb_start = buf; buflim = buf + size; for (beg = end = buf; end < buflim; beg = end) { if (!start_ptr) { /* We don't care about an exact match. */ if (kwset) { /* Find a possible match using the KWset matcher. */ size_t offset = kwsexec (kwset, beg, buflim - beg, &kwsm); if (offset == (size_t) -1) goto failure; beg += offset; /* Narrow down to the line containing the candidate, and run it through DFA. */ if ((end = memchr(beg, eol, buflim - beg)) != NULL) end++; else end = buflim; match = beg; while (beg > buf && beg[-1] != eol) --beg; if (kwsm.index < kwset_exact_matches) { if (!MBS_SUPPORT) goto success; if (mb_start < beg) mb_start = beg; if (MB_CUR_MAX == 1 || !is_mb_middle (&mb_start, match, buflim, kwsm.size[0])) goto success; } if (dfaexec (dfa, beg, (char *) end, 0, NULL, &backref) == NULL) continue; } else { /* No good fixed strings; start with DFA. */ char const *next_beg = dfaexec (dfa, beg, (char *) buflim, 0, NULL, &backref); if (next_beg == NULL) break; /* Narrow down to the line we've found. */ beg = next_beg; if ((end = memchr(beg, eol, buflim - beg)) != NULL) end++; else end = buflim; while (beg > buf && beg[-1] != eol) --beg; } /* Successful, no backreferences encountered! */ if (!backref) goto success; } else { /* We are looking for the leftmost (then longest) exact match. We will go through the outer loop only once. */ beg = start_ptr; end = buflim; } /* If we've made it to this point, this means DFA has seen a probable match, and we need to run it through Regex. */ best_match = end; best_len = 0; for (i = 0; i < pcount; i++) { patterns[i].regexbuf.not_eol = 0; if (0 <= (start = re_search (&(patterns[i].regexbuf), buf, end - buf - 1, beg - buf, end - beg - 1, &(patterns[i].regs)))) { len = patterns[i].regs.end[0] - start; match = buf + start; if (match > best_match) continue; if (start_ptr && !match_words) goto assess_pattern_match; if ((!match_lines && !match_words) || (match_lines && len == end - beg - 1)) { match = beg; len = end - beg; goto assess_pattern_match; } /* If -w, check if the match aligns with word boundaries. We do this iteratively because: (a) the line may contain more than one occurence of the pattern, and (b) Several alternatives in the pattern might be valid at a given point, and we may need to consider a shorter one to find a word boundary. */ if (match_words) while (match <= best_match) { if ((match == buf || !WCHAR ((unsigned char) match[-1])) && (start + len == end - buf - 1 || !WCHAR ((unsigned char) match[len]))) goto assess_pattern_match; if (len > 0) { /* Try a shorter length anchored at the same place. */ --len; patterns[i].regexbuf.not_eol = 1; len = re_match (&(patterns[i].regexbuf), buf, match + len - beg, match - buf, &(patterns[i].regs)); } if (len <= 0) { /* Try looking further on. */ if (match == end - 1) break; match++; patterns[i].regexbuf.not_eol = 0; start = re_search (&(patterns[i].regexbuf), buf, end - buf - 1, match - buf, end - match - 1, &(patterns[i].regs)); if (start < 0) break; len = patterns[i].regs.end[0] - start; match = buf + start; } } /* while (match <= best_match) */ continue; assess_pattern_match: if (!start_ptr) { /* Good enough for a non-exact match. No need to look at further patterns, if any. */ goto success; } if (match < best_match || (match == best_match && len > best_len)) { /* Best exact match: leftmost, then longest. */ best_match = match; best_len = len; } } /* if re_search >= 0 */ } /* for Regex patterns. */ if (best_match < end) { /* We have found an exact match. We were just waiting for the best one (leftmost then longest). */ beg = best_match; len = best_len; goto success_in_len; } } /* for (beg = end ..) */ failure: ret_val = -1; goto out; success: len = end - beg; success_in_len: *match_size = len; ret_val = beg - buf; out: return ret_val; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc. These problems mostly occur because the code attempts to stuff sizes into int or into unsigned int; this doesn't work on most 64-bit hosts and the errors can lead to core dumps. * NEWS: Document this. * src/dfa.c (token): Typedef to ptrdiff_t, since the enum's range could be as small as -128 .. 127 on practical hosts. (position.index): Now size_t, not unsigned int. (leaf_set.elems): Now size_t *, not unsigned int *. (dfa_state.hash, struct mb_char_classes.nchars, .nch_classes) (.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex) (.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets): (.mbcsets_alloc): Now size_t, not int. (dfa_state.first_end): Now token, not int. (state_num): New type. (struct mb_char_classes.cset): Now ptrdiff_t, not int. (struct dfa.utf8_anychar_classes): Now token[5], not int[5]. (struct dfa.sindex, .salloc, .tralloc): Now state_num, not int. (struct dfa.trans, .realtrans, .fails): Now state_num **, not int **. (struct dfa.newlines): Now state_num *, not int *. (prtok): Don't assume 'token' is no wider than int. (lexleft, parens, depth): Now size_t, not int. (charclass_index, nsubtoks) (parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete) (state_index, epsclosure, state_separate_contexts) (dfaanalyze, dfastate, build_state, realloc_trans_if_necessary) (transit_state_singlebyte, match_anychar, match_mb_charset) (check_matching_with_multibyte_ops, transit_state_consume_1char) (transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree) (freelist, enlist, addlists, inboth, dfamust): Don't assume indexes fit in 'int'. (lex): Avoid overflow in string-to-{hi,lo} conversions. (dfaanalyze): Redo indexing so that it works with size_t values, which cannot go negative. * src/dfa.h (dfaexec): Count argument is now size_t *, not int *. (dfastate): State numbers are now ptrdiff_t, not int. * src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM. (kwset_exact_matches): Now size_t, not int. (EGexecute): Don't assume indexes fit in 'int'. Check for overflow before converting a ptrdiff_t to a regoff_t, as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX). Check for memory exhaustion in re_search rather than treating it merely as failure to match; use xalloc_die () to report any error. * src/kwset.c (struct trie.accepting): Now size_t, not unsigned int. (struct kwset.words): Now ptrdiff_t, not int. * src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: prtext (char const *beg, char const *lim, int *nlinesp) { static int used; /* avoid printing SEP_STR_GROUP before any output */ char const *bp, *p; char eol = eolbyte; int i, n; if (!out_quiet && pending > 0) prpending (beg); p = beg; if (!out_quiet) { /* Deal with leading context crap. */ bp = lastout ? lastout : bufbeg; for (i = 0; i < out_before; ++i) if (p > bp) do --p; while (p[-1] != eol); /* We print the SEP_STR_GROUP separator only if our output is discontiguous from the last output in the file. */ if ((out_before || out_after) && used && p != lastout && group_separator) { pr_sgr_start_if (sep_color); fputs (group_separator, stdout); pr_sgr_end_if (sep_color); fputc ('\n', stdout); } while (p < beg) { char const *nl = memchr (p, eol, beg - p); nl++; prline (p, nl, SEP_CHAR_REJECTED); p = nl; } } if (nlinesp) { /* Caller wants a line count. */ for (n = 0; p < lim && n < outleft; n++) { char const *nl = memchr (p, eol, lim - p); nl++; if (!out_quiet) prline (p, nl, SEP_CHAR_SELECTED); p = nl; } *nlinesp = n; /* relying on it that this function is never called when outleft = 0. */ after_last_match = bufoffset - (buflim - p); } else if (!out_quiet) prline (beg, lim, SEP_CHAR_SELECTED); pending = out_quiet ? 0 : out_after; used = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program * NEWS: Document this. * bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax. Remove xstrtoumax. * src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX. (context_length_arg, prtext, grepbuf, grep, grepfile) (get_nondigit_option, main): Use intmax_t, not int, for line counts. (context_length_arg, main): Silently ceiling line counts to maximum value, since there's no practical difference between doing that and using infinite-precision arithmetic. (out_before, out_after, pending): Now intmax_t, not int. (max_count, outleft): Now intmax_t, not off_t. (prepend_args, prepend_default_options, main): Use size_t, not int, for sizes. (prepend_default_options): Check for int and size_t overflow.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cib_remote_connection_destroy(gpointer user_data) { cib_client_t *client = user_data; if (client == NULL) { return; } crm_trace("Cleaning up after client disconnect: %s/%s", crm_str(client->name), client->id); if (client->id != NULL) { if (!g_hash_table_remove(client_list, client->id)) { crm_err("Client %s not found in the hashtable", client->name); } } crm_trace("Destroying %s (%p)", client->name, user_data); num_clients--; crm_trace("Num unfree'd clients: %d", num_clients); free(client->name); free(client->callback_id); free(client->id); free(client->user); free(client); crm_trace("Freed the cib client"); if (cib_shutdown_flag) { cib_shutdown(0); } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cib_timeout_handler(gpointer data) { struct timer_rec_s *timer = data; timer_expired = TRUE; crm_err("Call %d timed out after %ds", timer->call_id, timer->timeout); /* Always return TRUE, never remove the handler * We do that after the while-loop in cib_native_perform_op() */ return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data) { GError *error; CheckData *data = user_data; gboolean op_res; error = NULL; op_res = FALSE; if (msg->status_code == SOUP_STATUS_CANCELLED) goto out; else if (msg->status_code != SOUP_STATUS_OK) { g_set_error (&error, GOA_ERROR, GOA_ERROR_FAILED, /* TODO: more specific */ _("Code: %u - Unexpected response from server"), msg->status_code); goto out; } op_res = TRUE; out: g_simple_async_result_set_op_res_gboolean (data->res, op_res); if (error != NULL) g_simple_async_result_take_error (data->res, error); g_simple_async_result_complete_in_idle (data->res); g_idle_add (http_client_check_data_free, data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates None of the branded providers (eg., Google, Facebook and Windows Live) should ever have an invalid certificate. So set "ssl-strict" on the SoupSession object being used by GoaWebView. Providers like ownCloud and Exchange might have to deal with certificates that are not up to the mark. eg., self-signed certificates. For those, show a warning when the account is being created, and only proceed if the user decides to ignore it. In any case, save the status of the certificate that was used to create the account. So an account created with a valid certificate will never work with an invalid one, and one created with an invalid certificate will not throw any further warnings. Fixes: CVE-2013-0240'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: add_account (GoaProvider *provider, GoaClient *client, GtkDialog *dialog, GtkBox *vbox, GError **error) { AddAccountData data; GVariantBuilder credentials; GVariantBuilder details; GoaEwsClient *ews_client; GoaObject *ret; const gchar *email_address; const gchar *server; const gchar *password; const gchar *username; const gchar *provider_type; gint response; ews_client = NULL; ret = NULL; memset (&data, 0, sizeof (AddAccountData)); data.cancellable = g_cancellable_new (); data.loop = g_main_loop_new (NULL, FALSE); data.dialog = dialog; data.error = NULL; create_account_details_ui (provider, dialog, vbox, TRUE, &data); gtk_widget_show_all (GTK_WIDGET (vbox)); g_signal_connect (dialog, "response", G_CALLBACK (dialog_response_cb), &data); ews_client = goa_ews_client_new (); ews_again: response = gtk_dialog_run (dialog); if (response != GTK_RESPONSE_OK) { g_set_error (&data.error, GOA_ERROR, GOA_ERROR_DIALOG_DISMISSED, _("Dialog was dismissed")); goto out; } email_address = gtk_entry_get_text (GTK_ENTRY (data.email_address)); password = gtk_entry_get_text (GTK_ENTRY (data.password)); username = gtk_entry_get_text (GTK_ENTRY (data.username)); server = gtk_entry_get_text (GTK_ENTRY (data.server)); /* See if there's already an account of this type with the * given identity */ provider_type = goa_provider_get_provider_type (provider); if (!goa_utils_check_duplicate (client, username, provider_type, (GoaPeekInterfaceFunc) goa_object_peek_password_based, &data.error)) goto out; g_cancellable_reset (data.cancellable); goa_ews_client_autodiscover (ews_client, email_address, password, username, server, data.cancellable, autodiscover_cb, &data); gtk_widget_set_sensitive (data.connect_button, FALSE); gtk_widget_show (data.progress_grid); g_main_loop_run (data.loop); if (g_cancellable_is_cancelled (data.cancellable)) { g_prefix_error (&data.error, _("Dialog was dismissed (%s, %d): "), g_quark_to_string (data.error->domain), data.error->code); data.error->domain = GOA_ERROR; data.error->code = GOA_ERROR_DIALOG_DISMISSED; goto out; } else if (data.error != NULL) { gchar *markup; markup = g_strdup_printf ("<b>%s:</b> %s", _("Error connecting to Microsoft Exchange server"), data.error->message); g_clear_error (&data.error); gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup); g_free (markup); gtk_button_set_label (GTK_BUTTON (data.connect_button), _("_Try Again")); gtk_expander_set_expanded (GTK_EXPANDER (data.expander), TRUE); gtk_widget_set_no_show_all (data.cluebar, FALSE); gtk_widget_show_all (data.cluebar); goto ews_again; } gtk_widget_hide (GTK_WIDGET (dialog)); g_variant_builder_init (&credentials, G_VARIANT_TYPE_VARDICT); g_variant_builder_add (&credentials, "{sv}", "password", g_variant_new_string (password)); g_variant_builder_init (&details, G_VARIANT_TYPE ("a{ss}")); g_variant_builder_add (&details, "{ss}", "MailEnabled", "true"); g_variant_builder_add (&details, "{ss}", "CalendarEnabled", "true"); g_variant_builder_add (&details, "{ss}", "ContactsEnabled", "true"); g_variant_builder_add (&details, "{ss}", "Host", server); /* OK, everything is dandy, add the account */ /* we want the GoaClient to update before this method returns (so it * can create a proxy for the new object) so run the mainloop while * waiting for this to complete */ goa_manager_call_add_account (goa_client_get_manager (client), goa_provider_get_provider_type (provider), username, email_address, g_variant_builder_end (&credentials), g_variant_builder_end (&details), NULL, /* GCancellable* */ (GAsyncReadyCallback) add_account_cb, &data); g_main_loop_run (data.loop); if (data.error != NULL) goto out; ret = GOA_OBJECT (g_dbus_object_manager_get_object (goa_client_get_object_manager (client), data.account_object_path)); out: /* We might have an object even when data.error is set. * eg., if we failed to store the credentials in the keyring. */ if (data.error != NULL) g_propagate_error (error, data.error); else g_assert (ret != NULL); g_free (data.account_object_path); if (data.loop != NULL) g_main_loop_unref (data.loop); g_clear_object (&data.cancellable); if (ews_client != NULL) g_object_unref (ews_client); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates None of the branded providers (eg., Google, Facebook and Windows Live) should ever have an invalid certificate. So set "ssl-strict" on the SoupSession object being used by GoaWebView. Providers like ownCloud and Exchange might have to deal with certificates that are not up to the mark. eg., self-signed certificates. For those, show a warning when the account is being created, and only proceed if the user decides to ignore it. In any case, save the status of the certificate that was used to create the account. So an account created with a valid certificate will never work with an invalid one, and one created with an invalid certificate will not throw any further warnings. Fixes: CVE-2013-0240'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data) { GError *error; CheckData *data = user_data; GTlsCertificateFlags cert_flags; gboolean op_res; gboolean using_https; error = NULL; op_res = FALSE; if (msg->status_code == SOUP_STATUS_CANCELLED) goto out; else if (msg->status_code != SOUP_STATUS_OK) { g_set_error (&error, GOA_ERROR, GOA_ERROR_FAILED, /* TODO: more specific */ _("Code: %u - Unexpected response from server"), msg->status_code); goto out; } if (!data->accept_ssl_errors) { using_https = soup_message_get_https_status (msg, NULL, &cert_flags); if (using_https && cert_flags != 0) { goa_utils_set_error_ssl (&error, cert_flags); goto out; } } op_res = TRUE; out: g_simple_async_result_set_op_res_gboolean (data->res, op_res); if (error != NULL) g_simple_async_result_take_error (data->res, error); g_simple_async_result_complete_in_idle (data->res); g_idle_add (http_client_check_data_free, data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates For providers like Exchange which use libsoup to talk to a HTTPS server it is not enough to warn the user about an invalid certificate. We should make sure that we abort the connection before any credentials have been sent. Fixes: CVE-2013-1799'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int dsOpen(void) { struct stat sb; int retval; char *path = server.diskstore_path; if ((retval = stat(path,&sb) == -1) && errno != ENOENT) { redisLog(REDIS_WARNING, "Error opening disk store at %s: %s", path, strerror(errno)); return REDIS_ERR; } /* Directory already in place. Assume everything is ok. */ if (retval == 0 && S_ISDIR(sb.st_mode)) return REDIS_OK; /* File exists but it's not a directory */ if (retval == 0 && !S_ISDIR(sb.st_mode)) { redisLog(REDIS_WARNING,"Disk store at %s is not a directory", path); return REDIS_ERR; } /* New disk store, create the directory structure now, as creating * them in a lazy way is not a good idea, after very few insertions * we'll need most of the 65536 directories anyway. */ if (mkdir(path) == -1) { redisLog(REDIS_WARNING,"Disk store init failed creating dir %s: %s", path, strerror(errno)); return REDIS_ERR; } return REDIS_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbAuthProcessSecurityTypeMessage(cl); return; #ifdef VINO_HAVE_GNUTLS case RFB_TLS_HANDSHAKE: rfbAuthProcessTLSHandshake(cl); return; #endif case RFB_AUTH_TYPE: rfbAuthProcessAuthTypeMessage(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_AUTH_DEFERRED: rfbLog("Authentication deferred - ignoring client message\n"); return; case RFB_INITIALISATION: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Reject new clients if in the deferred state As mentioned in bug 641811, Vino can get stuck trying to process the same data in an infinite loop if an authentication request is received from a client while that client is in the deferred state. Avoid this situation by closing new connections from the same client when it is in the deferred state.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlInitParserCtxt(xmlParserCtxtPtr ctxt) { xmlParserInputPtr input; if(ctxt==NULL) { xmlErrInternal(NULL, "Got NULL parser context\n", NULL); return(-1); } xmlDefaultSAXHandlerInit(); if (ctxt->dict == NULL) ctxt->dict = xmlDictCreate(); if (ctxt->dict == NULL) { xmlErrMemory(NULL, "cannot initialize parser context\n"); return(-1); } xmlDictSetLimit(ctxt->dict, XML_MAX_DICTIONARY_LIMIT); if (ctxt->sax == NULL) ctxt->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler)); if (ctxt->sax == NULL) { xmlErrMemory(NULL, "cannot initialize parser context\n"); return(-1); } else xmlSAXVersion(ctxt->sax, 2); ctxt->maxatts = 0; ctxt->atts = NULL; /* Allocate the Input stack */ if (ctxt->inputTab == NULL) { ctxt->inputTab = (xmlParserInputPtr *) xmlMalloc(5 * sizeof(xmlParserInputPtr)); ctxt->inputMax = 5; } if (ctxt->inputTab == NULL) { xmlErrMemory(NULL, "cannot initialize parser context\n"); ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */ xmlFreeInputStream(input); } ctxt->inputNr = 0; ctxt->input = NULL; ctxt->version = NULL; ctxt->encoding = NULL; ctxt->standalone = -1; ctxt->hasExternalSubset = 0; ctxt->hasPErefs = 0; ctxt->html = 0; ctxt->external = 0; ctxt->instate = XML_PARSER_START; ctxt->token = 0; ctxt->directory = NULL; /* Allocate the Node stack */ if (ctxt->nodeTab == NULL) { ctxt->nodeTab = (xmlNodePtr *) xmlMalloc(10 * sizeof(xmlNodePtr)); ctxt->nodeMax = 10; } if (ctxt->nodeTab == NULL) { xmlErrMemory(NULL, "cannot initialize parser context\n"); ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nodeNr = 0; ctxt->node = NULL; /* Allocate the Name stack */ if (ctxt->nameTab == NULL) { ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *)); ctxt->nameMax = 10; } if (ctxt->nameTab == NULL) { xmlErrMemory(NULL, "cannot initialize parser context\n"); ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; ctxt->nameNr = 0; ctxt->nameMax = 0; ctxt->name = NULL; return(-1); } ctxt->nameNr = 0; ctxt->name = NULL; /* Allocate the space stack */ if (ctxt->spaceTab == NULL) { ctxt->spaceTab = (int *) xmlMalloc(10 * sizeof(int)); ctxt->spaceMax = 10; } if (ctxt->spaceTab == NULL) { xmlErrMemory(NULL, "cannot initialize parser context\n"); ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; ctxt->nameNr = 0; ctxt->nameMax = 0; ctxt->name = NULL; ctxt->spaceNr = 0; ctxt->spaceMax = 0; ctxt->space = NULL; return(-1); } ctxt->spaceNr = 1; ctxt->spaceMax = 10; ctxt->spaceTab[0] = -1; ctxt->space = &ctxt->spaceTab[0]; ctxt->userData = ctxt; ctxt->myDoc = NULL; ctxt->wellFormed = 1; ctxt->nsWellFormed = 1; ctxt->valid = 1; ctxt->loadsubset = xmlLoadExtDtdDefaultValue; ctxt->validate = xmlDoValidityCheckingDefaultValue; ctxt->pedantic = xmlPedanticParserDefaultValue; ctxt->linenumbers = xmlLineNumbersDefaultValue; ctxt->keepBlanks = xmlKeepBlanksDefaultValue; if (ctxt->keepBlanks == 0) ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace; ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0; ctxt->vctxt.userData = ctxt; ctxt->vctxt.error = xmlParserValidityError; ctxt->vctxt.warning = xmlParserValidityWarning; if (ctxt->validate) { if (xmlGetWarningsDefaultValue == 0) ctxt->vctxt.warning = NULL; else ctxt->vctxt.warning = xmlParserValidityWarning; ctxt->vctxt.nodeMax = 0; } ctxt->replaceEntities = xmlSubstituteEntitiesDefaultValue; ctxt->record_info = 0; ctxt->nbChars = 0; ctxt->checkIndex = 0; ctxt->inSubset = 0; ctxt->errNo = XML_ERR_OK; ctxt->depth = 0; ctxt->charset = XML_CHAR_ENCODING_UTF8; ctxt->catalogs = NULL; ctxt->nbentities = 0; ctxt->input_id = 1; xmlInitNodeInfoSeq(&ctxt->node_seq); return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Detect excessive entities expansion upon replacement If entities expansion in the XML parser is asked for, it is possble to craft relatively small input document leading to excessive on-the-fly content generation. This patch accounts for those replacement and stop parsing after a given threshold. it can be bypassed as usual with the HUGE parser option.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info) { bool pr = false; u32 msr = msr_info->index; u64 data = msr_info->data; switch (msr) { case MSR_AMD64_NB_CFG: case MSR_IA32_UCODE_REV: case MSR_IA32_UCODE_WRITE: case MSR_VM_HSAVE_PA: case MSR_AMD64_PATCH_LOADER: case MSR_AMD64_BU_CFG2: break; case MSR_EFER: return set_efer(vcpu, data); case MSR_K7_HWCR: data &= ~(u64)0x40; /* ignore flush filter disable */ data &= ~(u64)0x100; /* ignore ignne emulation enable */ data &= ~(u64)0x8; /* ignore TLB cache disable */ if (data != 0) { vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n", data); return 1; } break; case MSR_FAM10H_MMIO_CONF_BASE: if (data != 0) { vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: " "0x%llx\n", data); return 1; } break; case MSR_IA32_DEBUGCTLMSR: if (!data) { /* We support the non-activated case already */ break; } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) { /* Values other than LBR and BTF are vendor-specific, thus reserved and should throw a #GP */ return 1; } vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n", __func__, data); break; case 0x200 ... 0x2ff: return set_msr_mtrr(vcpu, msr, data); case MSR_IA32_APICBASE: kvm_set_apic_base(vcpu, data); break; case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff: return kvm_x2apic_msr_write(vcpu, msr, data); case MSR_IA32_TSCDEADLINE: kvm_set_lapic_tscdeadline_msr(vcpu, data); break; case MSR_IA32_TSC_ADJUST: if (guest_cpuid_has_tsc_adjust(vcpu)) { if (!msr_info->host_initiated) { u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr; kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true); } vcpu->arch.ia32_tsc_adjust_msr = data; } break; case MSR_IA32_MISC_ENABLE: vcpu->arch.ia32_misc_enable_msr = data; break; case MSR_KVM_WALL_CLOCK_NEW: case MSR_KVM_WALL_CLOCK: vcpu->kvm->arch.wall_clock = data; kvm_write_wall_clock(vcpu->kvm, data); break; case MSR_KVM_SYSTEM_TIME_NEW: case MSR_KVM_SYSTEM_TIME: { kvmclock_reset(vcpu); vcpu->arch.time = data; kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); /* we verify if the enable bit is set... */ if (!(data & 1)) break; /* ...but clean it before doing the actual write */ vcpu->arch.time_offset = data & ~(PAGE_MASK | 1); /* Check that the address is 32-byte aligned. */ if (vcpu->arch.time_offset & (sizeof(struct pvclock_vcpu_time_info) - 1)) break; vcpu->arch.time_page = gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT); if (is_error_page(vcpu->arch.time_page)) vcpu->arch.time_page = NULL; break; } case MSR_KVM_ASYNC_PF_EN: if (kvm_pv_enable_async_pf(vcpu, data)) return 1; break; case MSR_KVM_STEAL_TIME: if (unlikely(!sched_info_on())) return 1; if (data & KVM_STEAL_RESERVED_MASK) return 1; if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime, data & KVM_STEAL_VALID_BITS)) return 1; vcpu->arch.st.msr_val = data; if (!(data & KVM_MSR_ENABLED)) break; vcpu->arch.st.last_steal = current->sched_info.run_delay; preempt_disable(); accumulate_steal_time(vcpu); preempt_enable(); kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu); break; case MSR_KVM_PV_EOI_EN: if (kvm_lapic_enable_pv_eoi(vcpu, data)) return 1; break; case MSR_IA32_MCG_CTL: case MSR_IA32_MCG_STATUS: case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1: return set_msr_mce(vcpu, msr, data); /* Performance counters are not protected by a CPUID bit, * so we should check all of them in the generic path for the sake of * cross vendor migration. * Writing a zero into the event select MSRs disables them, * which we perfectly emulate ;-). Any other value should be at least * reported, some guests depend on them. */ case MSR_K7_EVNTSEL0: case MSR_K7_EVNTSEL1: case MSR_K7_EVNTSEL2: case MSR_K7_EVNTSEL3: if (data != 0) vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; /* at least RHEL 4 unconditionally writes to the perfctr registers, * so we ignore writes to make it happy. */ case MSR_K7_PERFCTR0: case MSR_K7_PERFCTR1: case MSR_K7_PERFCTR2: case MSR_K7_PERFCTR3: vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; case MSR_P6_PERFCTR0: case MSR_P6_PERFCTR1: pr = true; case MSR_P6_EVNTSEL0: case MSR_P6_EVNTSEL1: if (kvm_pmu_msr(vcpu, msr)) return kvm_pmu_set_msr(vcpu, msr, data); if (pr || data != 0) vcpu_unimpl(vcpu, "disabled perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; case MSR_K7_CLK_CTL: /* * Ignore all writes to this no longer documented MSR. * Writes are only relevant for old K7 processors, * all pre-dating SVM, but a recommended workaround from * AMD for these chips. It is possible to specify the * affected processor models on the command line, hence * the need to ignore the workaround. */ break; case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15: if (kvm_hv_msr_partition_wide(msr)) { int r; mutex_lock(&vcpu->kvm->lock); r = set_msr_hyperv_pw(vcpu, msr, data); mutex_unlock(&vcpu->kvm->lock); return r; } else return set_msr_hyperv(vcpu, msr, data); break; case MSR_IA32_BBL_CR_CTL3: /* Drop writes to this legacy MSR -- see rdmsr * counterpart for further detail. */ vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data); break; case MSR_AMD64_OSVW_ID_LENGTH: if (!guest_cpuid_has_osvw(vcpu)) return 1; vcpu->arch.osvw.length = data; break; case MSR_AMD64_OSVW_STATUS: if (!guest_cpuid_has_osvw(vcpu)) return 1; vcpu->arch.osvw.status = data; break; default: if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr)) return xen_hvm_config(vcpu, data); if (kvm_pmu_msr(vcpu, msr)) return kvm_pmu_set_msr(vcpu, msr, data); if (!ignore_msrs) { vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data); return 1; } else { vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data); break; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <ahonig@google.com> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: php_libxml_input_buffer_noload(const char *URI, xmlCharEncoding enc) { return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb) { ext3_fsblk_t sb_block; char *options = (char *) *data; if (!options || strncmp(options, "sb=", 3) != 0) return 1; /* Default location */ options += 3; /*todo: use simple_strtoll with >32bit ext3 */ sb_block = simple_strtoul(options, &options, 0); if (*options && *options != ',') { ext3_msg(sb, "error: invalid sb specification: %s", (char *) *data); return 1; } if (*options == ',') options++; *data = (void *) options; return sb_block; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'ext3: Fix format string issues ext3_msg() takes the printk prefix as the second parameter and the format string as the third parameter. Two callers of ext3_msg omit the prefix and pass the format string as the second parameter and the first parameter to the format string as the third parameter. In both cases this string comes from an arbitrary source. Which means the string may contain format string characters, which will lead to undefined and potentially harmful behavior. The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages in ext3") and is fixed by this patch. CC: stable@vger.kernel.org Signed-off-by: Lars-Peter Clausen <lars@metafoo.de> Signed-off-by: Jan Kara <jack@suse.cz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; addr = gfn_to_hva(kvm, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; r = copy_from_user(data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'KVM: Validate userspace_addr of memslot when registered This way, we can avoid checking the user space address many times when we read the guest memory. Although we can do the same for write if we check which slots are writable, we do not care write now: reading the guest memory happens more often than writing. [avi: change VERIFY_READ to VERIFY_WRITE] Signed-off-by: Takuya Yoshikawa <yoshikawa.takuya@oss.ntt.co.jp> Signed-off-by: Avi Kivity <avi@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int cli_scanpe(cli_ctx *ctx) { uint16_t e_magic; /* DOS signature ("MZ") */ uint16_t nsections; uint32_t e_lfanew; /* address of new exe header */ uint32_t ep, vep; /* entry point (raw, virtual) */ uint8_t polipos = 0; time_t timestamp; struct pe_image_file_hdr file_hdr; union { struct pe_image_optional_hdr64 opt64; struct pe_image_optional_hdr32 opt32; } pe_opt; struct pe_image_section_hdr *section_hdr; char sname[9], epbuff[4096], *tempfile; uint32_t epsize; ssize_t bytes, at; unsigned int i, found, upx_success = 0, min = 0, max = 0, err, overlays = 0; unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur; int (*upxfn)(char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL; char *src = NULL, *dest = NULL; int ndesc, ret = CL_CLEAN, upack = 0, native=0; size_t fsize; uint32_t valign, falign, hdr_size, j; struct cli_exe_section *exe_sections; struct cli_matcher *md5_sect; char timestr[32]; struct pe_image_data_dir *dirs; struct cli_bc_ctx *bc_ctx; fmap_t *map; struct cli_pe_hook_data pedata; #ifdef HAVE__INTERNAL__SHA_COLLECT int sha_collect = ctx->sha_collect; #endif const char * virname = NULL; uint32_t viruses_found = 0; if(!ctx) { cli_errmsg("cli_scanpe: ctx == NULL\n"); return CL_ENULLARG; } map = *ctx->fmap; if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) { cli_dbgmsg("Can't read DOS signature\n"); return CL_CLEAN; } if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) { cli_dbgmsg("Invalid DOS signature\n"); return CL_CLEAN; } if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) { cli_dbgmsg("Can't read new header address\n"); /* truncated header? */ if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } e_lfanew = EC32(e_lfanew); cli_dbgmsg("e_lfanew == %d\n", e_lfanew); if(!e_lfanew) { cli_dbgmsg("Not a PE file\n"); return CL_CLEAN; } if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) { /* bad information in e_lfanew - probably not a PE file */ cli_dbgmsg("Can't read file header\n"); return CL_CLEAN; } if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) { cli_dbgmsg("Invalid PE signature (probably NE file)\n"); return CL_CLEAN; } if(EC16(file_hdr.Characteristics) & 0x2000) { cli_dbgmsg("File type: DLL\n"); dll = 1; } else if(EC16(file_hdr.Characteristics) & 0x01) { cli_dbgmsg("File type: Executable\n"); } switch(EC16(file_hdr.Machine)) { case 0x0: cli_dbgmsg("Machine type: Unknown\n"); break; case 0x14c: cli_dbgmsg("Machine type: 80386\n"); break; case 0x14d: cli_dbgmsg("Machine type: 80486\n"); break; case 0x14e: cli_dbgmsg("Machine type: 80586\n"); break; case 0x160: cli_dbgmsg("Machine type: R30000 (big-endian)\n"); break; case 0x162: cli_dbgmsg("Machine type: R3000\n"); break; case 0x166: cli_dbgmsg("Machine type: R4000\n"); break; case 0x168: cli_dbgmsg("Machine type: R10000\n"); break; case 0x184: cli_dbgmsg("Machine type: DEC Alpha AXP\n"); break; case 0x284: cli_dbgmsg("Machine type: DEC Alpha AXP 64bit\n"); break; case 0x1f0: cli_dbgmsg("Machine type: PowerPC\n"); break; case 0x200: cli_dbgmsg("Machine type: IA64\n"); break; case 0x268: cli_dbgmsg("Machine type: M68k\n"); break; case 0x266: cli_dbgmsg("Machine type: MIPS16\n"); break; case 0x366: cli_dbgmsg("Machine type: MIPS+FPU\n"); break; case 0x466: cli_dbgmsg("Machine type: MIPS16+FPU\n"); break; case 0x1a2: cli_dbgmsg("Machine type: Hitachi SH3\n"); break; case 0x1a3: cli_dbgmsg("Machine type: Hitachi SH3-DSP\n"); break; case 0x1a4: cli_dbgmsg("Machine type: Hitachi SH3-E\n"); break; case 0x1a6: cli_dbgmsg("Machine type: Hitachi SH4\n"); break; case 0x1a8: cli_dbgmsg("Machine type: Hitachi SH5\n"); break; case 0x1c0: cli_dbgmsg("Machine type: ARM\n"); break; case 0x1c2: cli_dbgmsg("Machine type: THUMB\n"); break; case 0x1d3: cli_dbgmsg("Machine type: AM33\n"); break; case 0x520: cli_dbgmsg("Machine type: Infineon TriCore\n"); break; case 0xcef: cli_dbgmsg("Machine type: CEF\n"); break; case 0xebc: cli_dbgmsg("Machine type: EFI Byte Code\n"); break; case 0x9041: cli_dbgmsg("Machine type: M32R\n"); break; case 0xc0ee: cli_dbgmsg("Machine type: CEE\n"); break; case 0x8664: cli_dbgmsg("Machine type: AMD64\n"); break; default: cli_dbgmsg("Machine type: ** UNKNOWN ** (0x%x)\n", EC16(file_hdr.Machine)); } nsections = EC16(file_hdr.NumberOfSections); if(nsections < 1 || nsections > 96) { if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } if(!ctx->corrupted_input) { if(nsections) cli_warnmsg("PE file contains %d sections\n", nsections); else cli_warnmsg("PE file contains no sections\n"); } return CL_CLEAN; } cli_dbgmsg("NumberOfSections: %d\n", nsections); timestamp = (time_t) EC32(file_hdr.TimeDateStamp); cli_dbgmsg("TimeDateStamp: %s", cli_ctime(&timestamp, timestr, sizeof(timestr))); cli_dbgmsg("SizeOfOptionalHeader: %x\n", EC16(file_hdr.SizeOfOptionalHeader)); if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg("SizeOfOptionalHeader too small\n"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } at = e_lfanew + sizeof(struct pe_image_file_hdr); if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg("Can't read optional file header\n"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr32); /* This will be a chicken and egg problem until we drop 9x */ if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) { if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) { /* FIXME: need to play around a bit more with xp64 */ cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } pe_plus = 1; } if(!pe_plus) { /* PE */ if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) { /* Seek to the end of the long header */ at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32); } if(DCONF & PE_CONF_UPACK) upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148); vep = EC32(optional_hdr32.AddressOfEntryPoint); hdr_size = EC32(optional_hdr32.SizeOfHeaders); cli_dbgmsg("File format: PE\n"); cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr32.MajorLinkerVersion); cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr32.MinorLinkerVersion); cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr32.SizeOfCode)); cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfInitializedData)); cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfUninitializedData)); cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep); cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr32.BaseOfCode)); cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr32.SectionAlignment)); cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr32.FileAlignment)); cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr32.MajorSubsystemVersion)); cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr32.MinorSubsystemVersion)); cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr32.SizeOfImage)); cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size); cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr32.NumberOfRvaAndSizes)); dirs = optional_hdr32.DataDirectory; } else { /* PE+ */ /* read the remaining part of the header */ if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg("Can't read optional file header\n"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32); vep = EC32(optional_hdr64.AddressOfEntryPoint); hdr_size = EC32(optional_hdr64.SizeOfHeaders); cli_dbgmsg("File format: PE32+\n"); cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr64.MajorLinkerVersion); cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr64.MinorLinkerVersion); cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr64.SizeOfCode)); cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfInitializedData)); cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfUninitializedData)); cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep); cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr64.BaseOfCode)); cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr64.SectionAlignment)); cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr64.FileAlignment)); cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr64.MajorSubsystemVersion)); cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr64.MinorSubsystemVersion)); cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr64.SizeOfImage)); cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size); cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr64.NumberOfRvaAndSizes)); dirs = optional_hdr64.DataDirectory; } switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) { case 0: cli_dbgmsg("Subsystem: Unknown\n"); break; case 1: cli_dbgmsg("Subsystem: Native (svc)\n"); native = 1; break; case 2: cli_dbgmsg("Subsystem: Win32 GUI\n"); break; case 3: cli_dbgmsg("Subsystem: Win32 console\n"); break; case 5: cli_dbgmsg("Subsystem: OS/2 console\n"); break; case 7: cli_dbgmsg("Subsystem: POSIX console\n"); break; case 8: cli_dbgmsg("Subsystem: Native Win9x driver\n"); break; case 9: cli_dbgmsg("Subsystem: WinCE GUI\n"); break; case 10: cli_dbgmsg("Subsystem: EFI application\n"); break; case 11: cli_dbgmsg("Subsystem: EFI driver\n"); break; case 12: cli_dbgmsg("Subsystem: EFI runtime driver\n"); break; case 13: cli_dbgmsg("Subsystem: EFI ROM image\n"); break; case 14: cli_dbgmsg("Subsystem: Xbox\n"); break; case 16: cli_dbgmsg("Subsystem: Boot application\n"); break; default: cli_dbgmsg("Subsystem: ** UNKNOWN ** (0x%x)\n", pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)); } cli_dbgmsg("------------------------------------\n"); if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) { cli_dbgmsg("Bad virtual alignment\n"); cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) { cli_dbgmsg("Bad file alignment\n"); cli_append_virus(ctx, "Heuristics.Broken.Executable"); return CL_VIRUS; } fsize = map->len; section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr)); if(!section_hdr) { cli_dbgmsg("Can't allocate memory for section headers\n"); return CL_EMEM; } exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section)); if(!exe_sections) { cli_dbgmsg("Can't allocate memory for section headers\n"); free(section_hdr); return CL_EMEM; } valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment); falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment); if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) { cli_dbgmsg("Can't read section header\n"); cli_dbgmsg("Possibly broken PE file\n"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_section_hdr)*nsections; for(i = 0; falign!=0x200 && i<nsections; i++) { /* file alignment fallback mode - blah */ if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) { cli_dbgmsg("Found misaligned section, using 0x200\n"); falign = 0x200; } } hdr_size = PESALIGN(hdr_size, valign); /* Aligned headers virtual size */ for(i = 0; i < nsections; i++) { strncpy(sname, (char *) section_hdr[i].Name, 8); sname[8] = 0; exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign); exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign); exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign); exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign); exe_sections[i].chr = EC32(section_hdr[i].Characteristics); exe_sections[i].urva = EC32(section_hdr[i].VirtualAddress); /* Just in case */ exe_sections[i].uvsz = EC32(section_hdr[i].VirtualSize); exe_sections[i].uraw = EC32(section_hdr[i].PointerToRawData); exe_sections[i].ursz = EC32(section_hdr[i].SizeOfRawData); if (!exe_sections[i].vsz && exe_sections[i].rsz) exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign); if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz)) exe_sections[i].rsz = fsize - exe_sections[i].raw; cli_dbgmsg("Section %d\n", i); cli_dbgmsg("Section name: %s\n", sname); cli_dbgmsg("Section data (from headers - in memory)\n"); cli_dbgmsg("VirtualSize: 0x%x 0x%x\n", exe_sections[i].uvsz, exe_sections[i].vsz); cli_dbgmsg("VirtualAddress: 0x%x 0x%x\n", exe_sections[i].urva, exe_sections[i].rva); cli_dbgmsg("SizeOfRawData: 0x%x 0x%x\n", exe_sections[i].ursz, exe_sections[i].rsz); cli_dbgmsg("PointerToRawData: 0x%x 0x%x\n", exe_sections[i].uraw, exe_sections[i].raw); if(exe_sections[i].chr & 0x20) { cli_dbgmsg("Section contains executable code\n"); if(exe_sections[i].vsz < exe_sections[i].rsz) { cli_dbgmsg("Section contains free space\n"); /* cli_dbgmsg("Dumping %d bytes\n", section_hdr.SizeOfRawData - section_hdr.VirtualSize); ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL)); */ } } if(exe_sections[i].chr & 0x20000000) cli_dbgmsg("Section's memory is executable\n"); if(exe_sections[i].chr & 0x80000000) cli_dbgmsg("Section's memory is writeable\n"); if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { /* Bad virtual alignment */ cli_dbgmsg("VirtualAddress is misaligned\n"); cli_dbgmsg("------------------------------------\n"); cli_append_virus(ctx, "Heuristics.Broken.Executable"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if (exe_sections[i].rsz) { /* Don't bother with virtual only sections */ if (exe_sections[i].raw >= fsize) { /* really broken */ cli_dbgmsg("Broken PE file - Section %d starts beyond the end of file (Offset@ %lu, Total filesize %lu)\n", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize); cli_dbgmsg("------------------------------------\n"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, "Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; /* no ninjas to see here! move along! */ } if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i; /* check MD5 section sigs */ md5_sect = ctx->engine->hm_mdb; if((DCONF & PE_CONF_MD5SECT) && md5_sect) { unsigned char md5_dig[16]; if(cli_hm_have_size(md5_sect, CLI_HASH_MD5, exe_sections[i].rsz) && cli_md5sect(map, &exe_sections[i], md5_dig) && cli_hm_scan(md5_dig, exe_sections[i].rsz, &virname, md5_sect, CLI_HASH_MD5) == CL_VIRUS) { cli_append_virus(ctx, virname); if(cli_hm_scan(md5_dig, fsize, NULL, ctx->engine->hm_fp, CLI_HASH_MD5) != CL_VIRUS) { if (!SCAN_ALL) { cli_dbgmsg("------------------------------------\n"); free(section_hdr); free(exe_sections); return CL_VIRUS; } } viruses_found++; } } } cli_dbgmsg("------------------------------------\n"); if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) { cli_dbgmsg("Found PE values with sign bit set\n"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, "Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } if(!i) { if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { /* Bad first section RVA */ cli_dbgmsg("First section is in the wrong place\n"); cli_append_virus(ctx, "Heuristics.Broken.Executable"); free(section_hdr); free(exe_sections); return CL_VIRUS; } min = exe_sections[i].rva; max = exe_sections[i].rva + exe_sections[i].rsz; } else { if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { /* No holes, no overlapping, no virtual disorder */ cli_dbgmsg("Virtually misplaced section (wrong order, overlapping, non contiguous)\n"); cli_append_virus(ctx, "Heuristics.Broken.Executable"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if(exe_sections[i].rva < min) min = exe_sections[i].rva; if(exe_sections[i].rva + exe_sections[i].rsz > max) { max = exe_sections[i].rva + exe_sections[i].rsz; overlays = exe_sections[i].raw + exe_sections[i].rsz; } } } free(section_hdr); if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) { cli_dbgmsg("EntryPoint out of file\n"); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,"Heuristics.Broken.Executable"); return CL_VIRUS; } return CL_CLEAN; } cli_dbgmsg("EntryPoint offset: 0x%x (%d)\n", ep, ep); if(pe_plus) { /* Do not continue for PE32+ files */ free(exe_sections); return CL_CLEAN; } epsize = fmap_readn(map, epbuff, ep, 4096); /* Disasm scan disabled since it's now handled by the bytecode */ /* CLI_UNPTEMP("DISASM",(exe_sections,0)); */ /* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) */ /* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); */ /* close(ndesc); */ /* CLI_TMPUNLK(); */ /* free(tempfile); */ /* if(ret == CL_VIRUS) { */ /* free(exe_sections); */ /* return ret; */ /* } */ if(overlays) { int overlays_sz = fsize - overlays; if(overlays_sz > 0) { ret = cli_scanishield(ctx, overlays, overlays_sz); if(ret != CL_CLEAN) { free(exe_sections); return ret; } } } pedata.nsections = nsections; pedata.ep = ep; pedata.offset = 0; memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr)); memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32)); memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64)); memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs)); pedata.e_lfanew = e_lfanew; pedata.overlays = overlays; pedata.overlays_sz = fsize - overlays; pedata.hdr_size = hdr_size; /* Bytecode BC_PE_ALL hook */ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map); if (ret == CL_VIRUS || ret == CL_BREAK) { free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN; } cli_bytecode_context_destroy(bc_ctx); /* Attempt to detect some popular polymorphic viruses */ /* W32.Parite.B */ if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) { const char *pt = cli_memstr(epbuff, 4040, "\x47\x65\x74\x50\x72\x6f\x63\x41\x64\x64\x72\x65\x73\x73\x00", 15); if(pt) { pt += 15; if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) { cli_append_virus(ctx,"Heuristics.W32.Parite.B"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } } } /* Kriz */ if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\x9c' && epbuff[2]=='\x60') { enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP}; uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP}; uint8_t *kzstate = kzs; uint8_t *kzcode = (uint8_t *)epbuff + 3; uint8_t kzdptr=0xff, kzdsize=0xff; int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1; cli_dbgmsg("in kriz\n"); while(*kzstate!=KZSTOP) { uint8_t op; if(kzlen<=6) break; op = *kzcode++; kzlen--; switch (*kzstate) { case KZSTRASH: case KZSGETSIZE: { int opsz=0; switch(op) { case 0x81: kzcode+=5; kzlen-=5; break; case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf: if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) { kzinitlen = kzlen-5; kzdsize=op-0xb8; kzstate++; op=4; /* fake the register to avoid breaking out */ cli_dbgmsg("kriz: using #%d as size counter\n", kzdsize); } opsz=4; case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f: op&=7; if(op!=kzdptr && op!=kzdsize) { kzcode+=opsz; kzlen-=opsz; break; } default: kzcode--; kzlen++; kzstate++; } break; } case KZSCDELTA: if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) { kzlen-=*kzcode+4; kzcode+=*kzcode+4; kzstate++; } else *kzstate=KZSTOP; break; case KZSPDELTA: if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) { kzstate++; cli_dbgmsg("kriz: using #%d as pointer\n", kzdptr); } else *kzstate=KZSTOP; break; case KZSXORPRFX: kzstate++; if(op==0x3e) break; case KZSXOR: if (op==0x80 && *kzcode==kzdptr+0xb0) { kzxorlen=kzlen; kzcode+=+6; kzlen-=+6; kzstate++; } else *kzstate=KZSTOP; break; case KZSDDELTA: if (op==kzdptr+0x48) kzstate++; else *kzstate=KZSTOP; break; case KZSLOOP: if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) { cli_append_virus(ctx,"Heuristics.W32.Kriz"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } cli_dbgmsg("kriz: loop out of bounds, corrupted sample?\n"); kzstate++; } } } /* W32.Magistr.A/B */ if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) { uint32_t rsize, vsize, dam = 0; vsize = exe_sections[nsections - 1].uvsz; rsize = exe_sections[nsections - 1].rsz; if(rsize < exe_sections[nsections - 1].ursz) { rsize = exe_sections[nsections - 1].ursz; dam = 1; } if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) { int bw = rsize < 0x7000 ? rsize : 0x7000; char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, "\xe8\x2c\x61\x00\x00", 5)) { cli_append_virus(ctx, dam ? "Heuristics.W32.Magistr.A.dam" : "Heuristics.W32.Magistr.A"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } } else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) { int bw = rsize < 0x8000 ? rsize : 0x8000; char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, "\xe8\x04\x72\x00\x00", 5)) { cli_append_virus(ctx,dam ? "Heuristics.W32.Magistr.B.dam" : "Heuristics.W32.Magistr.B"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } } } /* W32.Polipos.A */ while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) { uint32_t jump, jold, *jumps = NULL; uint8_t *code; unsigned int xsjs = 0; if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break; if(!exe_sections[0].rsz) break; if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break; for(i=0; i<exe_sections[0].rsz - 5; i++) { if((uint8_t)(code[i]-0xe8) > 1) continue; jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size); if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue; if(xsjs % 128 == 0) { if(xsjs == 1280) break; if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) { free(exe_sections); return CL_EMEM; } } j=0; for(; j<xsjs; j++) { if(jumps[j]<jump) continue; if(jumps[j]==jump) { xsjs--; break; } jold=jumps[j]; jumps[j]=jump; jump=jold; } jumps[j]=jump; xsjs++; } if(!xsjs) break; cli_dbgmsg("Polipos: Checking %d xsect jump(s)\n", xsjs); for(i=0;i<xsjs;i++) { if(!(code = fmap_need_off_once(map, jumps[i], 9))) continue; if((jump=cli_readint32(code))==0x60ec8b55 || (code[4]==0x0ec && ((jump==0x83ec8b55 && code[6]==0x60) || (jump==0x81ec8b55 && !code[7] && !code[8])))) { cli_append_virus(ctx,"Heuristics.W32.Polipos.A"); free(jumps); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } free(jumps); break; } /* Trojan.Swizzor.Gen */ if (SCAN_ALGO && (DCONF & PE_CONF_SWIZZOR) && nsections > 1 && fsize > 64*1024 && fsize < 4*1024*1024) { if(dirs[2].Size) { struct swizz_stats *stats = cli_calloc(1, sizeof(*stats)); unsigned int m = 1000; ret = CL_CLEAN; if (!stats) ret = CL_EMEM; else { cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats); if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) { cli_append_virus(ctx,"Heuristics.Trojan.Swizzor.Gen"); } free(stats); } if (ret != CL_CLEAN) { if (!(ret == CL_VIRUS && SCAN_ALL)) { free(exe_sections); return ret; } viruses_found++; } } } /* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! */ corrupted_cur = ctx->corrupted_input; ctx->corrupted_input = 2; /* caller will reset on return */ /* UPX, FSG, MEW support */ /* try to find the first section with physical size == 0 */ found = 0; if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) { for(i = 0; i < (unsigned int) nsections - 1; i++) { if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) { found = 1; cli_dbgmsg("UPX/FSG/MEW: empty section found - assuming compression\n"); break; } } } /* MEW support */ if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\xe9') { uint32_t fileoffset; char *tbuff; fileoffset = (vep + cli_readint32(epbuff + 1) + 5); while (fileoffset == 0x154 || fileoffset == 0x158) { uint32_t offdiff, uselzma; cli_dbgmsg ("MEW: found MEW characteristics %08X + %08X + 5 = %08X\n", cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5); if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0))) break; if (fileoffset == 0x154) cli_dbgmsg("MEW: Win9x compatibility was set!\n"); else cli_dbgmsg("MEW: Win9x compatibility was NOT set!\n"); if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) { cli_dbgmsg("MEW: ESI is not in proper section\n"); break; } offdiff -= exe_sections[i + 1].rva; if(!exe_sections[i + 1].rsz) { cli_dbgmsg("MEW: mew section is empty\n"); break; } ssize = exe_sections[i + 1].vsz; dsize = exe_sections[i].vsz; cli_dbgmsg("MEW: ssize %08x dsize %08x offdiff: %08x\n", ssize, dsize, offdiff); CLI_UNPSIZELIMITS("MEW", MAX(ssize, dsize)); CLI_UNPSIZELIMITS("MEW", MAX(ssize + dsize, exe_sections[i + 1].rsz)); if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) { cli_dbgmsg("MEW: Size mismatch: %08x\n", exe_sections[i + 1].rsz); break; } /* allocate needed buffer */ if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) { cli_dbgmsg("MEW: Can't read %d bytes [read: %lu]\n", exe_sections[i + 1].rsz, (unsigned long)bytes); free(exe_sections); free(src); return CL_EREAD; } cli_dbgmsg("MEW: %u (%08x) bytes read\n", (unsigned int)bytes, (unsigned int)bytes); /* count offset to lzma proc, if lzma used, 0xe8 -> call */ if (tbuff[0x7b] == '\xe8') { if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) { cli_dbgmsg("MEW: lzma proc out of bounds!\n"); free(src); break; /* to next unpacker in chain */ } uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80); } else { uselzma = 0; } CLI_UNPTEMP("MEW",(src,exe_sections,0)); CLI_UNPRESULTS("MEW",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0)); break; } } if(epsize<168) { free(exe_sections); return CL_CLEAN; } if (found || upack) { /* Check EP for UPX vs. FSG vs. Upack */ /* Upack 0.39 produces 2 types of executables * 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above): * mov esi, value | pusha * lodsd | call $+0x9 * push eax | * * Upack 1.1/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]: * 2 sections * mov esi, value * loads * mov edi, eax * * Upack unknown [sample 0297729] * 3 sections * mov esi, value * push [esi] * jmp * */ /* upack 0.39-3s + sample 0151477*/ while(((upack && nsections == 3) && /* 3 sections */ (( epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */ epbuff[5] == '\xad' && epbuff[6] == '\x50' /* lodsd; push eax */ ) || /* based on 0297729 sample from aCaB */ (epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */ epbuff[5] == '\xff' && epbuff[6] == '\x36' /* push [esi] */ ) )) || ((!upack && nsections == 2) && /* 2 sections */ (( /* upack 0.39-2s */ epbuff[0] == '\x60' && epbuff[1] == '\xe8' && cli_readint32(epbuff+2) == 0x9 /* pusha; call+9 */ ) || ( /* upack 1.1/1.2, based on 2 samples */ epbuff[0] == '\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && /* mov esi */ cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 && epbuff[5] == '\xad' && epbuff[6] == '\x8b' && epbuff[7] == '\xf8' /* loads; mov edi, eax */ ) )) ) { uint32_t vma, off; int a,b,c; cli_dbgmsg("Upack characteristics found.\n"); a = exe_sections[0].vsz; b = exe_sections[1].vsz; if (upack) { cli_dbgmsg("Upack: var set\n"); c = exe_sections[2].vsz; ssize = exe_sections[0].ursz + exe_sections[0].uraw; off = exe_sections[0].rva; vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva; } else { cli_dbgmsg("Upack: var NOT set\n"); c = exe_sections[1].rva; ssize = exe_sections[1].uraw; off = 0; vma = exe_sections[1].rva - exe_sections[1].uraw; } dsize = a+b+c; CLI_UNPSIZELIMITS("Upack", MAX(MAX(dsize, ssize), exe_sections[1].ursz)); if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) { cli_dbgmsg("Upack: probably malformed pe-header, skipping to next unpacker\n"); break; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } if(fmap_readn(map, dest, 0, ssize) != ssize) { cli_dbgmsg("Upack: Can't read raw data of section 0\n"); free(dest); break; } if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize); if(fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) { cli_dbgmsg("Upack: Can't read raw data of section 1\n"); free(dest); break; } CLI_UNPTEMP("Upack",(dest,exe_sections,0)); CLI_UNPRESULTS("Upack",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0)); break; } } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\x87' && epbuff[1] == '\x25') { /* FSG v2.0 support - thanks to aCaB ! */ uint32_t newesi, newedi, newebx, newedx; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize); free(exe_sections); return CL_CLEAN; } newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg("FSG: xchg out of bounds (%x), giving up\n", newedx); break; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg("Can't read raw data of section %d\n", i + 1); free(exe_sections); return CL_ESEEK; } dest = src + newedx - exe_sections[i + 1].rva; if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dest, 4)) { cli_dbgmsg("FSG: New ESP out of bounds\n"); break; } newedx = cli_readint32(dest) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg("FSG: New ESP (%x) is wrong\n", newedx); break; } dest = src + newedx - exe_sections[i + 1].rva; if(!CLI_ISCONTAINED(src, ssize, dest, 32)) { cli_dbgmsg("FSG: New stack out of bounds\n"); break; } newedi = cli_readint32(dest) - EC32(optional_hdr32.ImageBase); newesi = cli_readint32(dest + 4) - EC32(optional_hdr32.ImageBase); newebx = cli_readint32(dest + 16) - EC32(optional_hdr32.ImageBase); newedx = cli_readint32(dest + 20); if(newedi != exe_sections[i].rva) { cli_dbgmsg("FSG: Bad destination buffer (edi is %x should be %x)\n", newedi, exe_sections[i].rva); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg("FSG: Source buffer out of section bounds\n"); break; } if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) { cli_dbgmsg("FSG: Array of functions out of bounds\n"); break; } newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase); cli_dbgmsg("FSG: found old EP @%x\n",newedx); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(src); return CL_EMEM; } CLI_UNPTEMP("FSG",(dest,exe_sections,0)); CLI_UNPRESULTSFSG2("FSG",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0)); break; } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) { /* FSG support - v. 1.33 (thx trog for the many samples) */ int sectcnt = 0; char *support; uint32_t newesi, newedi, oldep, gp, t; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) { cli_dbgmsg("FSG: Support data out of padding area\n"); break; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS("FSG", gp); if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg("Can't read %d bytes from padding area\n", gp); free(exe_sections); return CL_EREAD; } /* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused */ newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); /* 1st dest */ newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); /* Source */ if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg("FSG: Source buffer out of section bounds\n"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva); break; } /* Counting original sections */ for(t = 12; t < gp - 4; t += 4) { uint32_t rva = cli_readint32(support+t); if(!rva) break; rva -= EC32(optional_hdr32.ImageBase)+1; sectcnt++; if(rva % 0x1000) cli_dbgmsg("FSG: Original section %d is misaligned\n", sectcnt); if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt); break; } } if(t >= gp - 4 || cli_readint32(support + t)) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 1; t <= (uint32_t)sectcnt; t++) sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase); if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg("Can't read raw data of section %d\n", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } oldep = vep + 161 + 6 + cli_readint32(epbuff+163); cli_dbgmsg("FSG: found old EP @%x\n", oldep); CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; /* were done with 1.33 */ } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\xbf' && epbuff[10] == '\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) { /* FSG support - v. 1.31 */ int sectcnt = 0; uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size); char *support; uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase); uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase); uint32_t oldep = vep - exe_sections[i + 1].rva; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; if(err) { cli_dbgmsg("FSG: Support data out of padding area\n"); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) { cli_dbgmsg("FSG: Source buffer out of section bounds\n"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva); break; } CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize); free(exe_sections); return CL_CLEAN; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS("FSG", gp) if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg("Can't read %d bytes from padding area\n", gp); free(exe_sections); return CL_EREAD; } /* Counting original sections */ for(t = 0; t < gp - 2; t += 2) { uint32_t rva = support[t]|(support[t+1]<<8); if (rva == 2 || rva == 1) break; rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase); sectcnt++; if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt); break; } } if(t >= gp-10 || cli_readint32(support + t + 6) != 2) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 0; t <= (uint32_t)sectcnt - 1; t++) { sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase); } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg("FSG: Can't read raw data of section %d\n", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } gp = 0xda + 6*(epbuff[16]=='\xe8'); oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep); cli_dbgmsg("FSG: found old EP @%x\n", oldep); CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; /* were done with 1.31 */ } if(found && (DCONF & PE_CONF_UPX)) { /* UPX support */ /* we assume (i + 1) is UPX1 */ ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz; CLI_UNPSIZELIMITS("UPX", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) { cli_dbgmsg("UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\n", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg("UPX: Can't read raw data of section %d\n", i+1); free(exe_sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } /* try to detect UPX code */ if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg("UPX: Looks like a NRV2B decompression routine\n"); upxfn = upx_inflate2b; } else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg("UPX: Looks like a NRV2D decompression routine\n"); upxfn = upx_inflate2d; } else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg("UPX: Looks like a NRV2E decompression routine\n"); upxfn = upx_inflate2e; } if(upxfn) { int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva; if(epbuff[1] != '\xbe' || skew <= 0 || skew > 0xfff) { /* FIXME: legit skews?? */ skew = 0; if(upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0) upx_success = 1; } else { cli_dbgmsg("UPX: UPX1 seems skewed by %d bytes\n", skew); if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0 || upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0) upx_success = 1; } if(upx_success) cli_dbgmsg("UPX: Successfully decompressed\n"); else cli_dbgmsg("UPX: Preferred decompressor failed\n"); } if(!upx_success && upxfn != upx_inflate2b) { if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg("UPX: NRV2B decompressor failed\n"); } else { upx_success = 1; cli_dbgmsg("UPX: Successfully decompressed with NRV2B\n"); } } if(!upx_success && upxfn != upx_inflate2d) { if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg("UPX: NRV2D decompressor failed\n"); } else { upx_success = 1; cli_dbgmsg("UPX: Successfully decompressed with NRV2D\n"); } } if(!upx_success && upxfn != upx_inflate2e) { if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg("UPX: NRV2E decompressor failed\n"); } else { upx_success = 1; cli_dbgmsg("UPX: Successfully decompressed with NRV2E\n"); } } if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0; if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0; if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } if(!upx_success) { cli_dbgmsg("UPX: All decompressors failed\n"); free(dest); } } if(upx_success) { free(exe_sections); CLI_UNPTEMP("UPX/FSG",(dest,0)); if((unsigned int) write(ndesc, dest, dsize) != dsize) { cli_dbgmsg("UPX/FSG: Can't write %d bytes\n", dsize); free(tempfile); free(dest); close(ndesc); return CL_EWRITE; } free(dest); lseek(ndesc, 0, SEEK_SET); if(ctx->engine->keeptmp) cli_dbgmsg("UPX/FSG: Decompressed data saved in %s\n", tempfile); cli_dbgmsg("***** Scanning decompressed file *****\n"); SHA_OFF; if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) { close(ndesc); CLI_TMPUNLK(); free(tempfile); SHA_RESET; return CL_VIRUS; } SHA_RESET; close(ndesc); CLI_TMPUNLK(); free(tempfile); return ret; } /* Petite */ if(epsize<200) { free(exe_sections); return CL_CLEAN; } found = 2; if(epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) { if(nsections < 2 || epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase)) found = 0; else found = 1; } if(found && (DCONF & PE_CONF_PETITE)) { cli_dbgmsg("Petite: v2.%d compression detected\n", found); if(cli_readint32(epbuff + 0x80) == 0x163c988d) { cli_dbgmsg("Petite: level zero compression is not supported yet\n"); } else { dsize = max - min; CLI_UNPSIZELIMITS("Petite", dsize); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { cli_dbgmsg("Petite: Can't allocate %d bytes\n", dsize); free(exe_sections); return CL_EMEM; } for(i = 0 ; i < nsections; i++) { if(exe_sections[i].raw) { if(!exe_sections[i].rsz || fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) { free(exe_sections); free(dest); return CL_CLEAN; } } } CLI_UNPTEMP("Petite",(dest,exe_sections,0)); CLI_UNPRESULTS("Petite",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0)); } } /* PESpin 1.1 */ if((DCONF & PE_CONF_PESPIN) && nsections > 1 && vep >= exe_sections[nsections - 1].rva && vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 && memcmp(epbuff+4, "\xe8\x00\x00\x00\x00\x8b\x1c\x24\x83\xc3", 10) == 0) { char *spinned; CLI_UNPSIZELIMITS("PEspin", fsize); if((spinned = (char *) cli_malloc(fsize)) == NULL) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg("PESpin: Can't read %lu bytes\n", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } CLI_UNPTEMP("PESpin",(spinned,exe_sections,0)); CLI_UNPRESULTS_("PEspin",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0)); } /* yC 1.3 & variants */ if((DCONF & PE_CONF_YC) && nsections > 1 && (EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) { uint32_t ecx = 0; int16_t offset; /* yC 1.3 */ if (!memcmp(epbuff, "\x55\x8B\xEC\x53\x56\x57\x60\xE8\x00\x00\x00\x00\x5D\x81\xED", 15) && !memcmp(epbuff+0x26, "\x8D\x3A\x8B\xF7\x33\xC0\xEB\x04\x90\xEB\x01\xC2\xAC", 13) && ((uint8_t)epbuff[0x13] == 0xB9) && ((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) && !memcmp(epbuff+0x1e,"\x8B\xD5\x81\xC2", 4)) { offset = 0; if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6) ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a); } /* yC 1.3 variant */ if (!ecx && !memcmp(epbuff, "\x55\x8B\xEC\x83\xEC\x40\x53\x56\x57", 9) && !memcmp(epbuff+0x17, "\xe8\x00\x00\x00\x00\x5d\x81\xed", 8) && ((uint8_t)epbuff[0x23] == 0xB9)) { offset = 0x10; if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6) ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a); } /* yC 1.x/modified */ if (!ecx && !memcmp(epbuff, "\x60\xe8\x00\x00\x00\x00\x5d\x81\xed",9) && ((uint8_t)epbuff[0xd] == 0xb9) && ((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) && !memcmp(epbuff+0x18, "\x8b\xf7\xac", 3)) { offset = -0x18; if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae) ecx = cli_readint32(epbuff+0xe); } if (ecx > 0x800 && ecx < 0x2000 && !memcmp(epbuff+0x63+offset, "\xaa\xe2\xcc", 3) && (fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) { char *spinned; if((spinned = (char *) cli_malloc(fsize)) == NULL) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg("yC: Can't read %lu bytes\n", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } cli_dbgmsg("%d,%d,%d,%d\n", nsections-1, e_lfanew, ecx, offset); CLI_UNPTEMP("yC",(spinned,exe_sections,0)); CLI_UNPRESULTS("yC",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0)); } } /* WWPack */ while ((DCONF & PE_CONF_WWPACK) && nsections > 1 && vep == exe_sections[nsections - 1].rva && memcmp(epbuff, "\x53\x55\x8b\xe8\x33\xdb\xeb", 7) == 0 && memcmp(epbuff+0x68, "\xe8\x00\x00\x00\x00\x58\x2d\x6d\x00\x00\x00\x50\x60\x33\xc9\x50\x58\x50\x50", 19) == 0) { uint32_t head = exe_sections[nsections - 1].raw; uint8_t *packer; ssize = 0; for(i=0 ; ; i++) { if(exe_sections[i].raw<head) head=exe_sections[i].raw; if(i+1==nsections) break; if(ssize<exe_sections[i].rva+exe_sections[i].vsz) ssize=exe_sections[i].rva+exe_sections[i].vsz; } if(!head || !ssize || head>ssize) break; CLI_UNPSIZELIMITS("WWPack", ssize); if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, src, 0, head) != head) { cli_dbgmsg("WWPack: Can't read %d bytes from headers\n", head); free(src); free(exe_sections); return CL_EREAD; } for(i = 0 ; i < (unsigned int)nsections-1; i++) { if(!exe_sections[i].rsz) continue; if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break; if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break; } if(i+1!=nsections) { cli_dbgmsg("WWpack: Probably hacked/damaged file.\n"); free(src); break; } if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) { free(src); free(exe_sections); return CL_EMEM; } if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) { cli_dbgmsg("WWPack: Can't read %d bytes from wwpack sect\n", exe_sections[nsections - 1].rsz); free(src); free(packer); free(exe_sections); return CL_EREAD; } CLI_UNPTEMP("WWPack",(src,packer,exe_sections,0)); CLI_UNPRESULTS("WWPack",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0)); break; } /* ASPACK support */ while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,"\x60\xe8\x03\x00\x00\x00\xe9\xeb",8)) { if(epsize<0x3bf || memcmp(epbuff+0x3b9, "\x68\x00\x00\x00\x00\xc3",6)) break; ssize = 0; for(i=0 ; i< nsections ; i++) if(ssize<exe_sections[i].rva+exe_sections[i].vsz) ssize=exe_sections[i].rva+exe_sections[i].vsz; if(!ssize) break; CLI_UNPSIZELIMITS("Aspack", ssize); if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } for(i = 0 ; i < (unsigned int)nsections; i++) { if(!exe_sections[i].rsz) continue; if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break; if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break; } if(i!=nsections) { cli_dbgmsg("Aspack: Probably hacked/damaged Aspack file.\n"); free(src); break; } CLI_UNPTEMP("Aspack",(src,exe_sections,0)); CLI_UNPRESULTS("Aspack",(unaspack212((uint8_t *)src, ssize, exe_sections, nsections, vep-1, EC32(optional_hdr32.ImageBase), ndesc)),1,(src,0)); break; } /* NsPack */ while (DCONF & PE_CONF_NSPACK) { uint32_t eprva = vep; uint32_t start_of_stuff, rep = ep; unsigned int nowinldr; char *nbuff; src=epbuff; if (*epbuff=='\xe9') { /* bitched headers */ eprva = cli_readint32(epbuff+1)+vep+5; if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) break; if (!(nbuff = fmap_need_off_once(map, rep, 24))) break; src = nbuff; } if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) break; nowinldr = 0x54-cli_readint32(src+17); cli_dbgmsg("NsPack: Found *start_of_stuff @delta-%x\n", nowinldr); if(!(nbuff = fmap_need_off_once(map, rep-nowinldr, 4))) break; start_of_stuff=rep+cli_readint32(nbuff); if(!(nbuff = fmap_need_off_once(map, start_of_stuff, 20))) break; src = nbuff; if (!cli_readint32(nbuff)) { start_of_stuff+=4; /* FIXME: more to do */ src+=4; } ssize = cli_readint32(src+5)|0xff; dsize = cli_readint32(src+9); CLI_UNPSIZELIMITS("NsPack", MAX(ssize,dsize)); if (!ssize || !dsize || dsize != exe_sections[0].vsz) break; if (!(dest=cli_malloc(dsize))) break; /* memset(dest, 0xfc, dsize); */ if(!(src = fmap_need_off(map, start_of_stuff, ssize))) { free(dest); break; } /* memset(src, 0x00, ssize); */ eprva+=0x27a; if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) { free(dest); break; } if(!(nbuff = fmap_need_off_once(map, rep, 5))) { free(dest); break; } fmap_unneed_off(map, start_of_stuff, ssize); eprva=eprva+5+cli_readint32(nbuff+1); cli_dbgmsg("NsPack: OEP = %08x\n", eprva); CLI_UNPTEMP("NsPack",(dest,exe_sections,0)); CLI_UNPRESULTS("NsPack",(unspack(src, dest, ctx, exe_sections[0].rva, EC32(optional_hdr32.ImageBase), eprva, ndesc)),0,(dest,0)); break; } /* to be continued ... */ /* !!!!!!!!!!!!!! PACKERS END HERE !!!!!!!!!!!!!! */ ctx->corrupted_input = corrupted_cur; /* Bytecode BC_PE_UNPACKER hook */ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map); switch (ret) { case CL_VIRUS: free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return CL_VIRUS; case CL_SUCCESS: ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile); cli_bytecode_context_destroy(bc_ctx); if (ndesc != -1 && tempfile) { CLI_UNPRESULTS("bytecode PE hook", 1, 1, (0)); } break; default: cli_bytecode_context_destroy(bc_ctx); } free(exe_sections); if (SCAN_ALL && viruses_found) return CL_VIRUS; return CL_CLEAN; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'libclamav: bb #7055'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void drive_machine(conn *c) { bool stop = false; int sfd, flags = 1; socklen_t addrlen; struct sockaddr_storage addr; int nreqs = settings.reqs_per_event; int res; const char *str; assert(c != NULL); while (!stop) { switch(c->state) { case conn_listening: addrlen = sizeof(addr); if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { /* these are transient, so don't log anything */ stop = true; } else if (errno == EMFILE) { if (settings.verbose > 0) fprintf(stderr, "Too many open connections\n"); accept_new_conns(false); stop = true; } else { perror("accept()"); stop = true; } break; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); break; } if (settings.maxconns_fast && stats.curr_conns + stats.reserved_fds >= settings.maxconns - 1) { str = "ERROR Too many open connections\r\n"; res = write(sfd, str, strlen(str)); close(sfd); STATS_LOCK(); stats.rejected_conns++; STATS_UNLOCK(); } else { dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST, DATA_BUFFER_SIZE, tcp_transport); } stop = true; break; case conn_waiting: if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } conn_set_state(c, conn_read); stop = true; break; case conn_read: res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c); switch (res) { case READ_NO_DATA_RECEIVED: conn_set_state(c, conn_waiting); break; case READ_DATA_RECEIVED: conn_set_state(c, conn_parse_cmd); break; case READ_ERROR: conn_set_state(c, conn_closing); break; case READ_MEMORY_ERROR: /* Failed to allocate more memory */ /* State already set by try_read_network */ break; } break; case conn_parse_cmd : if (try_read_command(c) == 0) { /* wee need more data! */ conn_set_state(c, conn_waiting); } break; case conn_new_cmd: /* Only process nreqs at a time to avoid starving other connections */ --nreqs; if (nreqs >= 0) { reset_cmd_handler(c); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.conn_yields++; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rbytes > 0) { /* We have already read in data into the input buffer, so libevent will most likely not signal read events on the socket (unless more data is available. As a hack we should just put in a request to write data, because that should be possible ;-) */ if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } } stop = true; } break; case conn_nread: if (c->rlbytes == 0) { complete_nread(c); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; if (c->ritem != c->rcurr) { memmove(c->ritem, c->rcurr, tocopy); } c->ritem += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; if (c->rlbytes == 0) { break; } } /* now try reading from the socket */ res = read(c->sfd, c->ritem, c->rlbytes); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rcurr == c->ritem) { c->rcurr += res; } c->ritem += res; c->rlbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) { fprintf(stderr, "Failed to read, and not due to blocking:\n" "errno: %d %s \n" "rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n", errno, strerror(errno), (long)c->rcurr, (long)c->ritem, (long)c->rbuf, (int)c->rlbytes, (int)c->rsize); } conn_set_state(c, conn_closing); break; case conn_swallow: /* we are reading sbytes and throwing them away */ if (c->sbytes == 0) { conn_set_state(c, conn_new_cmd); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes; c->sbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; break; } /* now try reading from the socket */ res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); c->sbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) fprintf(stderr, "Failed to read, and not due to blocking\n"); conn_set_state(c, conn_closing); break; case conn_write: /* * We want to write out a simple response. If we haven't already, * assemble it into a msgbuf list (this will be a single-entry * list for TCP or a two-entry list for UDP). */ if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) { if (add_iov(c, c->wcurr, c->wbytes) != 0) { if (settings.verbose > 0) fprintf(stderr, "Couldn't build response\n"); conn_set_state(c, conn_closing); break; } } /* fall through... */ case conn_mwrite: if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) { if (settings.verbose > 0) fprintf(stderr, "Failed to build UDP headers\n"); conn_set_state(c, conn_closing); break; } switch (transmit(c)) { case TRANSMIT_COMPLETE: if (c->state == conn_mwrite) { while (c->ileft > 0) { item *it = *(c->icurr); assert((it->it_flags & ITEM_SLABBED) == 0); item_remove(it); c->icurr++; c->ileft--; } while (c->suffixleft > 0) { char *suffix = *(c->suffixcurr); cache_free(c->thread->suffix_cache, suffix); c->suffixcurr++; c->suffixleft--; } /* XXX: I don't know why this wasn't the general case */ if(c->protocol == binary_prot) { conn_set_state(c, c->write_and_go); } else { conn_set_state(c, conn_new_cmd); } } else if (c->state == conn_write) { if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } conn_set_state(c, c->write_and_go); } else { if (settings.verbose > 0) fprintf(stderr, "Unexpected state %d\n", c->state); conn_set_state(c, conn_closing); } break; case TRANSMIT_INCOMPLETE: case TRANSMIT_HARD_ERROR: break; /* Continue in state machine. */ case TRANSMIT_SOFT_ERROR: stop = true; break; } break; case conn_closing: if (IS_UDP(c->transport)) conn_cleanup(c); else conn_close(c); stop = true; break; case conn_max_state: assert(false); break; } } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix segfault on specially crafted packet.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static apr_status_t modsecurity_request_body_store_memory(modsec_rec *msr, const char *data, apr_size_t length, char **error_msg) { *error_msg = NULL; /* Would storing this chunk mean going over the limit? */ if ((msr->msc_reqbody_spilltodisk) && (msr->msc_reqbody_length + length > (apr_size_t)msr->txcfg->reqbody_inmemory_limit)) { msc_data_chunk **chunks; unsigned int disklen = 0; int i; msr_log(msr, 4, "Input filter: Request too large to store in memory, switching to disk."); /* NOTE Must use modsecurity_request_body_store_disk() here * to prevent data to be sent to the streaming * processors again. */ /* Initialise disk storage */ msr->msc_reqbody_storage = MSC_REQBODY_DISK; if (modsecurity_request_body_start_init(msr, error_msg) < 0) return -1; /* Write the data we keep in memory */ chunks = (msc_data_chunk **)msr->msc_reqbody_chunks->elts; for(i = 0; i < msr->msc_reqbody_chunks->nelts; i++) { disklen += chunks[i]->length; if (modsecurity_request_body_store_disk(msr, chunks[i]->data, chunks[i]->length, error_msg) < 0) { return -1; } free(chunks[i]->data); chunks[i]->data = NULL; } /* Clear the memory pool as we no longer need the bits. */ /* IMP1 But since we only used apr_pool_clear memory might * not be released back to the OS straight away? */ msr->msc_reqbody_chunks = NULL; apr_pool_clear(msr->msc_reqbody_mp); msr_log(msr, 4, "Input filter: Wrote %u bytes from memory to disk.", disklen); /* Continue with disk storage from now on */ return modsecurity_request_body_store_disk(msr, data, length, error_msg); } /* If we're here that means we are not over the * request body in-memory limit yet. */ { unsigned long int bucket_offset, bucket_left; bucket_offset = 0; bucket_left = length; /* Although we store the request body in chunks we don't * want to use the same chunk sizes as the incoming memory * buffers. They are often of very small sizes and that * would make us waste a lot of memory. That's why we * use our own chunks of CHUNK_CAPACITY sizes. */ /* Loop until we empty this bucket into our chunks. */ while(bucket_left > 0) { /* Allocate a new chunk if we have to. */ if (msr->msc_reqbody_chunk_current == NULL) { msr->msc_reqbody_chunk_current = (msc_data_chunk *) apr_pcalloc(msr->msc_reqbody_mp, sizeof(msc_data_chunk)); if (msr->msc_reqbody_chunk_current == NULL) { *error_msg = apr_psprintf(msr->mp, "Input filter: Failed to allocate %lu bytes " "for request body chunk.", (unsigned long)sizeof(msc_data_chunk)); return -1; } msr->msc_reqbody_chunk_current->data = malloc(CHUNK_CAPACITY); if (msr->msc_reqbody_chunk_current->data == NULL) { *error_msg = apr_psprintf(msr->mp, "Input filter: Failed to allocate %d bytes " "for request body chunk data.", CHUNK_CAPACITY); return -1; } msr->msc_reqbody_chunk_current->length = 0; msr->msc_reqbody_chunk_current->is_permanent = 1; *(const msc_data_chunk **)apr_array_push(msr->msc_reqbody_chunks) = msr->msc_reqbody_chunk_current; } if (bucket_left < (CHUNK_CAPACITY - msr->msc_reqbody_chunk_current->length)) { /* There's enough space in the current chunk. */ memcpy(msr->msc_reqbody_chunk_current->data + msr->msc_reqbody_chunk_current->length, data + bucket_offset, bucket_left); msr->msc_reqbody_chunk_current->length += bucket_left; bucket_left = 0; } else { /* Fill the existing chunk. */ unsigned long int copy_length = CHUNK_CAPACITY - msr->msc_reqbody_chunk_current->length; memcpy(msr->msc_reqbody_chunk_current->data + msr->msc_reqbody_chunk_current->length, data + bucket_offset, copy_length); bucket_offset += copy_length; bucket_left -= copy_length; msr->msc_reqbody_chunk_current->length += copy_length; /* We're done with this chunk. Setting the pointer * to NULL is going to force a new chunk to be allocated * on the next go. */ msr->msc_reqbody_chunk_current = NULL; } } msr->msc_reqbody_length += length; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed: chuck null pointer when unknown CT is sent and over in-memory limit'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,0,2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if(!load_raw) return LIBRAW_UNSPECIFIED_ERROR; if (O.use_camera_matrix && C.cmatrix[0][0] > 0.25) { memcpy (C.rgb_cam, C.cmatrix, sizeof (C.cmatrix)); IO.raw_color = 0; } // already allocated ? if(imgdata.image) { free(imgdata.image); imgdata.image = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *) malloc (libraw_internal_data.unpacker_data.meta_length); merror (libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); int save_document_mode = O.document_mode; O.document_mode = 0; libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if( !IO.fuji_width) { // adjust non-Fuji allocation if(rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if(rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { imgdata.rawdata.raw_alloc = malloc(rwidth*rheight*sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; } else if (decoder_info.decoder_flags & LIBRAW_DECODER_4COMPONENT) { S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; imgdata.rawdata.raw_alloc = calloc(rwidth*rheight,sizeof(*imgdata.rawdata.color_image)); imgdata.rawdata.color_image = (ushort(*)[4]) imgdata.rawdata.raw_alloc; } else if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { // sRAW and Foveon only, so extra buffer size is just 1/4 // Legacy converters does not supports half mode! S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; // allocate image as temporary buffer, size imgdata.rawdata.raw_alloc = calloc(S.iwidth*S.iheight,sizeof(*imgdata.image)); imgdata.image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } (this->*load_raw)(); // recover saved if( decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { imgdata.image = 0; imgdata.rawdata.color_image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } // calculate channel maximum { for(int c=0;c<4;c++) C.channel_maximum[c] = 0; if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { for(int rc = 0; rc < S.iwidth*S.iheight; rc++) { if(C.channel_maximum[0]<imgdata.rawdata.color_image[rc][0]) C.channel_maximum[0]=imgdata.rawdata.color_image[rc][0]; if(C.channel_maximum[1]<imgdata.rawdata.color_image[rc][1]) C.channel_maximum[1]=imgdata.rawdata.color_image[rc][1]; if(C.channel_maximum[2]<imgdata.rawdata.color_image[rc][2]) C.channel_maximum[2]=imgdata.rawdata.color_image[rc][2]; if(C.channel_maximum[3]<imgdata.rawdata.color_image[rc][3]) C.channel_maximum[3]=imgdata.rawdata.color_image[rc][3]; } } else if(decoder_info.decoder_flags & LIBRAW_DECODER_4COMPONENT) { for(int row = S.top_margin; row < S.height+S.top_margin; row++) for(int col = S.left_margin; col < S.width+S.left_margin; col++) { int rc = row*S.raw_width+col; if(C.channel_maximum[0]<imgdata.rawdata.color_image[rc][0]) C.channel_maximum[0]=imgdata.rawdata.color_image[rc][0]; if(C.channel_maximum[1]<imgdata.rawdata.color_image[rc][1]) C.channel_maximum[1]=imgdata.rawdata.color_image[rc][1]; if(C.channel_maximum[2]<imgdata.rawdata.color_image[rc][2]) C.channel_maximum[2]=imgdata.rawdata.color_image[rc][2]; if(C.channel_maximum[3]<imgdata.rawdata.color_image[rc][3]) C.channel_maximum[3]=imgdata.rawdata.color_image[rc][4]; } } else if (decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { for(int row = 0; row < S.height; row++) { int colors[4]; for (int xx=0;xx<4;xx++) colors[xx] = COLOR(row,xx); for(int col = 0; col < S.width; col++) { int cc = colors[col&3]; if(C.channel_maximum[cc] < imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_width +(col+S.left_margin)]) C.channel_maximum[cc] = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_width +(col+S.left_margin)]; } } } } // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // phase-one black if(imgdata.rawdata.ph1_black) C.ph1_black = imgdata.rawdata.ph1_black; O.document_mode = save_document_mode; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for(c=0;c<3;c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c=0;c<4;c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,1,2); return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'fixed error handling for broken full-color images'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ZrtpPacketHello::ZrtpPacketHello(uint8_t *data) { DEBUGOUT((fprintf(stdout, "Creating Hello packet from data\n"))); zrtpHeader = (zrtpPacketHeader_t *)&((HelloPacket_t *)data)->hdr; // the standard header helloHeader = (Hello_t *)&((HelloPacket_t *)data)->hello; uint32_t t = *((uint32_t*)&helloHeader->flags); uint32_t temp = zrtpNtohl(t); nHash = (temp & (0xf << 16)) >> 16; nCipher = (temp & (0xf << 12)) >> 12; nAuth = (temp & (0xf << 8)) >> 8; nPubkey = (temp & (0xf << 4)) >> 4; nSas = temp & 0xf; // +2 : the MAC at the end of the packet computedLength = nHash + nCipher + nAuth + nPubkey + nSas + sizeof(HelloPacket_t)/ZRTP_WORD_SIZE + 2; oHash = sizeof(Hello_t); oCipher = oHash + (nHash * ZRTP_WORD_SIZE); oAuth = oCipher + (nCipher * ZRTP_WORD_SIZE); oPubkey = oAuth + (nAuth * ZRTP_WORD_SIZE); oSas = oPubkey + (nPubkey * ZRTP_WORD_SIZE); oHmac = oSas + (nSas * ZRTP_WORD_SIZE); // offset to HMAC } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd - limit length of memcpy - limit number of offered algorithms in Hello packet - length check in PING packet - fix a small coding error'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status AuthorizationManager::acquirePrivilegesFromPrivilegeDocument( const std::string& dbname, const PrincipalName& principal, const BSONObj& privilegeDocument) { if (!_authenticatedPrincipals.lookup(principal)) { return Status(ErrorCodes::UserNotFound, mongoutils::str::stream() << "No authenticated principle found with name: " << principal.getUser() << " from database " << principal.getDB(), 0); } if (principal.getUser() == internalSecurity.user) { // Grant full access to internal user ActionSet allActions; allActions.addAllActions(); return acquirePrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE, allActions), principal); } return buildPrivilegeSet(dbname, principal, privilegeDocument, &_acquiredPrivileges); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user. Uncorrected, this can cause replica set heartbeats to stall behind operations that hold the read lock for a long time.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int _ber_skip_length(int length) { if (length > 0x80) return 3; else return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>