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>
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
3
Edit dataset card