instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } }
167,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProcessStateChangesUnifiedPlan( WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan); handler_->OnModifyTransceivers( std::move(states.transceiver_states), action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION); } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} CWE ID: CWE-416
void ProcessStateChangesUnifiedPlan( WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan); if (handler_) { handler_->OnModifyTransceivers( std::move(states.transceiver_states), action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION); } }
173,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
170,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; }
167,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt) { static u32 ip6_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd); hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash); id = ip_idents_reserve(hash, 1); fhdr->identification = htonl(id); } Commit Message: inet: update the IP ID generation algorithm to higher standards. Commit 355b98553789 ("netns: provide pure entropy for net_hash_mix()") makes net_hash_mix() return a true 32 bits of entropy. When used in the IP ID generation algorithm, this has the effect of extending the IP ID generation key from 32 bits to 64 bits. However, net_hash_mix() is only used for IP ID generation starting with kernel version 4.1. Therefore, earlier kernels remain with 32-bit key no matter what the net_hash_mix() return value is. This change addresses the issue by explicitly extending the key to 64 bits for kernels older than 4.1. Signed-off-by: Amit Klein <[email protected]> Cc: Ben Hutchings <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200
static void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt) { static u32 ip6_idents_hashrnd __read_mostly; static u32 ip6_idents_hashrnd_extra __read_mostly; u32 hash, id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); net_get_random_once(&ip6_idents_hashrnd_extra, sizeof(ip6_idents_hashrnd_extra)); hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd); hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash); hash = jhash_1word(hash, ip6_idents_hashrnd_extra); id = ip_idents_reserve(hash, 1); fhdr->identification = htonl(id); }
170,238
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: choose_filters(struct archive_read *a) { int number_bidders, i, bid, best_bid; struct archive_read_filter_bidder *bidder, *best_bidder; struct archive_read_filter *filter; ssize_t avail; int r; for (;;) { number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]); best_bid = 0; best_bidder = NULL; bidder = a->bidders; for (i = 0; i < number_bidders; i++, bidder++) { if (bidder->bid != NULL) { bid = (bidder->bid)(bidder, a->filter); if (bid > best_bid) { best_bid = bid; best_bidder = bidder; } } } /* If no bidder, we're done. */ if (best_bidder == NULL) { /* Verify the filter by asking it for some data. */ __archive_read_filter_ahead(a->filter, 1, &avail); if (avail < 0) { __archive_read_close_filters(a); __archive_read_free_filters(a); return (ARCHIVE_FATAL); } a->archive.compression_name = a->filter->name; a->archive.compression_code = a->filter->code; return (ARCHIVE_OK); } filter = (struct archive_read_filter *)calloc(1, sizeof(*filter)); if (filter == NULL) return (ARCHIVE_FATAL); filter->bidder = best_bidder; filter->archive = a; filter->upstream = a->filter; a->filter = filter; r = (best_bidder->init)(a->filter); if (r != ARCHIVE_OK) { __archive_read_close_filters(a); __archive_read_free_filters(a); return (ARCHIVE_FATAL); } } } Commit Message: Fix a potential crash issue discovered by Alexander Cherepanov: It seems bsdtar automatically handles stacked compression. This is a nice feature but it could be problematic when it's completely unlimited. Most clearly it's illustrated with quines: $ curl -sRO http://www.maximumcompression.com/selfgz.gz $ (ulimit -v 10000000 && bsdtar -tvf selfgz.gz) bsdtar: Error opening archive: Can't allocate data for gzip decompression Without ulimit, bsdtar will eat all available memory. This could also be a problem for other applications using libarchive. CWE ID: CWE-399
choose_filters(struct archive_read *a) { int number_bidders, i, bid, best_bid, n; struct archive_read_filter_bidder *bidder, *best_bidder; struct archive_read_filter *filter; ssize_t avail; int r; for (n = 0; n < 25; ++n) { number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]); best_bid = 0; best_bidder = NULL; bidder = a->bidders; for (i = 0; i < number_bidders; i++, bidder++) { if (bidder->bid != NULL) { bid = (bidder->bid)(bidder, a->filter); if (bid > best_bid) { best_bid = bid; best_bidder = bidder; } } } /* If no bidder, we're done. */ if (best_bidder == NULL) { /* Verify the filter by asking it for some data. */ __archive_read_filter_ahead(a->filter, 1, &avail); if (avail < 0) { __archive_read_close_filters(a); __archive_read_free_filters(a); return (ARCHIVE_FATAL); } a->archive.compression_name = a->filter->name; a->archive.compression_code = a->filter->code; return (ARCHIVE_OK); } filter = (struct archive_read_filter *)calloc(1, sizeof(*filter)); if (filter == NULL) return (ARCHIVE_FATAL); filter->bidder = best_bidder; filter->archive = a; filter->upstream = a->filter; a->filter = filter; r = (best_bidder->init)(a->filter); if (r != ARCHIVE_OK) { __archive_read_close_filters(a); __archive_read_free_filters(a); return (ARCHIVE_FATAL); } } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Input requires too many filters for decoding"); return (ARCHIVE_FATAL); }
166,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_es_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ipsec_header { uint8_t sa_index[2]; uint8_t ttl; uint8_t type; uint8_t spi[4]; uint8_t src_ip[4]; uint8_t dst_ip[4]; }; u_int rewrite_len,es_type_bundle; const struct juniper_ipsec_header *ih; l2info.pictype = DLT_JUNIPER_ES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ih = (const struct juniper_ipsec_header *)p; switch (ih->type) { case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE: rewrite_len = 0; es_type_bundle = 1; break; case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE: rewrite_len = 16; es_type_bundle = 0; break; default: ND_PRINT((ndo, "ES Invalid type %u, length %u", ih->type, l2info.length)); return l2info.header_len; } l2info.length-=rewrite_len; p+=rewrite_len; if (ndo->ndo_eflag) { if (!es_type_bundle) { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, EXTRACT_32BITS(&ih->spi), ipaddr_string(ndo, &ih->src_ip), ipaddr_string(ndo, &ih->dst_ip), l2info.length)); } else { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, l2info.length)); } } ip_print(ndo, p, l2info.length); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_es_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ipsec_header { uint8_t sa_index[2]; uint8_t ttl; uint8_t type; uint8_t spi[4]; uint8_t src_ip[4]; uint8_t dst_ip[4]; }; u_int rewrite_len,es_type_bundle; const struct juniper_ipsec_header *ih; l2info.pictype = DLT_JUNIPER_ES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ih = (const struct juniper_ipsec_header *)p; ND_TCHECK(*ih); switch (ih->type) { case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE: rewrite_len = 0; es_type_bundle = 1; break; case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE: rewrite_len = 16; es_type_bundle = 0; break; default: ND_PRINT((ndo, "ES Invalid type %u, length %u", ih->type, l2info.length)); return l2info.header_len; } l2info.length-=rewrite_len; p+=rewrite_len; if (ndo->ndo_eflag) { if (!es_type_bundle) { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, EXTRACT_32BITS(&ih->spi), ipaddr_string(ndo, &ih->src_ip), ipaddr_string(ndo, &ih->dst_ip), l2info.length)); } else { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, l2info.length)); } } ip_print(ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; }
167,916
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; } Commit Message: [media] media: info leak in __media_device_enum_links() These structs have holes and reserved struct members which aren't cleared. I've added a memset() so we don't leak stack information. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Laurent Pinchart <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-200
static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; memset(&pad, 0, sizeof(pad)); media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; memset(&link, 0, sizeof(link)); media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; }
167,576
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_timer_user_release(struct inode *inode, struct file *file) { struct snd_timer_user *tu; if (file->private_data) { tu = file->private_data; file->private_data = NULL; if (tu->timeri) snd_timer_close(tu->timeri); kfree(tu->queue); kfree(tu->tqueue); kfree(tu); } return 0; } Commit Message: ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static int snd_timer_user_release(struct inode *inode, struct file *file) { struct snd_timer_user *tu; if (file->private_data) { tu = file->private_data; file->private_data = NULL; mutex_lock(&tu->ioctl_lock); if (tu->timeri) snd_timer_close(tu->timeri); mutex_unlock(&tu->ioctl_lock); kfree(tu->queue); kfree(tu->tqueue); kfree(tu); } return 0; }
167,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_inquire_sec_context_by_oid( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; ret = gss_inquire_sec_context_by_oid(minor_status, context_handle, desired_object, data_set); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_inquire_sec_context_by_oid( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; /* There are no SPNEGO-specific OIDs for this function. */ if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_UNAVAILABLE); ret = gss_inquire_sec_context_by_oid(minor_status, sc->ctx_handle, desired_object, data_set); return (ret); }
166,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void test_base64_lengths(void) { const char *in = "FuseMuse"; char out1[32]; char out2[32]; size_t enclen; int declen; /* Encoding a zero-length string should fail */ enclen = mutt_b64_encode(out1, in, 0, 32); if (!TEST_CHECK(enclen == 0)) { TEST_MSG("Expected: %zu", 0); TEST_MSG("Actual : %zu", enclen); } /* Decoding a zero-length string should fail, too */ out1[0] = '\0'; declen = mutt_b64_decode(out2, out1); if (!TEST_CHECK(declen == -1)) { TEST_MSG("Expected: %zu", -1); TEST_MSG("Actual : %zu", declen); } /* Encode one to eight bytes, check the lengths of the returned string */ for (size_t i = 1; i <= 8; ++i) { enclen = mutt_b64_encode(out1, in, i, 32); size_t exp = ((i + 2) / 3) << 2; if (!TEST_CHECK(enclen == exp)) { TEST_MSG("Expected: %zu", exp); TEST_MSG("Actual : %zu", enclen); } declen = mutt_b64_decode(out2, out1); if (!TEST_CHECK(declen == i)) { TEST_MSG("Expected: %zu", i); TEST_MSG("Actual : %zu", declen); } out2[declen] = '\0'; if (!TEST_CHECK(strncmp(out2, in, i) == 0)) { TEST_MSG("Expected: %s", in); TEST_MSG("Actual : %s", out2); } } } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
void test_base64_lengths(void) { const char *in = "FuseMuse"; char out1[32]; char out2[32]; size_t enclen; int declen; /* Encoding a zero-length string should fail */ enclen = mutt_b64_encode(out1, in, 0, 32); if (!TEST_CHECK(enclen == 0)) { TEST_MSG("Expected: %zu", 0); TEST_MSG("Actual : %zu", enclen); } /* Decoding a zero-length string should fail, too */ out1[0] = '\0'; declen = mutt_b64_decode(out2, out1, sizeof(out2)); if (!TEST_CHECK(declen == -1)) { TEST_MSG("Expected: %zu", -1); TEST_MSG("Actual : %zu", declen); } /* Encode one to eight bytes, check the lengths of the returned string */ for (size_t i = 1; i <= 8; ++i) { enclen = mutt_b64_encode(out1, in, i, 32); size_t exp = ((i + 2) / 3) << 2; if (!TEST_CHECK(enclen == exp)) { TEST_MSG("Expected: %zu", exp); TEST_MSG("Actual : %zu", enclen); } declen = mutt_b64_decode(out2, out1, sizeof(out2)); if (!TEST_CHECK(declen == i)) { TEST_MSG("Expected: %zu", i); TEST_MSG("Actual : %zu", declen); } out2[declen] = '\0'; if (!TEST_CHECK(strncmp(out2, in, i) == 0)) { TEST_MSG("Expected: %s", in); TEST_MSG("Actual : %s", out2); } } }
169,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long long Track::GetDefaultDuration() const { return m_info.defaultDuration; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
unsigned long long Track::GetDefaultDuration() const
174,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: ... CWE ID: CWE-20
ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
168,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: selReadStream(FILE *fp) { char *selname; char linebuf[L_BUF_SIZE]; l_int32 sy, sx, cy, cx, i, j, version, ignore; SEL *sel; PROCNAME("selReadStream"); if (!fp) return (SEL *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, " Sel Version %d\n", &version) != 1) return (SEL *)ERROR_PTR("not a sel file", procName, NULL); if (version != SEL_VERSION_NUMBER) return (SEL *)ERROR_PTR("invalid sel version", procName, NULL); if (fgets(linebuf, L_BUF_SIZE, fp) == NULL) return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL); selname = stringNew(linebuf); sscanf(linebuf, " ------ %s ------", selname); if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", &sy, &sx, &cy, &cx) != 4) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("dimensions not read", procName, NULL); } if ((sel = selCreate(sy, sx, selname)) == NULL) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("sel not made", procName, NULL); } selSetOrigin(sel, cy, cx); for (i = 0; i < sy; i++) { ignore = fscanf(fp, " "); for (j = 0; j < sx; j++) ignore = fscanf(fp, "%1d", &sel->data[i][j]); ignore = fscanf(fp, "\n"); } ignore = fscanf(fp, "\n"); LEPT_FREE(selname); return sel; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
selReadStream(FILE *fp) { char *selname; char linebuf[L_BUFSIZE]; l_int32 sy, sx, cy, cx, i, j, version, ignore; SEL *sel; PROCNAME("selReadStream"); if (!fp) return (SEL *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, " Sel Version %d\n", &version) != 1) return (SEL *)ERROR_PTR("not a sel file", procName, NULL); if (version != SEL_VERSION_NUMBER) return (SEL *)ERROR_PTR("invalid sel version", procName, NULL); if (fgets(linebuf, L_BUFSIZE, fp) == NULL) return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL); selname = stringNew(linebuf); sscanf(linebuf, " ------ %200s ------", selname); if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", &sy, &sx, &cy, &cx) != 4) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("dimensions not read", procName, NULL); } if ((sel = selCreate(sy, sx, selname)) == NULL) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("sel not made", procName, NULL); } selSetOrigin(sel, cy, cx); for (i = 0; i < sy; i++) { ignore = fscanf(fp, " "); for (j = 0; j < sx; j++) ignore = fscanf(fp, "%1d", &sel->data[i][j]); ignore = fscanf(fp, "\n"); } ignore = fscanf(fp, "\n"); LEPT_FREE(selname); return sel; }
169,329
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LPSTR tr_esc_str(LPCSTR arg, bool format) { LPSTR tmp = NULL; size_t cs = 0, x, ds, len; size_t s; if (NULL == arg) return NULL; s = strlen(arg); /* Find trailing whitespaces */ while ((s > 0) && isspace(arg[s - 1])) s--; /* Prepare a initial buffer with the size of the result string. */ ds = s + 1; if (s) tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not allocate string buffer.\n"); exit(-2); } /* Copy character for character and check, if it is necessary to escape. */ memset(tmp, 0, ds * sizeof(CHAR)); for (x = 0; x < s; x++) { switch (arg[x]) { case '<': len = format ? 13 : 4; ds += len - 1; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-3); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "<replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '>': len = format ? 14 : 4; ds += len - 1; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-4); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "</replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '\'': ds += 5; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-5); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'p'; tmp[cs++] = 'o'; tmp[cs++] = 's'; tmp[cs++] = ';'; break; case '"': ds += 5; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-6); } tmp[cs++] = '&'; tmp[cs++] = 'q'; tmp[cs++] = 'u'; tmp[cs++] = 'o'; tmp[cs++] = 't'; tmp[cs++] = ';'; break; case '&': ds += 4; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-7); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'm'; tmp[cs++] = 'p'; tmp[cs++] = ';'; break; default: tmp[cs++] = arg[x]; break; } /* Assure, the string is '\0' terminated. */ tmp[ds - 1] = '\0'; } return tmp; } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
LPSTR tr_esc_str(LPCSTR arg, bool format) { LPSTR tmp = NULL; LPSTR tmp2 = NULL; size_t cs = 0, x, ds, len; size_t s; if (NULL == arg) return NULL; s = strlen(arg); /* Find trailing whitespaces */ while ((s > 0) && isspace(arg[s - 1])) s--; /* Prepare a initial buffer with the size of the result string. */ ds = s + 1; if (s) { tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; } if (NULL == tmp) { fprintf(stderr, "Could not allocate string buffer.\n"); exit(-2); } /* Copy character for character and check, if it is necessary to escape. */ memset(tmp, 0, ds * sizeof(CHAR)); for (x = 0; x < s; x++) { switch (arg[x]) { case '<': len = format ? 13 : 4; ds += len - 1; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-3); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "<replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '>': len = format ? 14 : 4; ds += len - 1; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-4); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "</replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '\'': ds += 5; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-5); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'p'; tmp[cs++] = 'o'; tmp[cs++] = 's'; tmp[cs++] = ';'; break; case '"': ds += 5; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-6); } tmp[cs++] = '&'; tmp[cs++] = 'q'; tmp[cs++] = 'u'; tmp[cs++] = 'o'; tmp[cs++] = 't'; tmp[cs++] = ';'; break; case '&': ds += 4; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-7); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'm'; tmp[cs++] = 'p'; tmp[cs++] = ';'; break; default: tmp[cs++] = arg[x]; break; } /* Assure, the string is '\0' terminated. */ tmp[ds - 1] = '\0'; } return tmp; }
169,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { case TLS_ST_SW_HELLO_REQ: s->shutdown = 0; if (SSL_IS_DTLS(s)) dtls1_clear_record_buffer(s); break; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: s->shutdown = 0; if (SSL_IS_DTLS(s)) { dtls1_clear_record_buffer(s); /* We don't buffer this message so don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_SRVR_HELLO: if (SSL_IS_DTLS(s)) { /* * Messages we write from now on should be bufferred and * retransmitted if necessary, so we need to use the timer now */ st->use_timer = 1; } break; case TLS_ST_SW_SRVR_DONE: #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) return dtls_wait_for_dry(s); #endif return WORK_FINISHED_CONTINUE; case TLS_ST_SW_SESSION_TICKET: if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_CHANGE: s->session->cipher = s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ossl_statem_set_error(s); return WORK_ERROR; } if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer. This might have * already been set to 0 if we sent a NewSessionTicket message, * but we'll set it again here in case we didn't. */ st->use_timer = 0; } return WORK_FINISHED_CONTINUE; case TLS_ST_OK: return tls_finish_handshake(s, wst); default: /* No pre work to be done */ break; } return WORK_FINISHED_CONTINUE; } Commit Message: CWE ID: CWE-399
WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { case TLS_ST_SW_HELLO_REQ: s->shutdown = 0; if (SSL_IS_DTLS(s)) dtls1_clear_sent_buffer(s); break; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: s->shutdown = 0; if (SSL_IS_DTLS(s)) { dtls1_clear_sent_buffer(s); /* We don't buffer this message so don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_SRVR_HELLO: if (SSL_IS_DTLS(s)) { /* * Messages we write from now on should be bufferred and * retransmitted if necessary, so we need to use the timer now */ st->use_timer = 1; } break; case TLS_ST_SW_SRVR_DONE: #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) return dtls_wait_for_dry(s); #endif return WORK_FINISHED_CONTINUE; case TLS_ST_SW_SESSION_TICKET: if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_CHANGE: s->session->cipher = s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ossl_statem_set_error(s); return WORK_ERROR; } if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer. This might have * already been set to 0 if we sent a NewSessionTicket message, * but we'll set it again here in case we didn't. */ st->use_timer = 0; } return WORK_FINISHED_CONTINUE; case TLS_ST_OK: return tls_finish_handshake(s, wst); default: /* No pre work to be done */ break; } return WORK_FINISHED_CONTINUE; }
165,199
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::UnserializeFloat( IMkvReader* pReader, long long pos, long long size_, double& result) { assert(pReader); assert(pos >= 0); if ((size_ != 4) && (size_ != 8)) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) //error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { assert(size == 8); union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long mkvparser::UnserializeFloat( { signed char b; const long status = pReader->Read(pos, 1, (unsigned char*)&b); if (status < 0) return status; result = b; ++pos; } for (long i = 1; i < size; ++i) { unsigned char b; const long status = pReader->Read(pos, 1, &b); if (status < 0) return status; result <<= 8; result |= b; ++pos; } return 0; // success }
174,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemForEachPtr comp = (xsltStyleItemForEachPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif int i; xmlXPathObjectPtr res = NULL; xmlNodePtr cur, curInst; xmlNodeSetPtr list = NULL; xmlNodeSetPtr oldList; int oldXPProximityPosition, oldXPContextSize; xmlNodePtr oldContextNode; xsltTemplatePtr oldCurTemplRule; xmlDocPtr oldXPDoc; xsltDocumentPtr oldDocInfo; xmlXPathContextPtr xpctxt; if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) { xsltGenericError(xsltGenericErrorContext, "xsltForEach(): Bad arguments.\n"); return; } if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltForEach(): " "The XSLT 'for-each' instruction was not compiled.\n"); return; } if ((comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltForEach(): " "The selecting expression of the XSLT 'for-each' " "instruction was not compiled correctly.\n"); return; } xpctxt = ctxt->xpathCtxt; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select %s\n", comp->select)); #endif /* * Save context states. */ oldDocInfo = ctxt->document; oldList = ctxt->nodeList; oldContextNode = ctxt->node; /* * The "current template rule" is cleared for the instantiation of * xsl:for-each. */ oldCurTemplRule = ctxt->currentTemplateRule; ctxt->currentTemplateRule = NULL; oldXPDoc = xpctxt->doc; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; /* * Set up XPath. */ xpctxt->node = contextNode; #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif /* * Evaluate the 'select' expression. */ res = xmlXPathCompiledEval(comp->comp, ctxt->xpathCtxt); if (res != NULL) { if (res->type == XPATH_NODESET) list = res->nodesetval; else { xsltTransformError(ctxt, NULL, inst, "The 'select' expression does not evaluate to a node set.\n"); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select didn't evaluate to a node list\n")); #endif goto error; } } else { xsltTransformError(ctxt, NULL, inst, "Failed to evaluate the 'select' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } if ((list == NULL) || (list->nodeNr <= 0)) goto exit; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select evaluates to %d nodes\n", list->nodeNr)); #endif /* * Restore XPath states for the "current node". */ xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->node = contextNode; /* * Set the list; this has to be done already here for xsltDoSortFunction(). */ ctxt->nodeList = list; /* * Handle xsl:sort instructions and skip them for further processing. * BUG TODO: We are not using namespaced potentially defined on the * xsl:sort element; XPath expression might fail. */ curInst = inst->children; if (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) { int nbsorts = 0; xmlNodePtr sorts[XSLT_MAX_SORT]; sorts[nbsorts++] = curInst; #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(curInst, contextNode, NULL, ctxt); #endif curInst = curInst->next; while (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) { if (nbsorts >= XSLT_MAX_SORT) { xsltTransformError(ctxt, NULL, curInst, "The number of xsl:sort instructions exceeds the " "maximum (%d) allowed by this processor.\n", XSLT_MAX_SORT); goto error; } else { sorts[nbsorts++] = curInst; } #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(curInst, contextNode, NULL, ctxt); #endif curInst = curInst->next; } xsltDoSortFunction(ctxt, sorts, nbsorts); } xpctxt->contextSize = list->nodeNr; /* * Instantiate the sequence constructor for each selected node. */ for (i = 0; i < list->nodeNr; i++) { cur = list->nodeTab[i]; /* * The selected node becomes the "current node". */ ctxt->node = cur; /* * An xsl:for-each can change the current context doc. * OPTIMIZE TODO: Get rid of the need to set the context doc. */ if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL)) xpctxt->doc = cur->doc; xpctxt->proximityPosition = i + 1; xsltApplySequenceConstructor(ctxt, cur, curInst, NULL); } exit: error: if (res != NULL) xmlXPathFreeObject(res); /* * Restore old states. */ ctxt->document = oldDocInfo; ctxt->nodeList = oldList; ctxt->node = oldContextNode; ctxt->currentTemplateRule = oldCurTemplRule; xpctxt->doc = oldXPDoc; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemForEachPtr comp = (xsltStyleItemForEachPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif int i; xmlXPathObjectPtr res = NULL; xmlNodePtr cur, curInst; xmlNodeSetPtr list = NULL; xmlNodeSetPtr oldList; int oldXPProximityPosition, oldXPContextSize; xmlNodePtr oldContextNode; xsltTemplatePtr oldCurTemplRule; xmlDocPtr oldXPDoc; xsltDocumentPtr oldDocInfo; xmlXPathContextPtr xpctxt; if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) { xsltGenericError(xsltGenericErrorContext, "xsltForEach(): Bad arguments.\n"); return; } if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltForEach(): " "The XSLT 'for-each' instruction was not compiled.\n"); return; } if ((comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltForEach(): " "The selecting expression of the XSLT 'for-each' " "instruction was not compiled correctly.\n"); return; } xpctxt = ctxt->xpathCtxt; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select %s\n", comp->select)); #endif /* * Save context states. */ oldDocInfo = ctxt->document; oldList = ctxt->nodeList; oldContextNode = ctxt->node; /* * The "current template rule" is cleared for the instantiation of * xsl:for-each. */ oldCurTemplRule = ctxt->currentTemplateRule; ctxt->currentTemplateRule = NULL; oldXPDoc = xpctxt->doc; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; /* * Evaluate the 'select' expression. */ res = xsltPreCompEval(ctxt, contextNode, comp); if (res != NULL) { if (res->type == XPATH_NODESET) list = res->nodesetval; else { xsltTransformError(ctxt, NULL, inst, "The 'select' expression does not evaluate to a node set.\n"); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select didn't evaluate to a node list\n")); #endif goto error; } } else { xsltTransformError(ctxt, NULL, inst, "Failed to evaluate the 'select' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } if ((list == NULL) || (list->nodeNr <= 0)) goto exit; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select evaluates to %d nodes\n", list->nodeNr)); #endif /* * Set the list; this has to be done already here for xsltDoSortFunction(). */ ctxt->nodeList = list; /* * Handle xsl:sort instructions and skip them for further processing. * BUG TODO: We are not using namespaced potentially defined on the * xsl:sort element; XPath expression might fail. */ curInst = inst->children; if (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) { int nbsorts = 0; xmlNodePtr sorts[XSLT_MAX_SORT]; sorts[nbsorts++] = curInst; #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(curInst, contextNode, NULL, ctxt); #endif curInst = curInst->next; while (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) { if (nbsorts >= XSLT_MAX_SORT) { xsltTransformError(ctxt, NULL, curInst, "The number of xsl:sort instructions exceeds the " "maximum (%d) allowed by this processor.\n", XSLT_MAX_SORT); goto error; } else { sorts[nbsorts++] = curInst; } #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(curInst, contextNode, NULL, ctxt); #endif curInst = curInst->next; } xsltDoSortFunction(ctxt, sorts, nbsorts); } xpctxt->contextSize = list->nodeNr; /* * Instantiate the sequence constructor for each selected node. */ for (i = 0; i < list->nodeNr; i++) { cur = list->nodeTab[i]; /* * The selected node becomes the "current node". */ ctxt->node = cur; /* * An xsl:for-each can change the current context doc. * OPTIMIZE TODO: Get rid of the need to set the context doc. */ if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL)) xpctxt->doc = cur->doc; xpctxt->proximityPosition = i + 1; xsltApplySequenceConstructor(ctxt, cur, curInst, NULL); } exit: error: if (res != NULL) xmlXPathFreeObject(res); /* * Restore old states. */ ctxt->document = oldDocInfo; ctxt->nodeList = oldList; ctxt->node = oldContextNode; ctxt->currentTemplateRule = oldCurTemplRule; xpctxt->doc = oldXPDoc; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; }
173,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioSystemImplTest() : use_audio_thread_(GetParam()), audio_thread_("AudioSystemThread") { if (use_audio_thread_) { audio_thread_.StartAndWaitForTesting(); audio_manager_.reset( new media::MockAudioManager(audio_thread_.task_runner())); } else { audio_manager_.reset(new media::MockAudioManager( base::ThreadTaskRunnerHandle::Get().get())); } audio_manager_->SetInputStreamParameters( media::AudioParameters::UnavailableDeviceParams()); audio_system_ = media::AudioSystemImpl::Create(audio_manager_.get()); EXPECT_EQ(AudioSystem::Get(), audio_system_.get()); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
AudioSystemImplTest() : use_audio_thread_(GetParam()), audio_thread_("AudioSystemThread"), input_params_(AudioParameters::AUDIO_PCM_LINEAR, CHANNEL_LAYOUT_MONO, AudioParameters::kTelephoneSampleRate, 16, AudioParameters::kTelephoneSampleRate / 10), output_params_(AudioParameters::AUDIO_PCM_LINEAR, CHANNEL_LAYOUT_MONO, AudioParameters::kTelephoneSampleRate, 16, AudioParameters::kTelephoneSampleRate / 20), default_output_params_(AudioParameters::AUDIO_PCM_LINEAR, CHANNEL_LAYOUT_MONO, AudioParameters::kTelephoneSampleRate, 16, AudioParameters::kTelephoneSampleRate / 30) { if (use_audio_thread_) { audio_thread_.StartAndWaitForTesting(); audio_manager_.reset( new media::MockAudioManager(audio_thread_.task_runner())); } else { audio_manager_.reset(new media::MockAudioManager( base::ThreadTaskRunnerHandle::Get().get())); } audio_manager_->SetInputStreamParameters(input_params_); audio_manager_->SetOutputStreamParameters(output_params_); audio_manager_->SetDefaultOutputStreamParameters(default_output_params_); audio_system_ = media::AudioSystemImpl::Create(audio_manager_.get()); EXPECT_EQ(AudioSystem::Get(), audio_system_.get()); }
171,989
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAVC::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAVC::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (!isValidOMXParam(params)) { return OMX_ErrorBadParameter; } if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (!isValidOMXParam(params)) { return OMX_ErrorBadParameter; } if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } }
174,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels* next_image->columns,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } Commit Message: Fixed overflow. CWE ID: CWE-125
static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); }
170,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SpeechRecognitionManagerImpl::SpeechRecognitionManagerImpl( media::AudioSystem* audio_system, MediaStreamManager* media_stream_manager) : audio_system_(audio_system), media_stream_manager_(media_stream_manager), primary_session_id_(kSessionIDInvalid), last_session_id_(kSessionIDInvalid), is_dispatching_event_(false), delegate_(GetContentClient() ->browser() ->CreateSpeechRecognitionManagerDelegate()), weak_factory_(this) { DCHECK(!g_speech_recognition_manager_impl); g_speech_recognition_manager_impl = this; frame_deletion_observer_.reset(new FrameDeletionObserver( base::BindRepeating(&SpeechRecognitionManagerImpl::AbortSessionImpl, weak_factory_.GetWeakPtr()))); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
SpeechRecognitionManagerImpl::SpeechRecognitionManagerImpl( media::AudioSystem* audio_system, MediaStreamManager* media_stream_manager) : audio_system_(audio_system), media_stream_manager_(media_stream_manager), primary_session_id_(kSessionIDInvalid), last_session_id_(kSessionIDInvalid), is_dispatching_event_(false), delegate_(GetContentClient() ->browser() ->CreateSpeechRecognitionManagerDelegate()), requester_id_(next_requester_id_++), weak_factory_(this) { DCHECK(!g_speech_recognition_manager_impl); g_speech_recognition_manager_impl = this; frame_deletion_observer_.reset(new FrameDeletionObserver( base::BindRepeating(&SpeechRecognitionManagerImpl::AbortSessionImpl, weak_factory_.GetWeakPtr()))); }
173,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags) { struct fs_struct *fs, *new_fs = NULL; struct files_struct *fd, *new_fd = NULL; struct cred *new_cred = NULL; struct nsproxy *new_nsproxy = NULL; int do_sysvsem = 0; int err; /* * If unsharing a user namespace must also unshare the thread. */ if (unshare_flags & CLONE_NEWUSER) unshare_flags |= CLONE_THREAD; /* * If unsharing a pid namespace must also unshare the thread. */ if (unshare_flags & CLONE_NEWPID) unshare_flags |= CLONE_THREAD; /* * If unsharing a thread from a thread group, must also unshare vm. */ if (unshare_flags & CLONE_THREAD) unshare_flags |= CLONE_VM; /* * If unsharing vm, must also unshare signal handlers. */ if (unshare_flags & CLONE_VM) unshare_flags |= CLONE_SIGHAND; /* * If unsharing namespace, must also unshare filesystem information. */ if (unshare_flags & CLONE_NEWNS) unshare_flags |= CLONE_FS; err = check_unshare_flags(unshare_flags); if (err) goto bad_unshare_out; /* * CLONE_NEWIPC must also detach from the undolist: after switching * to a new ipc namespace, the semaphore arrays from the old * namespace are unreachable. */ if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM)) do_sysvsem = 1; err = unshare_fs(unshare_flags, &new_fs); if (err) goto bad_unshare_out; err = unshare_fd(unshare_flags, &new_fd); if (err) goto bad_unshare_cleanup_fs; err = unshare_userns(unshare_flags, &new_cred); if (err) goto bad_unshare_cleanup_fd; err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, new_cred, new_fs); if (err) goto bad_unshare_cleanup_cred; if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) { if (do_sysvsem) { /* * CLONE_SYSVSEM is equivalent to sys_exit(). */ exit_sem(current); } if (new_nsproxy) switch_task_namespaces(current, new_nsproxy); task_lock(current); if (new_fs) { fs = current->fs; spin_lock(&fs->lock); current->fs = new_fs; if (--fs->users) new_fs = NULL; else new_fs = fs; spin_unlock(&fs->lock); } if (new_fd) { fd = current->files; current->files = new_fd; new_fd = fd; } task_unlock(current); if (new_cred) { /* Install the new user namespace */ commit_creds(new_cred); new_cred = NULL; } } bad_unshare_cleanup_cred: if (new_cred) put_cred(new_cred); bad_unshare_cleanup_fd: if (new_fd) put_files_struct(new_fd); bad_unshare_cleanup_fs: if (new_fs) free_fs_struct(new_fs); bad_unshare_out: return err; } Commit Message: userns: Don't allow CLONE_NEWUSER | CLONE_FS Don't allowing sharing the root directory with processes in a different user namespace. There doesn't seem to be any point, and to allow it would require the overhead of putting a user namespace reference in fs_struct (for permission checks) and incrementing that reference count on practically every call to fork. So just perform the inexpensive test of forbidding sharing fs_struct acrosss processes in different user namespaces. We already disallow other forms of threading when unsharing a user namespace so this should be no real burden in practice. This updates setns, clone, and unshare to disallow multiple user namespaces sharing an fs_struct. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags) { struct fs_struct *fs, *new_fs = NULL; struct files_struct *fd, *new_fd = NULL; struct cred *new_cred = NULL; struct nsproxy *new_nsproxy = NULL; int do_sysvsem = 0; int err; /* * If unsharing a user namespace must also unshare the thread. */ if (unshare_flags & CLONE_NEWUSER) unshare_flags |= CLONE_THREAD | CLONE_FS; /* * If unsharing a pid namespace must also unshare the thread. */ if (unshare_flags & CLONE_NEWPID) unshare_flags |= CLONE_THREAD; /* * If unsharing a thread from a thread group, must also unshare vm. */ if (unshare_flags & CLONE_THREAD) unshare_flags |= CLONE_VM; /* * If unsharing vm, must also unshare signal handlers. */ if (unshare_flags & CLONE_VM) unshare_flags |= CLONE_SIGHAND; /* * If unsharing namespace, must also unshare filesystem information. */ if (unshare_flags & CLONE_NEWNS) unshare_flags |= CLONE_FS; err = check_unshare_flags(unshare_flags); if (err) goto bad_unshare_out; /* * CLONE_NEWIPC must also detach from the undolist: after switching * to a new ipc namespace, the semaphore arrays from the old * namespace are unreachable. */ if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM)) do_sysvsem = 1; err = unshare_fs(unshare_flags, &new_fs); if (err) goto bad_unshare_out; err = unshare_fd(unshare_flags, &new_fd); if (err) goto bad_unshare_cleanup_fs; err = unshare_userns(unshare_flags, &new_cred); if (err) goto bad_unshare_cleanup_fd; err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, new_cred, new_fs); if (err) goto bad_unshare_cleanup_cred; if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) { if (do_sysvsem) { /* * CLONE_SYSVSEM is equivalent to sys_exit(). */ exit_sem(current); } if (new_nsproxy) switch_task_namespaces(current, new_nsproxy); task_lock(current); if (new_fs) { fs = current->fs; spin_lock(&fs->lock); current->fs = new_fs; if (--fs->users) new_fs = NULL; else new_fs = fs; spin_unlock(&fs->lock); } if (new_fd) { fd = current->files; current->files = new_fd; new_fd = fd; } task_unlock(current); if (new_cred) { /* Install the new user namespace */ commit_creds(new_cred); new_cred = NULL; } } bad_unshare_cleanup_cred: if (new_cred) put_cred(new_cred); bad_unshare_cleanup_fd: if (new_fd) put_files_struct(new_fd); bad_unshare_cleanup_fs: if (new_fs) free_fs_struct(new_fs); bad_unshare_out: return err; }
166,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err("No USB device connected to ttyUSB%i\n", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, "could not open USB console port\n"); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; } Commit Message: USB: serial: console: fix use-after-free after failed setup Make sure to reset the USB-console port pointer when console setup fails in order to avoid having the struct usb_serial be prematurely freed by the console code when the device is later disconnected. Fixes: 73e487fdb75f ("[PATCH] USB console: fix disconnection issues") Cc: stable <[email protected]> # 2.6.18 Acked-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-416
static int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err("No USB device connected to ttyUSB%i\n", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, "could not open USB console port\n"); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; info->port = NULL; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; }
167,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( const GURL& page_url) const { if (page_url.host() == extension_misc::kBookmarkManagerId) return BookmarksUI::GetFaviconResourceBytes(); if (page_url.SchemeIs(chrome::kExtensionScheme)) { NOTREACHED(); return NULL; } if (!HasWebUIScheme(page_url)) return NULL; #if defined(OS_WIN) if (page_url.host() == chrome::kChromeUIConflictsHost) return ConflictsUI::GetFaviconResourceBytes(); #endif if (page_url.host() == chrome::kChromeUICrashesHost) return CrashesUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIHistoryHost) return HistoryUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIFlagsHost) return FlagsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISessionsHost) return SessionsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIFlashHost) return FlashUI::GetFaviconResourceBytes(); #if !defined(OS_ANDROID) if (page_url.host() == chrome::kChromeUIDownloadsHost) return DownloadsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISettingsHost) return OptionsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISettingsFrameHost) return options2::OptionsUI::GetFaviconResourceBytes(); #endif if (page_url.host() == chrome::kChromeUIPluginsHost) return PluginsUI::GetFaviconResourceBytes(); return NULL; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( const GURL& page_url) const { if (page_url.host() == extension_misc::kBookmarkManagerId) return BookmarksUI::GetFaviconResourceBytes(); if (page_url.SchemeIs(chrome::kExtensionScheme)) { NOTREACHED(); return NULL; } if (!content::GetContentClient()->HasWebUIScheme(page_url)) return NULL; #if defined(OS_WIN) if (page_url.host() == chrome::kChromeUIConflictsHost) return ConflictsUI::GetFaviconResourceBytes(); #endif if (page_url.host() == chrome::kChromeUICrashesHost) return CrashesUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIHistoryHost) return HistoryUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIFlagsHost) return FlagsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISessionsHost) return SessionsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIFlashHost) return FlashUI::GetFaviconResourceBytes(); #if !defined(OS_ANDROID) if (page_url.host() == chrome::kChromeUIDownloadsHost) return DownloadsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISettingsHost) return OptionsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISettingsFrameHost) return options2::OptionsUI::GetFaviconResourceBytes(); #endif if (page_url.host() == chrome::kChromeUIPluginsHost) return PluginsUI::GetFaviconResourceBytes(); return NULL; }
171,007
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } Commit Message: index: fix out-of-bounds read with invalid index entry prefix length The index format in version 4 has prefix-compressed entries, where every index entry can compress its path by using a path prefix of the previous entry. Since implmenting support for this index format version in commit 5625d86b9 (index: support index v4, 2016-05-17), though, we do not correctly verify that the prefix length that we want to reuse is actually smaller or equal to the amount of characters than the length of the previous index entry's path. This can lead to a an integer underflow and subsequently to an out-of-bounds read. Fix this by verifying that the prefix is actually smaller than the previous entry's path length. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-190
static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }
169,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const CuePoint* Cues::GetNext(const CuePoint* pCurr) const { if (pCurr == NULL) return NULL; assert(pCurr->GetTimeCode() >= 0); assert(m_cue_points); assert(m_count >= 1); #if 0 const size_t count = m_count + m_preload_count; size_t index = pCurr->m_index; assert(index < count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); pNext->Load(m_pSegment->m_pReader); #else long index = pCurr->m_index; assert(index < m_count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); assert(pNext->GetTimeCode() >= 0); #endif return pNext; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const CuePoint* Cues::GetNext(const CuePoint* pCurr) const { if (pCurr == NULL || pCurr->GetTimeCode() < 0 || m_cue_points == NULL || m_count < 1) { return NULL; } long index = pCurr->m_index; if (index >= m_count) return NULL; CuePoint* const* const pp = m_cue_points; if (pp == NULL || pp[index] != pCurr) return NULL; ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; if (pNext == NULL || pNext->GetTimeCode() < 0) return NULL; return pNext; }
173,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; int error = 0; lock_sock(sk); opt->src_addr = sp->sa_addr.pptp; if (add_chan(po)) error = -EBUSY; release_sock(sk); return error; } Commit Message: pptp: verify sockaddr_len in pptp_bind() and pptp_connect() Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; int error = 0; if (sockaddr_len < sizeof(struct sockaddr_pppox)) return -EINVAL; lock_sock(sk); opt->src_addr = sp->sa_addr.pptp; if (add_chan(po)) error = -EBUSY; release_sock(sk); return error; }
166,560
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code, uintptr_t abort_msg_address, bool dump_sibling_threads, bool* detach_failed, int* total_sleep_time_usec) { log_t log; log.current_tid = tid; log.crashed_tid = tid; if ((mkdir(TOMBSTONE_DIR, 0755) == -1) && (errno != EEXIST)) { _LOG(&log, logtype::ERROR, "failed to create %s: %s\n", TOMBSTONE_DIR, strerror(errno)); } if (chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM) == -1) { _LOG(&log, logtype::ERROR, "failed to change ownership of %s: %s\n", TOMBSTONE_DIR, strerror(errno)); } int fd = -1; char* path = NULL; if (selinux_android_restorecon(TOMBSTONE_DIR, 0) == 0) { path = find_and_open_tombstone(&fd); } else { _LOG(&log, logtype::ERROR, "Failed to restore security context, not writing tombstone.\n"); } if (fd < 0) { _LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n"); *detach_failed = false; return NULL; } log.tfd = fd; int amfd = activity_manager_connect(); log.amfd = amfd; *detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address, dump_sibling_threads, total_sleep_time_usec); ALOGI("\nTombstone written to: %s\n", path); close(amfd); close(fd); return path; } Commit Message: Don't create tombstone directory. Partial backport of cf79748. Bug: http://b/26403620 Change-Id: Ib877ab6cfab6aef079830c5a50ba81141ead35ee CWE ID: CWE-264
char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code, uintptr_t abort_msg_address, bool dump_sibling_threads, bool* detach_failed, int* total_sleep_time_usec) { log_t log; log.current_tid = tid; log.crashed_tid = tid; int fd = -1; char* path = find_and_open_tombstone(&fd); if (fd < 0) { _LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n"); *detach_failed = false; return NULL; } log.tfd = fd; int amfd = activity_manager_connect(); log.amfd = amfd; *detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address, dump_sibling_threads, total_sleep_time_usec); ALOGI("\nTombstone written to: %s\n", path); close(amfd); close(fd); return path; }
173,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_syscall(struct x86_emulate_ctxt *ctxt) { struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; /* syscall is not available in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_EFER, &efer); setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_STAR, &msr_data); msr_data >>= 32; cs_sel = (u16)(msr_data & 0xfffc); ss_sel = (u16)(msr_data + 8); if (efer & EFER_LMA) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip; if (efer & EFER_LMA) { #ifdef CONFIG_X86_64 ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF; ops->get_msr(ctxt, ctxt->mode == X86EMUL_MODE_PROT64 ? MSR_LSTAR : MSR_CSTAR, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data); ctxt->eflags &= ~(msr_data | EFLG_RF); #endif } else { /* legacy mode */ ops->get_msr(ctxt, MSR_STAR, &msr_data); ctxt->_eip = (u32)msr_data; ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF); } return X86EMUL_CONTINUE; } Commit Message: KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID:
static int em_syscall(struct x86_emulate_ctxt *ctxt) { struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; /* syscall is not available in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_ud(ctxt); if (!(em_syscall_is_enabled(ctxt))) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_EFER, &efer); setup_syscalls_segments(ctxt, &cs, &ss); if (!(efer & EFER_SCE)) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_STAR, &msr_data); msr_data >>= 32; cs_sel = (u16)(msr_data & 0xfffc); ss_sel = (u16)(msr_data + 8); if (efer & EFER_LMA) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip; if (efer & EFER_LMA) { #ifdef CONFIG_X86_64 ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF; ops->get_msr(ctxt, ctxt->mode == X86EMUL_MODE_PROT64 ? MSR_LSTAR : MSR_CSTAR, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data); ctxt->eflags &= ~(msr_data | EFLG_RF); #endif } else { /* legacy mode */ ops->get_msr(ctxt, MSR_STAR, &msr_data); ctxt->_eip = (u32)msr_data; ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF); } return X86EMUL_CONTINUE; }
165,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; }
167,213
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); return __load_segment_descriptor(ctxt, selector, seg, cpl, X86_TRANSFER_NONE, NULL); } Commit Message: KVM: x86: fix emulation of "MOV SS, null selector" This is CVE-2017-2583. On Intel this causes a failed vmentry because SS's type is neither 3 nor 7 (even though the manual says this check is only done for usable SS, and the dmesg splat says that SS is unusable!). On AMD it's worse: svm.c is confused and sets CPL to 0 in the vmcb. The fix fabricates a data segment descriptor when SS is set to a null selector, so that CPL and SS.DPL are set correctly in the VMCS/vmcb. Furthermore, only allow setting SS to a NULL selector if SS.RPL < 3; this in turn ensures CPL < 3 because RPL must be equal to CPL. Thanks to Andy Lutomirski and Willy Tarreau for help in analyzing the bug and deciphering the manuals. Reported-by: Xiaohan Zhang <[email protected]> Fixes: 79d5b4c3cd809c770d4bf9812635647016c56011 Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID:
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); /* * None of MOV, POP and LSS can load a NULL selector in CPL=3, but * they can load it at CPL<3 (Intel's manual says only LSS can, * but it's wrong). * * However, the Intel manual says that putting IST=1/DPL=3 in * an interrupt gate will result in SS=3 (the AMD manual instead * says it doesn't), so allow SS=3 in __load_segment_descriptor * and only forbid it here. */ if (seg == VCPU_SREG_SS && selector == 3 && ctxt->mode == X86EMUL_MODE_PROT64) return emulate_exception(ctxt, GP_VECTOR, 0, true); return __load_segment_descriptor(ctxt, selector, seg, cpl, X86_TRANSFER_NONE, NULL); }
168,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int extract_status_code(char *buffer, size_t size) { char *buf_code; char *begin; char *end = buffer + size; size_t inc = 0; int code; /* Allocate the room */ buf_code = (char *)MALLOC(10); /* Status-Code extraction */ while (buffer < end && *buffer++ != ' ') ; begin = buffer; while (buffer < end && *buffer++ != ' ') inc++; strncat(buf_code, begin, inc); code = atoi(buf_code); FREE(buf_code); return code; } Commit Message: Fix buffer overflow in extract_status_code() Issue #960 identified that the buffer allocated for copying the HTTP status code could overflow if the http response was corrupted. This commit changes the way the status code is read, avoids copying data, and also ensures that the status code is three digits long, is non-negative and occurs on the first line of the response. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-119
int extract_status_code(char *buffer, size_t size) { char *end = buffer + size; unsigned long code; /* Status-Code extraction */ while (buffer < end && *buffer != ' ' && *buffer != '\r') buffer++; buffer++; if (buffer + 3 >= end || *buffer == ' ' || buffer[3] != ' ') return 0; code = strtoul(buffer, &end, 10); if (buffer + 3 != end) return 0; return code; }
168,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusNameOwnerChangedCallback( IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer user_data) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); DLOG(INFO) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; return; } LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusNameOwnerChangedCallback( void IBusBusNameOwnerChanged(IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); VLOG(1) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; // |OnConnectionChange| with false here to allow Chrome to return; } VLOG(1) << "IBus config daemon is started. Recovering ibus_config_"; // successfully created, |OnConnectionChange| will be called to MaybeRestoreConnections(); }
170,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; int extra; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; } Commit Message: Fixed CVE-2018-8785 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119
static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; UINT32 extra = 0; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; }
169,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); mutex_unlock(&memcg->thresholds_lock); } Commit Message: mm: memcg: Correct unregistring of events attached to the same eventfd There is an issue when memcg unregisters events that were attached to the same eventfd: - On the first call mem_cgroup_usage_unregister_event() removes all events attached to a given eventfd, and if there were no events left, thresholds->primary would become NULL; - Since there were several events registered, cgroups core will call mem_cgroup_usage_unregister_event() again, but now kernel will oops, as the function doesn't expect that threshold->primary may be NULL. That's a good question whether mem_cgroup_usage_unregister_event() should actually remove all events in one go, but nowadays it can't do any better as cftype->unregister_event callback doesn't pass any private event-associated cookie. So, let's fix the issue by simply checking for threshold->primary. FWIW, w/o the patch the following oops may be observed: BUG: unable to handle kernel NULL pointer dereference at 0000000000000004 IP: [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0 Pid: 574, comm: kworker/0:2 Not tainted 3.3.0-rc4+ #9 Bochs Bochs RIP: 0010:[<ffffffff810be32c>] [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0 RSP: 0018:ffff88001d0b9d60 EFLAGS: 00010246 Process kworker/0:2 (pid: 574, threadinfo ffff88001d0b8000, task ffff88001de91cc0) Call Trace: [<ffffffff8107092b>] cgroup_event_remove+0x2b/0x60 [<ffffffff8103db94>] process_one_work+0x174/0x450 [<ffffffff8103e413>] worker_thread+0x123/0x2d0 Cc: stable <[email protected]> Signed-off-by: Anton Vorontsov <[email protected]> Acked-by: KAMEZAWA Hiroyuki <[email protected]> Cc: Kirill A. Shutemov <[email protected]> Cc: Michal Hocko <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID:
static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); if (!thresholds->primary) goto unlock; usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); unlock: mutex_unlock(&memcg->thresholds_lock); }
165,643
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode, char __user *buf, size_t len, bool compat) { struct file *file = req->ki_filp; ssize_t ret; unsigned long nr_segs; int rw; fmode_t mode; aio_rw_op *rw_op; rw_iter_op *iter_op; struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs; struct iov_iter iter; switch (opcode) { case IOCB_CMD_PREAD: case IOCB_CMD_PREADV: mode = FMODE_READ; rw = READ; rw_op = file->f_op->aio_read; iter_op = file->f_op->read_iter; goto rw_common; case IOCB_CMD_PWRITE: case IOCB_CMD_PWRITEV: mode = FMODE_WRITE; rw = WRITE; rw_op = file->f_op->aio_write; iter_op = file->f_op->write_iter; goto rw_common; rw_common: if (unlikely(!(file->f_mode & mode))) return -EBADF; if (!rw_op && !iter_op) return -EINVAL; if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV) ret = aio_setup_vectored_rw(req, rw, buf, &nr_segs, &len, &iovec, compat); else ret = aio_setup_single_vector(req, rw, buf, &nr_segs, len, iovec); if (!ret) ret = rw_verify_area(rw, file, &req->ki_pos, len); if (ret < 0) { if (iovec != inline_vecs) kfree(iovec); return ret; } len = ret; /* XXX: move/kill - rw_verify_area()? */ /* This matches the pread()/pwrite() logic */ if (req->ki_pos < 0) { ret = -EINVAL; break; } if (rw == WRITE) file_start_write(file); if (iter_op) { iov_iter_init(&iter, rw, iovec, nr_segs, len); ret = iter_op(req, &iter); } else { ret = rw_op(req, iovec, nr_segs, req->ki_pos); } if (rw == WRITE) file_end_write(file); break; case IOCB_CMD_FDSYNC: if (!file->f_op->aio_fsync) return -EINVAL; ret = file->f_op->aio_fsync(req, 1); break; case IOCB_CMD_FSYNC: if (!file->f_op->aio_fsync) return -EINVAL; ret = file->f_op->aio_fsync(req, 0); break; default: pr_debug("EINVAL: no operation provided\n"); return -EINVAL; } if (iovec != inline_vecs) kfree(iovec); if (ret != -EIOCBQUEUED) { /* * There's no easy way to restart the syscall since other AIO's * may be already running. Just fail this IO with EINTR. */ if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR || ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK)) ret = -EINTR; aio_complete(req, ret, 0); } return 0; } Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw() the only non-trivial detail is that we do it before rw_verify_area(), so we'd better cap the length ourselves in aio_setup_single_rw() case (for vectored case rw_copy_check_uvector() will do that for us). Signed-off-by: Al Viro <[email protected]> CWE ID:
static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode, char __user *buf, size_t len, bool compat) { struct file *file = req->ki_filp; ssize_t ret; unsigned long nr_segs; int rw; fmode_t mode; aio_rw_op *rw_op; rw_iter_op *iter_op; struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs; struct iov_iter iter; switch (opcode) { case IOCB_CMD_PREAD: case IOCB_CMD_PREADV: mode = FMODE_READ; rw = READ; rw_op = file->f_op->aio_read; iter_op = file->f_op->read_iter; goto rw_common; case IOCB_CMD_PWRITE: case IOCB_CMD_PWRITEV: mode = FMODE_WRITE; rw = WRITE; rw_op = file->f_op->aio_write; iter_op = file->f_op->write_iter; goto rw_common; rw_common: if (unlikely(!(file->f_mode & mode))) return -EBADF; if (!rw_op && !iter_op) return -EINVAL; if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV) ret = aio_setup_vectored_rw(req, rw, buf, &nr_segs, &len, &iovec, compat, &iter); else ret = aio_setup_single_vector(req, rw, buf, &nr_segs, len, iovec, &iter); if (!ret) ret = rw_verify_area(rw, file, &req->ki_pos, len); if (ret < 0) { if (iovec != inline_vecs) kfree(iovec); return ret; } len = ret; /* XXX: move/kill - rw_verify_area()? */ /* This matches the pread()/pwrite() logic */ if (req->ki_pos < 0) { ret = -EINVAL; break; } if (rw == WRITE) file_start_write(file); if (iter_op) { ret = iter_op(req, &iter); } else { ret = rw_op(req, iter.iov, iter.nr_segs, req->ki_pos); } if (rw == WRITE) file_end_write(file); break; case IOCB_CMD_FDSYNC: if (!file->f_op->aio_fsync) return -EINVAL; ret = file->f_op->aio_fsync(req, 1); break; case IOCB_CMD_FSYNC: if (!file->f_op->aio_fsync) return -EINVAL; ret = file->f_op->aio_fsync(req, 0); break; default: pr_debug("EINVAL: no operation provided\n"); return -EINVAL; } if (iovec != inline_vecs) kfree(iovec); if (ret != -EIOCBQUEUED) { /* * There's no easy way to restart the syscall since other AIO's * may be already running. Just fail this IO with EINTR. */ if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR || ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK)) ret = -EINTR; aio_complete(req, ret, 0); } return 0; }
170,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sparse_dump_region (struct tar_sparse_file *file, size_t i) { union block *blk; off_t bytes_left = file->stat_info->sparse_map[i].numbytes; if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset)) return false; while (bytes_left > 0) { size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left; size_t bytes_read; blk = find_next_block (); bytes_read = safe_read (file->fd, blk->buffer, bufsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left), bufsize); return false; } memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read); bytes_left -= bytes_read; { size_t count; size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size; union block *blk = find_next_block (); if (!blk) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) { write_error_details (file->stat_info->orig_file_name, count, wrbytes); return false; } } return true; } /* Interface functions */ enum dump_status sparse_dump_file (int fd, struct tar_stat_info *st) { return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) rc = sparse_scan_file (&file); if (rc && file.optab->dump_region) { tar_sparse_dump_header (&file); if (fd >= 0) { size_t i; mv_begin_write (file.stat_info->file_name, file.stat_info->stat.st_size, file.stat_info->archive_file_size - file.dumped_size); for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++) rc = tar_sparse_dump_region (&file, i); } } pad_archive (file.stat_info->archive_file_size - file.dumped_size); return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short; } Commit Message: CWE ID: CWE-835
sparse_dump_region (struct tar_sparse_file *file, size_t i) { union block *blk; off_t bytes_left = file->stat_info->sparse_map[i].numbytes; if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset)) return false; while (bytes_left > 0) { size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left; size_t bytes_read; blk = find_next_block (); bytes_read = safe_read (file->fd, blk->buffer, bufsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left), bufsize); return false; } else if (bytes_read == 0) { char buf[UINTMAX_STRSIZE_BOUND]; struct stat st; size_t n; if (fstat (file->fd, &st) == 0) n = file->stat_info->stat.st_size - st.st_size; else n = file->stat_info->stat.st_size - (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left); WARNOPT (WARN_FILE_SHRANK, (0, 0, ngettext ("%s: File shrank by %s byte; padding with zeros", "%s: File shrank by %s bytes; padding with zeros", n), quotearg_colon (file->stat_info->orig_file_name), STRINGIFY_BIGINT (n, buf))); if (! ignore_failed_read_option) set_exit_status (TAREXIT_DIFFERS); return false; } memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read); bytes_left -= bytes_read; { size_t count; size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size; union block *blk = find_next_block (); if (!blk) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) { write_error_details (file->stat_info->orig_file_name, count, wrbytes); return false; } } return true; } /* Interface functions */ enum dump_status sparse_dump_file (int fd, struct tar_stat_info *st) { return false; } set_next_block_after (blk); file->dumped_size += BLOCKSIZE; count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) rc = sparse_scan_file (&file); if (rc && file.optab->dump_region) { tar_sparse_dump_header (&file); if (fd >= 0) { size_t i; mv_begin_write (file.stat_info->file_name, file.stat_info->stat.st_size, file.stat_info->archive_file_size - file.dumped_size); for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++) rc = tar_sparse_dump_region (&file, i); } } pad_archive (file.stat_info->archive_file_size - file.dumped_size); return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short; }
164,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline ogg_uint32_t decode_packed_entry_number(codebook *book, oggpack_buffer *b){ ogg_uint32_t chase=0; int read=book->dec_maxlength; long lok = oggpack_look(b,read),i; while(lok<0 && read>1) lok = oggpack_look(b, --read); if(lok<0){ oggpack_adv(b,1); /* force eop */ return -1; } /* chase the tree with the bits we got */ switch (book->dec_method) { case 0: { /* book->dec_nodeb==1, book->dec_leafw==1 */ /* 8/8 - Used */ unsigned char *t=(unsigned char *)book->dec_table; for(i=0;i<read;i++){ chase=t[chase*2+((lok>>i)&1)]; if(chase&0x80UL)break; } chase&=0x7fUL; break; } case 1: { /* book->dec_nodeb==1, book->dec_leafw!=1 */ /* 8/16 - Used by infile2 */ unsigned char *t=(unsigned char *)book->dec_table; for(i=0;i<read;i++){ int bit=(lok>>i)&1; int next=t[chase+bit]; if(next&0x80){ chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)]; break; } chase=next; } chase&=~0x8000UL; break; } case 2: { /* book->dec_nodeb==2, book->dec_leafw==1 */ /* 16/16 - Used */ for(i=0;i<read;i++){ chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)]; if(chase&0x8000UL)break; } chase&=~0x8000UL; break; } case 3: { /* book->dec_nodeb==2, book->dec_leafw!=1 */ /* 16/32 - Used by infile2 */ ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table; for(i=0;i<read;i++){ int bit=(lok>>i)&1; int next=t[chase+bit]; if(next&0x8000){ chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)]; break; } chase=next; } chase&=~0x80000000UL; break; } case 4: { for(i=0;i<read;i++){ chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)]; if(chase&0x80000000UL)break; } chase&=~0x80000000UL; break; } } if(i<read){ oggpack_adv(b,i+1); return chase; } oggpack_adv(b,read+1); return(-1); } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static inline ogg_uint32_t decode_packed_entry_number(codebook *book, oggpack_buffer *b){ ogg_uint32_t chase=0; int read=book->dec_maxlength; long lok = oggpack_look(b,read),i; while(lok<0 && read>1) lok = oggpack_look(b, --read); if(lok<0){ oggpack_adv(b,1); /* force eop */ return -1; } /* chase the tree with the bits we got */ switch (book->dec_method) { case 0: { /* book->dec_nodeb==1, book->dec_leafw==1 */ /* 8/8 - Used */ unsigned char *t=(unsigned char *)book->dec_table; for(i=0;i<read;i++){ chase=t[chase*2+((lok>>i)&1)]; if(chase&0x80UL)break; } chase&=0x7fUL; break; } case 1: { /* book->dec_nodeb==1, book->dec_leafw!=1 */ /* 8/16 - Used by infile2 */ unsigned char *t=(unsigned char *)book->dec_table; for(i=0;i<read;i++){ int bit=(lok>>i)&1; int next=t[chase+bit]; if(next&0x80){ chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)]; break; } chase=next; } chase&=~0x8000UL; break; } case 2: { /* book->dec_nodeb==2, book->dec_leafw==1 */ /* 16/16 - Used */ for(i=0;i<read;i++){ chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)]; if(chase&0x8000UL)break; } chase&=~0x8000UL; break; } case 3: { /* book->dec_nodeb==2, book->dec_leafw!=1 */ /* 16/32 - Used by infile2 */ ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table; for(i=0;i<read;i++){ int bit=(lok>>i)&1; int next=t[chase+bit]; if(next&0x8000){ chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)]; break; } chase=next; } chase&=~0x80000000UL; break; } case 4: { for(i=0;i<read;i++){ chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)]; if(chase&0x80000000UL)break; } chase&=~0x80000000UL; break; } } if(i<read){ oggpack_adv(b,i+1); return chase; } oggpack_adv(b,read+1); return(-1); }
173,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IPV6DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) goto end; if (IPV6_GET_PLEN(reassembled) != 19) goto end; /* 40 bytes in we should find 8 bytes of A. */ for (i = 40; i < 40 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 48; i < 48 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 56; i < 56 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
IPV6DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) goto end; if (IPV6_GET_PLEN(reassembled) != 19) goto end; /* 40 bytes in we should find 8 bytes of A. */ for (i = 40; i < 40 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 48; i < 48 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 56; i < 56 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; }
168,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: chpass_principal3_2_svc(chpass3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->pass); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_chpass_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->pass); } else { log_unauth("kadm5_chpass_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_chpass_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
chpass_principal3_2_svc(chpass3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->pass); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_chpass_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->pass); } else { log_unauth("kadm5_chpass_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_chpass_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,504
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() { return screen_lock_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() {
170,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; if (new_content_rendering_timeout_ && new_content_rendering_timeout_->IsRunning()) { new_content_rendering_timeout_->Stop(); ClearDisplayedGraphics(); } SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#544518} CWE ID:
void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; ForceFirstFrameAfterNavigationTimeout(); SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); }
173,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int v9fs_device_realize_common(V9fsState *s, Error **errp) { V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); int i, len; struct stat stat; FsDriverEntry *fse; V9fsPath path; int rc = 1; /* initialize pdu allocator */ QLIST_INIT(&s->free_list); QLIST_INIT(&s->active_list); for (i = 0; i < (MAX_REQ - 1); i++) { QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next); v->pdus[i].s = s; v->pdus[i].idx = i; } v9fs_path_init(&path); fse = get_fsdev_fsentry(s->fsconf.fsdev_id); if (!fse) { /* We don't have a fsdev identified by fsdev_id */ error_setg(errp, "9pfs device couldn't find fsdev with the " "id = %s", s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL"); goto out; } if (!s->fsconf.tag) { /* we haven't specified a mount_tag */ error_setg(errp, "fsdev with id %s needs mount_tag arguments", s->fsconf.fsdev_id); goto out; } s->ctx.export_flags = fse->export_flags; s->ctx.fs_root = g_strdup(fse->path); s->ctx.exops.get_st_gen = NULL; len = strlen(s->fsconf.tag); if (len > MAX_TAG_LEN - 1) { error_setg(errp, "mount tag '%s' (%d bytes) is longer than " "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1); goto out; } s->tag = g_strdup(s->fsconf.tag); s->ctx.uid = -1; s->ops = fse->ops; s->fid_list = NULL; qemu_co_rwlock_init(&s->rename_lock); if (s->ops->init(&s->ctx) < 0) { error_setg(errp, "9pfs Failed to initialize fs-driver with id:%s" " and export path:%s", s->fsconf.fsdev_id, s->ctx.fs_root); goto out; } /* * Check details of export path, We need to use fs driver * call back to do that. Since we are in the init path, we don't * use co-routines here. */ if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) { error_setg(errp, "error in converting name to path %s", strerror(errno)); goto out; } if (s->ops->lstat(&s->ctx, &path, &stat)) { error_setg(errp, "share path %s does not exist", fse->path); goto out; } else if (!S_ISDIR(stat.st_mode)) { error_setg(errp, "share path %s is not a directory", fse->path); goto out; } v9fs_path_free(&path); rc = 0; out: if (rc) { g_free(s->ctx.fs_root); g_free(s->tag); v9fs_path_free(&path); } return rc; } Commit Message: CWE ID: CWE-400
int v9fs_device_realize_common(V9fsState *s, Error **errp) { V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); int i, len; struct stat stat; FsDriverEntry *fse; V9fsPath path; int rc = 1; /* initialize pdu allocator */ QLIST_INIT(&s->free_list); QLIST_INIT(&s->active_list); for (i = 0; i < (MAX_REQ - 1); i++) { QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next); v->pdus[i].s = s; v->pdus[i].idx = i; } v9fs_path_init(&path); fse = get_fsdev_fsentry(s->fsconf.fsdev_id); if (!fse) { /* We don't have a fsdev identified by fsdev_id */ error_setg(errp, "9pfs device couldn't find fsdev with the " "id = %s", s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL"); goto out; } if (!s->fsconf.tag) { /* we haven't specified a mount_tag */ error_setg(errp, "fsdev with id %s needs mount_tag arguments", s->fsconf.fsdev_id); goto out; } s->ctx.export_flags = fse->export_flags; s->ctx.fs_root = g_strdup(fse->path); s->ctx.exops.get_st_gen = NULL; len = strlen(s->fsconf.tag); if (len > MAX_TAG_LEN - 1) { error_setg(errp, "mount tag '%s' (%d bytes) is longer than " "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1); goto out; } s->tag = g_strdup(s->fsconf.tag); s->ctx.uid = -1; s->ops = fse->ops; s->fid_list = NULL; qemu_co_rwlock_init(&s->rename_lock); if (s->ops->init(&s->ctx) < 0) { error_setg(errp, "9pfs Failed to initialize fs-driver with id:%s" " and export path:%s", s->fsconf.fsdev_id, s->ctx.fs_root); goto out; } /* * Check details of export path, We need to use fs driver * call back to do that. Since we are in the init path, we don't * use co-routines here. */ if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) { error_setg(errp, "error in converting name to path %s", strerror(errno)); goto out; } if (s->ops->lstat(&s->ctx, &path, &stat)) { error_setg(errp, "share path %s does not exist", fse->path); goto out; } else if (!S_ISDIR(stat.st_mode)) { error_setg(errp, "share path %s is not a directory", fse->path); goto out; } v9fs_path_free(&path); rc = 0; out: if (rc) { g_free(s->tag); g_free(s->ctx.fs_root); v9fs_path_free(&path); } return rc; }
164,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool RendererPermissionsPolicyDelegate::IsRestrictedUrl( const GURL& document_url, std::string* error) { if (dispatcher_->IsExtensionActive(kWebStoreAppId)) { if (error) *error = errors::kCannotScriptGallery; return true; } if (SearchBouncer::GetInstance()->IsNewTabPage(document_url)) { if (error) *error = errors::kCannotScriptNtp; return true; } return false; } Commit Message: Extensions: Prevent content script injection in the New tab Page. r487664 disallowed content script injection in the New Tab Page. However, the check in RendererPermissionsPolicyDelegate::IsRestrictedUrl for the same, might not work due to the following reasons: - There might be a race between checking if the extension can inject the script and setting the new tab url in the renderer (SearchBouncer). - The New Tab page url in the SearchBouncer might be set incorrectly due to incorrect handling of multiple profiles by InstantService. Fix this by checking if the current renderer process is an Instant (NTP) renderer. This should work since the NTP renderer process should not be shared with other sites. BUG=844428, 662610 Change-Id: I45f6b27fb2680d3b8df6e1da223452ffee09b0d8 Reviewed-on: https://chromium-review.googlesource.com/1068607 Reviewed-by: Devlin <[email protected]> Commit-Queue: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#563031} CWE ID: CWE-285
bool RendererPermissionsPolicyDelegate::IsRestrictedUrl( const GURL& document_url, std::string* error) { if (dispatcher_->IsExtensionActive(kWebStoreAppId)) { if (error) *error = errors::kCannotScriptGallery; return true; } if (base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kInstantProcess)) { if (error) *error = errors::kCannotScriptNtp; return true; } return false; }
173,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return; newitem->next = c->next; newitem->prev = c->prev; if ( newitem->next ) newitem->next->prev = newitem; if ( c == array->child ) array->child = newitem; else newitem->prev->next = newitem; c->next = c->prev = 0; cJSON_Delete( c ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
167,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) { FrameLoadRequest frame_request(passed_request); FrameLoader::SetReferrerForFrameRequest(frame_request); FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(), frame_request.OriginDocument()); frame_request.GetResourceRequest().SetHasUserGesture( Frame::HasTransientUserActivation(this)); Client()->Navigate(frame_request.GetResourceRequest(), frame_request.ReplacesCurrentItem()); } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190
void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) { FrameLoadRequest frame_request(passed_request); FrameLoader::SetReferrerForFrameRequest(frame_request); FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(), frame_request.OriginDocument()); Client()->Navigate(frame_request.GetResourceRequest(), frame_request.ReplacesCurrentItem()); }
173,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); first_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); first_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); }
172,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_set_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type) { png_debug1(1, "in %s storage function", "IHDR"); if (png_ptr == NULL || info_ptr == NULL) return; info_ptr->width = width; info_ptr->height = height; info_ptr->bit_depth = (png_byte)bit_depth; info_ptr->color_type = (png_byte)color_type; info_ptr->compression_type = (png_byte)compression_type; info_ptr->filter_type = (png_byte)filter_type; info_ptr->interlace_type = (png_byte)interlace_type; png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height, info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type, info_ptr->compression_type, info_ptr->filter_type); if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); /* Check for potential overflow */ if (width > (PNG_UINT_32_MAX >> 3) /* 8-byte RGBA pixels */ - 64 /* bigrowbuf hack */ - 1 /* filter byte */ - 7*8 /* rounding of width to multiple of 8 pixels */ - 8) /* extra max_pixel_depth pad */ info_ptr->rowbytes = (png_size_t)0; else info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_set_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type) { png_debug1(1, "in %s storage function", "IHDR"); if (png_ptr == NULL || info_ptr == NULL) return; info_ptr->width = width; info_ptr->height = height; info_ptr->bit_depth = (png_byte)bit_depth; info_ptr->color_type = (png_byte)color_type; info_ptr->compression_type = (png_byte)compression_type; info_ptr->filter_type = (png_byte)filter_type; info_ptr->interlace_type = (png_byte)interlace_type; png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height, info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type, info_ptr->compression_type, info_ptr->filter_type); if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); /* Check for potential overflow */ if (width > (PNG_UINT_32_MAX >> 3) /* 8-byte RGBA pixels */ - 64 /* bigrowbuf hack */ - 1 /* filter byte */ - 7*8 /* rounding of width to multiple of 8 pixels */ - 8) /* extra max_pixel_depth pad */ { info_ptr->rowbytes = (png_size_t)0; png_error(png_ptr, "Image width is too large for this architecture"); } else info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); }
172,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[]) { struct mschm_decompressor *chmd; struct mschmd_header *chm; struct mschmd_file *file, **f; unsigned int numf, i; setbuf(stdout, NULL); setbuf(stderr, NULL); user_umask = umask(0); umask(user_umask); MSPACK_SYS_SELFTEST(i); if (i) return 0; if ((chmd = mspack_create_chm_decompressor(NULL))) { for (argv++; *argv; argv++) { printf("%s\n", *argv); if ((chm = chmd->open(chmd, *argv))) { /* build an ordered list of files for maximum extraction speed */ for (numf=0, file=chm->files; file; file = file->next) numf++; if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) { for (i=0, file=chm->files; file; file = file->next) f[i++] = file; qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc); for (i = 0; i < numf; i++) { char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0); printf("Extracting %s\n", outname); ensure_filepath(outname); if (chmd->extract(chmd, f[i], outname)) { printf("%s: extract error on \"%s\": %s\n", *argv, f[i]->filename, ERROR(chmd)); } free(outname); } free(f); } chmd->close(chmd, chm); } else { printf("%s: can't open -- %s\n", *argv, ERROR(chmd)); } } mspack_destroy_chm_decompressor(chmd); } return 0; } Commit Message: add anti "../" and leading slash protection to chmextract CWE ID: CWE-22
int main(int argc, char *argv[]) { struct mschm_decompressor *chmd; struct mschmd_header *chm; struct mschmd_file *file, **f; unsigned int numf, i; setbuf(stdout, NULL); setbuf(stderr, NULL); user_umask = umask(0); umask(user_umask); MSPACK_SYS_SELFTEST(i); if (i) return 0; if ((chmd = mspack_create_chm_decompressor(NULL))) { for (argv++; *argv; argv++) { printf("%s\n", *argv); if ((chm = chmd->open(chmd, *argv))) { /* build an ordered list of files for maximum extraction speed */ for (numf=0, file=chm->files; file; file = file->next) numf++; if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) { for (i=0, file=chm->files; file; file = file->next) f[i++] = file; qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc); for (i = 0; i < numf; i++) { char *outname = create_output_name(f[i]->filename); printf("Extracting %s\n", outname); ensure_filepath(outname); if (chmd->extract(chmd, f[i], outname)) { printf("%s: extract error on \"%s\": %s\n", *argv, f[i]->filename, ERROR(chmd)); } free(outname); } free(f); } chmd->close(chmd, chm); } else { printf("%s: can't open -- %s\n", *argv, ERROR(chmd)); } } mspack_destroy_chm_decompressor(chmd); } return 0; }
169,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FileReaderLoader::OnCalculatedSize(uint64_t total_size, uint64_t expected_content_size) { OnStartLoading(expected_content_size); if (expected_content_size == 0) { received_all_data_ = true; return; } if (IsSyncLoad()) { OnDataPipeReadable(MOJO_RESULT_OK); } else { handle_watcher_.Watch( consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE, WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable, WTF::Unretained(this))); } } Commit Message: Fix use-after-free in FileReaderLoader. Anything that calls out to client_ can cause FileReaderLoader to be destroyed, so make sure to check for that situation. Bug: 835639 Change-Id: I57533d41b7118c06da17abec28bbf301e1f50646 Reviewed-on: https://chromium-review.googlesource.com/1024450 Commit-Queue: Marijn Kruisselbrink <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Reviewed-by: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#552807} CWE ID: CWE-416
void FileReaderLoader::OnCalculatedSize(uint64_t total_size, uint64_t expected_content_size) { auto weak_this = weak_factory_.GetWeakPtr(); OnStartLoading(expected_content_size); // OnStartLoading calls out to our client, which could delete |this|, so bail // out if that happened. if (!weak_this) return; if (expected_content_size == 0) { received_all_data_ = true; return; } if (IsSyncLoad()) { OnDataPipeReadable(MOJO_RESULT_OK); } else { handle_watcher_.Watch( consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE, WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable, WTF::Unretained(this))); } }
173,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Cluster::Cluster( Segment* pSegment, long idx, long long element_start /* long long element_size */ ) : m_pSegment(pSegment), m_element_start(element_start), m_index(idx), m_pos(element_start), m_element_size(-1 /* element_size */ ), m_timecode(-1), m_entries(NULL), m_entries_size(0), m_entries_count(-1) //means "has not been parsed yet" { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Cluster::Cluster(
174,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RecordDailyContentLengthHistograms( int64 original_length, int64 received_length, int64 original_length_with_data_reduction_enabled, int64 received_length_with_data_reduction_enabled, int64 original_length_via_data_reduction_proxy, int64 received_length_via_data_reduction_proxy) { if (original_length <= 0 || received_length <= 0) return; UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength", original_length >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength", received_length >> 10); int percent = 0; if (original_length > received_length) { percent = (100 * (original_length - received_length)) / original_length; } UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent); if (original_length_with_data_reduction_enabled <= 0 || received_length_with_data_reduction_enabled <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", original_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled", received_length_with_data_reduction_enabled >> 10); int percent_data_reduction_proxy_enabled = 0; if (original_length_with_data_reduction_enabled > received_length_with_data_reduction_enabled) { percent_data_reduction_proxy_enabled = 100 * (original_length_with_data_reduction_enabled - received_length_with_data_reduction_enabled) / original_length_with_data_reduction_enabled; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", percent_data_reduction_proxy_enabled); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled", (100 * received_length_with_data_reduction_enabled) / received_length); if (original_length_via_data_reduction_proxy <= 0 || received_length_via_data_reduction_proxy <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_ViaDataReductionProxy", original_length_via_data_reduction_proxy >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_ViaDataReductionProxy", received_length_via_data_reduction_proxy >> 10); int percent_via_data_reduction_proxy = 0; if (original_length_via_data_reduction_proxy > received_length_via_data_reduction_proxy) { percent_via_data_reduction_proxy = 100 * (original_length_via_data_reduction_proxy - received_length_via_data_reduction_proxy) / original_length_via_data_reduction_proxy; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_ViaDataReductionProxy", percent_via_data_reduction_proxy); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_ViaDataReductionProxy", (100 * received_length_via_data_reduction_proxy) / received_length); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void RecordDailyContentLengthHistograms( int64 original_length, int64 received_length, int64 original_length_with_data_reduction_enabled, int64 received_length_with_data_reduction_enabled, int64 original_length_via_data_reduction_proxy, int64 received_length_via_data_reduction_proxy, int64 https_length_with_data_reduction_enabled, int64 short_bypass_length_with_data_reduction_enabled, int64 long_bypass_length_with_data_reduction_enabled, int64 unknown_length_with_data_reduction_enabled) { if (original_length <= 0 || received_length <= 0) return; UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength", original_length >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength", received_length >> 10); int percent = 0; if (original_length > received_length) { percent = (100 * (original_length - received_length)) / original_length; } UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent); if (original_length_with_data_reduction_enabled <= 0 || received_length_with_data_reduction_enabled <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", original_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled", received_length_with_data_reduction_enabled >> 10); int percent_data_reduction_proxy_enabled = 0; if (original_length_with_data_reduction_enabled > received_length_with_data_reduction_enabled) { percent_data_reduction_proxy_enabled = 100 * (original_length_with_data_reduction_enabled - received_length_with_data_reduction_enabled) / original_length_with_data_reduction_enabled; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", percent_data_reduction_proxy_enabled); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled", (100 * received_length_with_data_reduction_enabled) / received_length); if (https_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_Https", https_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_Https", (100 * https_length_with_data_reduction_enabled) / received_length); } if (short_bypass_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_ShortBypass", short_bypass_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_ShortBypass", ((100 * short_bypass_length_with_data_reduction_enabled) / received_length)); } if (long_bypass_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_LongBypass", long_bypass_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_LongBypass", ((100 * long_bypass_length_with_data_reduction_enabled) / received_length)); } if (unknown_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_Unknown", unknown_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_Unknown", ((100 * unknown_length_with_data_reduction_enabled) / received_length)); } if (original_length_via_data_reduction_proxy <= 0 || received_length_via_data_reduction_proxy <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_ViaDataReductionProxy", original_length_via_data_reduction_proxy >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_ViaDataReductionProxy", received_length_via_data_reduction_proxy >> 10); int percent_via_data_reduction_proxy = 0; if (original_length_via_data_reduction_proxy > received_length_via_data_reduction_proxy) { percent_via_data_reduction_proxy = 100 * (original_length_via_data_reduction_proxy - received_length_via_data_reduction_proxy) / original_length_via_data_reduction_proxy; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_ViaDataReductionProxy", percent_via_data_reduction_proxy); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_ViaDataReductionProxy", (100 * received_length_via_data_reduction_proxy) / received_length); }
171,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate) : delegate_(delegate), state_(INITIALIZED), waiting_(false), callback_(NULL), handshake_request_(new WebSocketHandshakeRequestHandler), handshake_response_(new WebSocketHandshakeResponseHandler), started_to_send_handshake_request_(false), handshake_request_sent_(0), response_cookies_save_index_(0), send_frame_handler_(new WebSocketFrameHandler), receive_frame_handler_(new WebSocketFrameHandler) { } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate) : delegate_(delegate), state_(INITIALIZED), waiting_(false), callback_(NULL), handshake_request_(new WebSocketHandshakeRequestHandler), handshake_response_(new WebSocketHandshakeResponseHandler), started_to_send_handshake_request_(false), handshake_request_sent_(0), response_cookies_save_index_(0), send_frame_handler_(new WebSocketFrameHandler), receive_frame_handler_(new WebSocketFrameHandler), ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) { }
170,308
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */ int i; if (heap->count+1 > heap->max_size) { /* we need to allocate more memory */ heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size))); heap->max_size *= 2; } heap->ctor(elem TSRMLS_CC); /* sifting up */ for(i = heap->count++; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) { heap->elements[i] = heap->elements[(i-1)/2]; } if (EG(exception)) { /* exception thrown during comparison */ } heap->elements[i] = elem; } /* }}} */ Commit Message: CWE ID:
static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */ int i; if (heap->count+1 > heap->max_size) { /* we need to allocate more memory */ heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size))); heap->max_size *= 2; } heap->ctor(elem TSRMLS_CC); /* sifting up */ for(i = heap->count; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) { heap->elements[i] = heap->elements[(i-1)/2]; } heap->count++; if (EG(exception)) { /* exception thrown during comparison */ } heap->elements[i] = elem; } /* }}} */
165,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return true; case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; } Commit Message: xkbcomp: Don't falsely promise from ExprResolveLhs Every user of ExprReturnLhs goes on to unconditionally dereference the field return, which can be NULL if xkb_intern_atom fails. Return false if this is the case, so we fail safely. testcase: splice geometry data into interp Signed-off-by: Daniel Stone <[email protected]> CWE ID: CWE-476
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; }
169,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return 0.0; uint32_t key, insamples; uint32_t repeat, outsamples; GPMF_stream find_stream; if (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0; key = GPMF_Key(gs); repeat = GPMF_Repeat(gs); if (rate == 0.0) rate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST); if (rate == 0.0) { *in = *out = 0.0; return 0.0; } GPMF_CopyState(gs, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) { outsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)); insamples = outsamples - repeat; *in = ((double)insamples / (double)rate); *out = ((double)outsamples / (double)rate); } else { *in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); *out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); } return rate; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out) GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_OFFSET, GPMF_CURRENT_LEVEL)) GPMF_FormattedData(&find_stream, &timo, 4, 0, 1); double first, last; first = -intercept / rate - timo; last = first + (double)totalsamples / rate; //printf("%c%c%c%c first sample at time %.3fms, last at %.3fms\n", PRINTF_4CC(fourcc), 1000.0*first, 1000.0*last); if (firstsampletime) *firstsampletime = first; if (lastsampletime) *lastsampletime = last; } } } } cleanup: if (payload) FreePayload(payload); payload = NULL; return rate; }
169,547
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void parse_input(h2o_http2_conn_t *conn) { size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection; int perform_early_exit = 0; if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection) perform_early_exit = 1; /* handle the input */ while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) { if (perform_early_exit == 1 && conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection) goto EarlyExit; /* process a frame */ const char *err_desc = NULL; ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc); if (ret == H2O_HTTP2_ERROR_INCOMPLETE) { break; } else if (ret < 0) { if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) { enqueue_goaway(conn, (int)ret, err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){}); } close_connection(conn); return; } /* advance to the next frame */ h2o_buffer_consume(&conn->sock->input, ret); } if (!h2o_socket_is_reading(conn->sock)) h2o_socket_read_start(conn->sock, on_read); return; EarlyExit: if (h2o_socket_is_reading(conn->sock)) h2o_socket_read_stop(conn->sock); } Commit Message: h2: use after free on premature connection close #920 lib/http2/connection.c:on_read() calls parse_input(), which might free `conn`. It does so in particular if the connection preface isn't the expected one in expect_preface(). `conn` is then used after the free in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`. We fix this by adding a return value to close_connection that returns a negative value if `conn` has been free'd and can't be used anymore. Credits for finding the bug to Tim Newsham. CWE ID:
static void parse_input(h2o_http2_conn_t *conn) static int parse_input(h2o_http2_conn_t *conn) { size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection; int perform_early_exit = 0; if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection) perform_early_exit = 1; /* handle the input */ while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) { if (perform_early_exit == 1 && conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection) goto EarlyExit; /* process a frame */ const char *err_desc = NULL; ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc); if (ret == H2O_HTTP2_ERROR_INCOMPLETE) { break; } else if (ret < 0) { if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) { enqueue_goaway(conn, (int)ret, err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){}); } return close_connection(conn); } /* advance to the next frame */ h2o_buffer_consume(&conn->sock->input, ret); } if (!h2o_socket_is_reading(conn->sock)) h2o_socket_read_start(conn->sock, on_read); return 0; EarlyExit: if (h2o_socket_is_reading(conn->sock)) h2o_socket_read_stop(conn->sock); return 0; }
167,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; min_shrink = 0; max_shrink = 0; desired_dpi = 0; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_addr = std::string(); preview_request_id = 0; is_first_request = false; print_scaling_option = WebKit::WebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; date = string16(); title = string16(); url = string16(); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; min_shrink = 0; max_shrink = 0; desired_dpi = 0; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = WebKit::WebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; date = string16(); title = string16(); url = string16(); }
170,846
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SystemLibrary* CrosLibrary::GetSystemLibrary() { return system_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
SystemLibrary* CrosLibrary::GetSystemLibrary() {
170,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ip6t_entry *e = (struct ip6t_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ip6t_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct ip6t_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->ipv6)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ip6t_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ip6t_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ip6t_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ip6t_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ip6t_entry *e = (struct ip6t_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ip6t_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ip6t_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ip6t_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ip6t_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ip6t_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; }
167,375
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int megasas_alloc_cmds(struct megasas_instance *instance) { int i; int j; u16 max_cmd; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * instance->cmd_list is an array of struct megasas_cmd pointers. * Allocate the dynamic array first and then allocate individual * commands. */ instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL); if (!instance->cmd_list) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n"); return -ENOMEM; } memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd); for (i = 0; i < max_cmd; i++) { instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd), GFP_KERNEL); if (!instance->cmd_list[i]) { for (j = 0; j < i; j++) kfree(instance->cmd_list[j]); kfree(instance->cmd_list); instance->cmd_list = NULL; return -ENOMEM; } } for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; memset(cmd, 0, sizeof(struct megasas_cmd)); cmd->index = i; cmd->scmd = NULL; cmd->instance = instance; list_add_tail(&cmd->list, &instance->cmd_pool); } /* * Create a frame pool and assign one frame to each cmd */ if (megasas_create_frame_pool(instance)) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n"); megasas_free_cmds(instance); } return 0; } Commit Message: scsi: megaraid_sas: return error when create DMA pool failed when create DMA pool for cmd frames failed, we should return -ENOMEM, instead of 0. In some case in: megasas_init_adapter_fusion() -->megasas_alloc_cmds() -->megasas_create_frame_pool create DMA pool failed, --> megasas_free_cmds() [1] -->megasas_alloc_cmds_fusion() failed, then goto fail_alloc_cmds. -->megasas_free_cmds() [2] we will call megasas_free_cmds twice, [1] will kfree cmd_list, [2] will use cmd_list.it will cause a problem: Unable to handle kernel NULL pointer dereference at virtual address 00000000 pgd = ffffffc000f70000 [00000000] *pgd=0000001fbf893003, *pud=0000001fbf893003, *pmd=0000001fbf894003, *pte=006000006d000707 Internal error: Oops: 96000005 [#1] SMP Modules linked in: CPU: 18 PID: 1 Comm: swapper/0 Not tainted task: ffffffdfb9290000 ti: ffffffdfb923c000 task.ti: ffffffdfb923c000 PC is at megasas_free_cmds+0x30/0x70 LR is at megasas_free_cmds+0x24/0x70 ... Call trace: [<ffffffc0005b779c>] megasas_free_cmds+0x30/0x70 [<ffffffc0005bca74>] megasas_init_adapter_fusion+0x2f4/0x4d8 [<ffffffc0005b926c>] megasas_init_fw+0x2dc/0x760 [<ffffffc0005b9ab0>] megasas_probe_one+0x3c0/0xcd8 [<ffffffc0004a5abc>] local_pci_probe+0x4c/0xb4 [<ffffffc0004a5c40>] pci_device_probe+0x11c/0x14c [<ffffffc00053a5e4>] driver_probe_device+0x1ec/0x430 [<ffffffc00053a92c>] __driver_attach+0xa8/0xb0 [<ffffffc000538178>] bus_for_each_dev+0x74/0xc8 [<ffffffc000539e88>] driver_attach+0x28/0x34 [<ffffffc000539a18>] bus_add_driver+0x16c/0x248 [<ffffffc00053b234>] driver_register+0x6c/0x138 [<ffffffc0004a5350>] __pci_register_driver+0x5c/0x6c [<ffffffc000ce3868>] megasas_init+0xc0/0x1a8 [<ffffffc000082a58>] do_one_initcall+0xe8/0x1ec [<ffffffc000ca7be8>] kernel_init_freeable+0x1c8/0x284 [<ffffffc0008d90b8>] kernel_init+0x1c/0xe4 Signed-off-by: Jason Yan <[email protected]> Acked-by: Sumit Saxena <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-476
int megasas_alloc_cmds(struct megasas_instance *instance) { int i; int j; u16 max_cmd; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * instance->cmd_list is an array of struct megasas_cmd pointers. * Allocate the dynamic array first and then allocate individual * commands. */ instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL); if (!instance->cmd_list) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n"); return -ENOMEM; } memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd); for (i = 0; i < max_cmd; i++) { instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd), GFP_KERNEL); if (!instance->cmd_list[i]) { for (j = 0; j < i; j++) kfree(instance->cmd_list[j]); kfree(instance->cmd_list); instance->cmd_list = NULL; return -ENOMEM; } } for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; memset(cmd, 0, sizeof(struct megasas_cmd)); cmd->index = i; cmd->scmd = NULL; cmd->instance = instance; list_add_tail(&cmd->list, &instance->cmd_pool); } /* * Create a frame pool and assign one frame to each cmd */ if (megasas_create_frame_pool(instance)) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n"); megasas_free_cmds(instance); return -ENOMEM; } return 0; }
169,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int treeRead(struct READER *reader, struct DATAOBJECT *data) { int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy, szy; char *input, *output; uint8_t node_type, node_level; uint16_t entries_used; uint32_t size_of_chunk; uint32_t filter_mask; uint64_t address_of_left_sibling, address_of_right_sibling, start[4], child_pointer, key, store; char buf[4]; UNUSED(node_level); UNUSED(address_of_right_sibling); UNUSED(address_of_left_sibling); UNUSED(key); if (data->ds.dimensionality > 3) { log("TREE dimensions > 3"); return MYSOFA_INVALID_FORMAT; } /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) { log("cannot read signature of TREE\n"); return MYSOFA_INVALID_FORMAT; } log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); node_type = (uint8_t)fgetc(reader->fhd); node_level = (uint8_t)fgetc(reader->fhd); entries_used = (uint16_t)readValue(reader, 2); if(entries_used>0x1000) return MYSOFA_UNSUPPORTED_FORMAT; address_of_left_sibling = readValue(reader, reader->superblock.size_of_offsets); address_of_right_sibling = readValue(reader, reader->superblock.size_of_offsets); elements = 1; for (j = 0; j < data->ds.dimensionality; j++) elements *= data->datalayout_chunk[j]; dy = data->datalayout_chunk[1]; dz = data->datalayout_chunk[2]; sx = data->ds.dimension_size[0]; sy = data->ds.dimension_size[1]; sz = data->ds.dimension_size[2]; dzy = dz * dy; szy = sz * sy; size = data->datalayout_chunk[data->ds.dimensionality]; log("elements %d size %d\n",elements,size); if (!(output = malloc(elements * size))) { return MYSOFA_NO_MEMORY; } for (e = 0; e < entries_used * 2; e++) { if (node_type == 0) { key = readValue(reader, reader->superblock.size_of_lengths); } else { size_of_chunk = (uint32_t)readValue(reader, 4); filter_mask = (uint32_t)readValue(reader, 4); if (filter_mask) { log("TREE all filters must be enabled\n"); free(output); return MYSOFA_INVALID_FORMAT; } for (j = 0; j < data->ds.dimensionality; j++) { start[j] = readValue(reader, 8); log("start %d %lu\n",j,start[j]); } if (readValue(reader, 8)) { break; } child_pointer = readValue(reader, reader->superblock.size_of_offsets); log(" data at %lX len %u\n", child_pointer, size_of_chunk); /* read data */ store = ftell(reader->fhd); if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) { free(output); return errno; } if (!(input = malloc(size_of_chunk))) { free(output); return MYSOFA_NO_MEMORY; } if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) { free(output); free(input); return MYSOFA_INVALID_FORMAT; } olen = elements * size; err = gunzip(size_of_chunk, input, &olen, output); free(input); log(" gunzip %d %d %d\n",err, olen, elements*size); if (err || olen != elements * size) { free(output); return MYSOFA_INVALID_FORMAT; } switch (data->ds.dimensionality) { case 1: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements + start[0]; if (x < sx) { j = x * size + b; ((char*)data->data)[j] = output[i]; } } break; case 2: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; y = x % dy + start[1]; x = x / dy + start[0]; if (y < sy && x < sx) { j = ((x * sy + y) * size) + b; ((char*)data->data)[j] = output[i]; } } break; case 3: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; z = x % dz + start[2]; y = (x / dz) % dy + start[1]; x = (x / dzy) + start[0]; if (z < sz && y < sy && x < sx) { j = (x * szy + y * sz + z) * size + b; ((char*)data->data)[j] = output[i]; } } break; default: log("invalid dim\n"); return MYSOFA_INTERNAL_ERROR; } if(fseek(reader->fhd, store, SEEK_SET)<0) { free(output); return errno; } } } free(output); if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */ return errno; return MYSOFA_OK; } Commit Message: Fixed security issue 1 CWE ID: CWE-20
int treeRead(struct READER *reader, struct DATAOBJECT *data) { int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy, szy; char *input, *output; uint8_t node_type, node_level; uint16_t entries_used; uint32_t size_of_chunk; uint32_t filter_mask; uint64_t address_of_left_sibling, address_of_right_sibling, start[4], child_pointer, key, store; char buf[4]; UNUSED(node_level); UNUSED(address_of_right_sibling); UNUSED(address_of_left_sibling); UNUSED(key); if (data->ds.dimensionality > 3) { log("TREE dimensions > 3"); return MYSOFA_INVALID_FORMAT; } /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) { log("cannot read signature of TREE\n"); return MYSOFA_INVALID_FORMAT; } log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); node_type = (uint8_t)fgetc(reader->fhd); node_level = (uint8_t)fgetc(reader->fhd); entries_used = (uint16_t)readValue(reader, 2); if(entries_used>0x1000) return MYSOFA_UNSUPPORTED_FORMAT; address_of_left_sibling = readValue(reader, reader->superblock.size_of_offsets); address_of_right_sibling = readValue(reader, reader->superblock.size_of_offsets); elements = 1; for (j = 0; j < data->ds.dimensionality; j++) elements *= data->datalayout_chunk[j]; dy = data->datalayout_chunk[1]; dz = data->datalayout_chunk[2]; sx = data->ds.dimension_size[0]; sy = data->ds.dimension_size[1]; sz = data->ds.dimension_size[2]; dzy = dz * dy; szy = sz * sy; size = data->datalayout_chunk[data->ds.dimensionality]; log("elements %d size %d\n",elements,size); if (!(output = malloc(elements * size))) { return MYSOFA_NO_MEMORY; } for (e = 0; e < entries_used * 2; e++) { if (node_type == 0) { key = readValue(reader, reader->superblock.size_of_lengths); } else { size_of_chunk = (uint32_t)readValue(reader, 4); filter_mask = (uint32_t)readValue(reader, 4); if (filter_mask) { log("TREE all filters must be enabled\n"); free(output); return MYSOFA_INVALID_FORMAT; } for (j = 0; j < data->ds.dimensionality; j++) { start[j] = readValue(reader, 8); log("start %d %lu\n",j,start[j]); } if (readValue(reader, 8)) { break; } child_pointer = readValue(reader, reader->superblock.size_of_offsets); log(" data at %lX len %u\n", child_pointer, size_of_chunk); /* read data */ store = ftell(reader->fhd); if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) { free(output); return errno; } if (!(input = malloc(size_of_chunk))) { free(output); return MYSOFA_NO_MEMORY; } if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) { free(output); free(input); return MYSOFA_INVALID_FORMAT; } olen = elements * size; err = gunzip(size_of_chunk, input, &olen, output); free(input); log(" gunzip %d %d %d\n",err, olen, elements*size); if (err || olen != elements * size) { free(output); return MYSOFA_INVALID_FORMAT; } switch (data->ds.dimensionality) { case 1: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements + start[0]; j = x * size + b; if (j>=0 && j < elements * size) { ((char*)data->data)[j] = output[i]; } } break; case 2: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; y = x % dy + start[1]; x = x / dy + start[0]; j = ((x * sy + y) * size) + b; if (j>=0 && j < elements * size) { ((char*)data->data)[j] = output[i]; } } break; case 3: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; z = x % dz + start[2]; y = (x / dz) % dy + start[1]; x = (x / dzy) + start[0]; j = (x * szy + y * sz + z) * size + b; if (j>=0 && j < elements * size) { ((char*)data->data)[j] = output[i]; } } break; default: log("invalid dim\n"); return MYSOFA_INTERNAL_ERROR; } if(fseek(reader->fhd, store, SEEK_SET)<0) { free(output); return errno; } } } free(output); if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */ return errno; return MYSOFA_OK; }
169,713
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int MockNetworkTransaction::RestartWithAuth( const AuthCredentials& credentials, const CompletionCallback& callback) { if (!IsReadyToRestartForAuth()) return ERR_FAILED; HttpRequestInfo auth_request_info = *request_; auth_request_info.extra_headers.AddHeaderFromString("Authorization: Bar"); return StartInternal(&auth_request_info, callback, BoundNetLog()); } Commit Message: Replace fixed string uses of AddHeaderFromString Uses of AddHeaderFromString() with a static string may as well be replaced with SetHeader(). Do so. BUG=None Review-Url: https://codereview.chromium.org/2236933005 Cr-Commit-Position: refs/heads/master@{#418161} CWE ID: CWE-119
int MockNetworkTransaction::RestartWithAuth( const AuthCredentials& credentials, const CompletionCallback& callback) { if (!IsReadyToRestartForAuth()) return ERR_FAILED; HttpRequestInfo auth_request_info = *request_; auth_request_info.extra_headers.SetHeader("Authorization", "Bar"); return StartInternal(&auth_request_info, callback, BoundNetLog()); }
171,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void Rp_test(js_State *J) { js_Regexp *re; const char *text; int opts; Resub m; re = js_toregexp(J, 0); text = js_tostring(J, 1); opts = 0; if (re->flags & JS_REGEXP_G) { if (re->last > strlen(text)) { re->last = 0; js_pushboolean(J, 0); return; } if (re->last > 0) { text += re->last; opts |= REG_NOTBOL; } } if (!js_regexec(re->prog, text, &m, opts)) { if (re->flags & JS_REGEXP_G) re->last = re->last + (m.sub[0].ep - text); js_pushboolean(J, 1); return; } if (re->flags & JS_REGEXP_G) re->last = 0; js_pushboolean(J, 0); } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400
static void Rp_test(js_State *J) { js_Regexp *re; const char *text; int result; int opts; Resub m; re = js_toregexp(J, 0); text = js_tostring(J, 1); opts = 0; if (re->flags & JS_REGEXP_G) { if (re->last > strlen(text)) { re->last = 0; js_pushboolean(J, 0); return; } if (re->last > 0) { text += re->last; opts |= REG_NOTBOL; } } result = js_regexec(re->prog, text, &m, opts); if (result < 0) js_error(J, "regexec failed"); if (result == 0) { if (re->flags & JS_REGEXP_G) re->last = re->last + (m.sub[0].ep - text); js_pushboolean(J, 1); return; } if (re->flags & JS_REGEXP_G) re->last = 0; js_pushboolean(J, 0); }
169,696
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *pool_strdup(const char *s) { char *r = pool_alloc(strlen(s) + 1); strcpy(r, s); return r; } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static char *pool_strdup(const char *s) { size_t len = strlen(s) + 1; char *r = pool_alloc(len); memcpy(r, s, len); return r; }
167,428
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _gcry_ecc_eddsa_sign (gcry_mpi_t input, ECC_secret_key *skey, gcry_mpi_t r_r, gcry_mpi_t s, int hashalgo, gcry_mpi_t pk) { int rc; mpi_ec_t ctx = NULL; int b; unsigned int tmp; unsigned char *digest = NULL; gcry_buffer_t hvec[3]; const void *mbuf; size_t mlen; unsigned char *rawmpi = NULL; unsigned int rawmpilen; unsigned char *encpk = NULL; /* Encoded public key. */ unsigned int encpklen; mpi_point_struct I; /* Intermediate value. */ mpi_point_struct Q; /* Public key. */ gcry_mpi_t a, x, y, r; memset (hvec, 0, sizeof hvec); if (!mpi_is_opaque (input)) return GPG_ERR_INV_DATA; /* Initialize some helpers. */ point_init (&I); point_init (&Q); a = mpi_snew (0); x = mpi_new (0); y = mpi_new (0); r = mpi_new (0); ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0, skey->E.p, skey->E.a, skey->E.b); b = (ctx->nbits+7)/8; if (b != 256/8) { rc = GPG_ERR_INTERNAL; /* We only support 256 bit. */ goto leave; } rc = _gcry_ecc_eddsa_compute_h_d (&digest, skey->d, ctx); if (rc) goto leave; _gcry_mpi_set_buffer (a, digest, 32, 0); /* Compute the public key if it has not been supplied as optional parameter. */ if (pk) { rc = _gcry_ecc_eddsa_decodepoint (pk, ctx, &Q, &encpk, &encpklen); if (rc) goto leave; if (DBG_CIPHER) log_printhex ("* e_pk", encpk, encpklen); if (!_gcry_mpi_ec_curve_point (&Q, ctx)) { rc = GPG_ERR_BROKEN_PUBKEY; goto leave; } } else { _gcry_mpi_ec_mul_point (&Q, a, &skey->E.G, ctx); rc = _gcry_ecc_eddsa_encodepoint (&Q, ctx, x, y, 0, &encpk, &encpklen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_pk", encpk, encpklen); } /* Compute R. */ mbuf = mpi_get_opaque (input, &tmp); mlen = (tmp +7)/8; if (DBG_CIPHER) log_printhex (" m", mbuf, mlen); hvec[0].data = digest; hvec[0].off = 32; hvec[0].len = 32; hvec[1].data = (char*)mbuf; hvec[1].len = mlen; rc = _gcry_md_hash_buffers (hashalgo, 0, digest, hvec, 2); if (rc) goto leave; reverse_buffer (digest, 64); if (DBG_CIPHER) log_printhex (" r", digest, 64); _gcry_mpi_set_buffer (r, digest, 64, 0); _gcry_mpi_ec_mul_point (&I, r, &skey->E.G, ctx); if (DBG_CIPHER) log_printpnt (" r", &I, ctx); /* Convert R into affine coordinates and apply encoding. */ rc = _gcry_ecc_eddsa_encodepoint (&I, ctx, x, y, 0, &rawmpi, &rawmpilen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_r", rawmpi, rawmpilen); /* S = r + a * H(encodepoint(R) + encodepoint(pk) + m) mod n */ hvec[0].data = rawmpi; /* (this is R) */ hvec[0].off = 0; hvec[0].len = rawmpilen; hvec[1].data = encpk; hvec[1].off = 0; hvec[1].len = encpklen; hvec[2].data = (char*)mbuf; hvec[2].off = 0; hvec[2].len = mlen; rc = _gcry_md_hash_buffers (hashalgo, 0, digest, hvec, 3); if (rc) goto leave; /* No more need for RAWMPI thus we now transfer it to R_R. */ mpi_set_opaque (r_r, rawmpi, rawmpilen*8); rawmpi = NULL; reverse_buffer (digest, 64); if (DBG_CIPHER) log_printhex (" H(R+)", digest, 64); _gcry_mpi_set_buffer (s, digest, 64, 0); mpi_mulm (s, s, a, skey->E.n); mpi_addm (s, s, r, skey->E.n); rc = eddsa_encodempi (s, b, &rawmpi, &rawmpilen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_s", rawmpi, rawmpilen); mpi_set_opaque (s, rawmpi, rawmpilen*8); rawmpi = NULL; rc = 0; leave: _gcry_mpi_release (a); _gcry_mpi_release (x); _gcry_mpi_release (y); _gcry_mpi_release (r); xfree (digest); _gcry_mpi_ec_free (ctx); point_free (&I); point_free (&Q); xfree (encpk); xfree (rawmpi); return rc; } Commit Message: CWE ID: CWE-200
_gcry_ecc_eddsa_sign (gcry_mpi_t input, ECC_secret_key *skey, gcry_mpi_t r_r, gcry_mpi_t s, int hashalgo, gcry_mpi_t pk) { int rc; mpi_ec_t ctx = NULL; int b; unsigned int tmp; unsigned char *digest = NULL; gcry_buffer_t hvec[3]; const void *mbuf; size_t mlen; unsigned char *rawmpi = NULL; unsigned int rawmpilen; unsigned char *encpk = NULL; /* Encoded public key. */ unsigned int encpklen; mpi_point_struct I; /* Intermediate value. */ mpi_point_struct Q; /* Public key. */ gcry_mpi_t a, x, y, r; memset (hvec, 0, sizeof hvec); if (!mpi_is_opaque (input)) return GPG_ERR_INV_DATA; /* Initialize some helpers. */ point_init (&I); point_init (&Q); a = mpi_snew (0); x = mpi_new (0); y = mpi_new (0); r = mpi_snew (0); ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0, skey->E.p, skey->E.a, skey->E.b); b = (ctx->nbits+7)/8; if (b != 256/8) { rc = GPG_ERR_INTERNAL; /* We only support 256 bit. */ goto leave; } rc = _gcry_ecc_eddsa_compute_h_d (&digest, skey->d, ctx); if (rc) goto leave; _gcry_mpi_set_buffer (a, digest, 32, 0); /* Compute the public key if it has not been supplied as optional parameter. */ if (pk) { rc = _gcry_ecc_eddsa_decodepoint (pk, ctx, &Q, &encpk, &encpklen); if (rc) goto leave; if (DBG_CIPHER) log_printhex ("* e_pk", encpk, encpklen); if (!_gcry_mpi_ec_curve_point (&Q, ctx)) { rc = GPG_ERR_BROKEN_PUBKEY; goto leave; } } else { _gcry_mpi_ec_mul_point (&Q, a, &skey->E.G, ctx); rc = _gcry_ecc_eddsa_encodepoint (&Q, ctx, x, y, 0, &encpk, &encpklen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_pk", encpk, encpklen); } /* Compute R. */ mbuf = mpi_get_opaque (input, &tmp); mlen = (tmp +7)/8; if (DBG_CIPHER) log_printhex (" m", mbuf, mlen); hvec[0].data = digest; hvec[0].off = 32; hvec[0].len = 32; hvec[1].data = (char*)mbuf; hvec[1].len = mlen; rc = _gcry_md_hash_buffers (hashalgo, 0, digest, hvec, 2); if (rc) goto leave; reverse_buffer (digest, 64); if (DBG_CIPHER) log_printhex (" r", digest, 64); _gcry_mpi_set_buffer (r, digest, 64, 0); _gcry_mpi_ec_mul_point (&I, r, &skey->E.G, ctx); if (DBG_CIPHER) log_printpnt (" r", &I, ctx); /* Convert R into affine coordinates and apply encoding. */ rc = _gcry_ecc_eddsa_encodepoint (&I, ctx, x, y, 0, &rawmpi, &rawmpilen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_r", rawmpi, rawmpilen); /* S = r + a * H(encodepoint(R) + encodepoint(pk) + m) mod n */ hvec[0].data = rawmpi; /* (this is R) */ hvec[0].off = 0; hvec[0].len = rawmpilen; hvec[1].data = encpk; hvec[1].off = 0; hvec[1].len = encpklen; hvec[2].data = (char*)mbuf; hvec[2].off = 0; hvec[2].len = mlen; rc = _gcry_md_hash_buffers (hashalgo, 0, digest, hvec, 3); if (rc) goto leave; /* No more need for RAWMPI thus we now transfer it to R_R. */ mpi_set_opaque (r_r, rawmpi, rawmpilen*8); rawmpi = NULL; reverse_buffer (digest, 64); if (DBG_CIPHER) log_printhex (" H(R+)", digest, 64); _gcry_mpi_set_buffer (s, digest, 64, 0); mpi_mulm (s, s, a, skey->E.n); mpi_addm (s, s, r, skey->E.n); rc = eddsa_encodempi (s, b, &rawmpi, &rawmpilen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_s", rawmpi, rawmpilen); mpi_set_opaque (s, rawmpi, rawmpilen*8); rawmpi = NULL; rc = 0; leave: _gcry_mpi_release (a); _gcry_mpi_release (x); _gcry_mpi_release (y); _gcry_mpi_release (r); xfree (digest); _gcry_mpi_ec_free (ctx); point_free (&I); point_free (&Q); xfree (encpk); xfree (rawmpi); return rc; }
164,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; current_input_method_changed_(language_library_, current_input_method); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); VLOG(1) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; FOR_EACH_OBSERVER(Observer, observers_, OnCurrentInputMethodChanged(current_input_method)); }
170,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); const struct uac_to_guid { uint32_t uac; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } }; Commit Message: CWE ID: CWE-264
static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); struct ldb_context *ldb = ldb_module_get_ctx(ac->module); const struct uac_to_guid { uint32_t uac; uint32_t priv_to_change_from; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; bool admin_required; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_WORKSTATION_TRUST_ACCOUNT, .priv_to_change_from = UF_NORMAL_ACCOUNT, .error_string = "Swapping UF_NORMAL_ACCOUNT to UF_WORKSTATION_TRUST_ACCOUNT requires the user to be a member of the domain admins group" }, { .uac = UF_NORMAL_ACCOUNT, .priv_to_change_from = UF_WORKSTATION_TRUST_ACCOUNT, .error_string = "Swapping UF_WORKSTATION_TRUST_ACCOUNT to UF_NORMAL_ACCOUNT requires the user to be a member of the domain admins group" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } };
164,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). CWE ID: CWE-119
void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } }
168,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r, len; switch (node->type) { case BAG_MEMORY: r = compile_bag_memory_node(node, reg, env); break; case BAG_OPTION: r = compile_option_node(node, reg, env); break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; len = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (len < 0) return len; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; r = add_op(reg, OP_POP_OUT); if (r != 0) return r; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); } else { r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); } break; case BAG_IF_ELSE: { int cond_len, then_len, jump_len; Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; cond_len = compile_length_tree(cond, reg); if (cond_len < 0) return cond_len; if (IS_NOT_NULL(Then)) { then_len = compile_length_tree(Then, reg); if (then_len < 0) return then_len; } else then_len = 0; jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + jump_len; r = compile_tree(cond, reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Then)) { r = compile_tree(Then, reg, env); if (r != 0) return r; } if (IS_NOT_NULL(Else)) { int else_len = compile_length_tree(Else, reg); r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = else_len + SIZE_INC_OP; r = compile_tree(Else, reg, env); } } break; } return r; } Commit Message: Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode. CWE ID: CWE-476
compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r, len; switch (node->type) { case BAG_MEMORY: r = compile_bag_memory_node(node, reg, env); break; case BAG_OPTION: r = compile_option_node(node, reg, env); break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; len = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (len < 0) return len; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; r = add_op(reg, OP_POP_OUT); if (r != 0) return r; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); } else { r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); } break; case BAG_IF_ELSE: { int cond_len, then_len, else_len, jump_len; Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; cond_len = compile_length_tree(cond, reg); if (cond_len < 0) return cond_len; if (IS_NOT_NULL(Then)) { then_len = compile_length_tree(Then, reg); if (then_len < 0) return then_len; } else then_len = 0; jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + jump_len; r = compile_tree(cond, reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Then)) { r = compile_tree(Then, reg, env); if (r != 0) return r; } if (IS_NOT_NULL(Else)) { else_len = compile_length_tree(Else, reg); if (else_len < 0) return else_len; } else else_len = 0; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Else)) { r = compile_tree(Else, reg, env); } } break; } return r; }
169,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_rpcsec_auth(struct svc_req *rqstp) { gss_ctx_id_t ctx; krb5_context kctx; OM_uint32 maj_stat, min_stat; gss_name_t name; krb5_principal princ; int ret, success; krb5_data *c1, *c2, *realm; gss_buffer_desc gss_str; kadm5_server_handle_t handle; size_t slen; char *sdots; success = 0; handle = (kadm5_server_handle_t)global_server_handle; if (rqstp->rq_cred.oa_flavor != RPCSEC_GSS) return 0; ctx = rqstp->rq_svccred; maj_stat = gss_inquire_context(&min_stat, ctx, NULL, &name, NULL, NULL, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) { krb5_klog_syslog(LOG_ERR, _("check_rpcsec_auth: failed " "inquire_context, stat=%u"), maj_stat); log_badauth(maj_stat, min_stat, rqstp->rq_xprt, NULL); goto fail_name; } kctx = handle->context; ret = gss_to_krb5_name_1(rqstp, kctx, name, &princ, &gss_str); if (ret == 0) goto fail_name; slen = gss_str.length; trunc_name(&slen, &sdots); /* * Since we accept with GSS_C_NO_NAME, the client can authenticate * against the entire kdb. Therefore, ensure that the service * name is something reasonable. */ if (krb5_princ_size(kctx, princ) != 2) goto fail_princ; c1 = krb5_princ_component(kctx, princ, 0); c2 = krb5_princ_component(kctx, princ, 1); realm = krb5_princ_realm(kctx, princ); if (strncmp(handle->params.realm, realm->data, realm->length) == 0 && strncmp("kadmin", c1->data, c1->length) == 0) { if (strncmp("history", c2->data, c2->length) == 0) goto fail_princ; else success = 1; } fail_princ: if (!success) { krb5_klog_syslog(LOG_ERR, _("bad service principal %.*s%s"), (int) slen, (char *) gss_str.value, sdots); } gss_release_buffer(&min_stat, &gss_str); krb5_free_principal(kctx, princ); fail_name: gss_release_name(&min_stat, &name); return success; } Commit Message: Fix kadmind server validation [CVE-2014-9422] [MITKRB5-SA-2015-001] In kadmind's check_rpcsec_auth(), use data_eq_string() instead of strncmp() to check components of the server principal, so that we don't erroneously match left substrings of "kadmin", "history", or the realm. ticket: 8057 (new) target_version: 1.13.1 tags: pullup CWE ID: CWE-284
check_rpcsec_auth(struct svc_req *rqstp) { gss_ctx_id_t ctx; krb5_context kctx; OM_uint32 maj_stat, min_stat; gss_name_t name; krb5_principal princ; int ret, success; krb5_data *c1, *c2, *realm; gss_buffer_desc gss_str; kadm5_server_handle_t handle; size_t slen; char *sdots; success = 0; handle = (kadm5_server_handle_t)global_server_handle; if (rqstp->rq_cred.oa_flavor != RPCSEC_GSS) return 0; ctx = rqstp->rq_svccred; maj_stat = gss_inquire_context(&min_stat, ctx, NULL, &name, NULL, NULL, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) { krb5_klog_syslog(LOG_ERR, _("check_rpcsec_auth: failed " "inquire_context, stat=%u"), maj_stat); log_badauth(maj_stat, min_stat, rqstp->rq_xprt, NULL); goto fail_name; } kctx = handle->context; ret = gss_to_krb5_name_1(rqstp, kctx, name, &princ, &gss_str); if (ret == 0) goto fail_name; slen = gss_str.length; trunc_name(&slen, &sdots); /* * Since we accept with GSS_C_NO_NAME, the client can authenticate * against the entire kdb. Therefore, ensure that the service * name is something reasonable. */ if (krb5_princ_size(kctx, princ) != 2) goto fail_princ; c1 = krb5_princ_component(kctx, princ, 0); c2 = krb5_princ_component(kctx, princ, 1); realm = krb5_princ_realm(kctx, princ); success = data_eq_string(*realm, handle->params.realm) && data_eq_string(*c1, "kadmin") && !data_eq_string(*c2, "history"); fail_princ: if (!success) { krb5_klog_syslog(LOG_ERR, _("bad service principal %.*s%s"), (int) slen, (char *) gss_str.value, sdots); } gss_release_buffer(&min_stat, &gss_str); krb5_free_principal(kctx, princ); fail_name: gss_release_name(&min_stat, &name); return success; }
166,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void toggle_fpga_eeprom_bus(bool cpu_own) { qrio_gpio_direction_output(GPIO_A, PROM_SEL_L, !cpu_own); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
static void toggle_fpga_eeprom_bus(bool cpu_own) { qrio_gpio_direction_output(QRIO_GPIO_A, PROM_SEL_L, !cpu_own); }
169,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SeekHead::SeekHead( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_entries(0), m_entry_count(0), m_void_elements(0), m_void_element_count(0) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
SeekHead::SeekHead( // Outermost (level 0) segment object has been constructed, // and pos designates start of payload. We need to find the // inner (level 1) elements. const long long header_status = ParseHeaders(); if (header_status < 0) // error return static_cast<long>(header_status); if (header_status > 0) // underflow return E_BUFFER_NOT_FULL; assert(m_pInfo); assert(m_pTracks); for (;;) { const int status = LoadCluster(); if (status < 0) // error return status; if (status >= 1) // no more clusters return 0; } }
174,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void show_object(struct object *obj, struct strbuf *path, const char *last, void *data) { char *name = path_name(path, last); add_preferred_base_object(name); add_object_entry(obj->oid.hash, obj->type, name, 0); obj->flags |= OBJECT_ADDED; /* * We will have generated the hash from the name, * but not saved a pointer to it - we can free it */ free((char *)name); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void show_object(struct object *obj, static void show_object(struct object *obj, const char *name, void *data) { add_preferred_base_object(name); add_object_entry(obj->oid.hash, obj->type, name, 0); obj->flags |= OBJECT_ADDED; }
167,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void l2tp_eth_dev_setup(struct net_device *dev) { ether_setup(dev); dev->netdev_ops = &l2tp_eth_netdev_ops; dev->destructor = free_netdev; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static void l2tp_eth_dev_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; dev->netdev_ops = &l2tp_eth_netdev_ops; dev->destructor = free_netdev; }
165,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::string16 TranslateInfoBarDelegate::GetLanguageDisplayableName( const std::string& language_code) { return l10n_util::GetDisplayNameForLocale( language_code, g_browser_process->GetApplicationLocale(), true); } Commit Message: Remove dependency of TranslateInfobarDelegate on profile This CL uses TranslateTabHelper instead of Profile and also cleans up some unused code and irrelevant dependencies. BUG=371845 Review URL: https://codereview.chromium.org/286973003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@270758 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
base::string16 TranslateInfoBarDelegate::GetLanguageDisplayableName(
171,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, static_cast<OMX_U8 *>(params->pointer())); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } // metadata buffers are not connected cross process // use a backup buffer instead of the actual buffer BufferMeta *buffer_meta; bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid; OMX_U8 *data = static_cast<OMX_U8 *>(params->pointer()); // allocate backup buffer if (useBackup) { data = new (std::nothrow) OMX_U8[allottedSize]; if (data == NULL) { return NO_MEMORY; } memset(data, 0, allottedSize); // if we are not connecting the buffers, the sizes must match if (allottedSize != params->size()) { CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data)); delete[] data; return BAD_VALUE; } buffer_meta = new BufferMeta( params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data); } else { buffer_meta = new BufferMeta( params, portIndex, false /* copyFromOmx */, false /* copyToOmx */, NULL); } OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, data); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, data)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; }
174,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void CopyPixels(PixelPacket *destination, const PixelPacket *source,const MagickSizeType number_pixels) { #if !defined(MAGICKCORE_OPENMP_SUPPORT) || (MAGICKCORE_QUANTUM_DEPTH <= 8) (void) memcpy(destination,source,(size_t) number_pixels*sizeof(*source)); #else { register MagickOffsetType i; if ((number_pixels*sizeof(*source)) < MagickMaxBufferExtent) { (void) memcpy(destination,source,(size_t) number_pixels* sizeof(*source)); return; } #pragma omp parallel for for (i=0; i < (MagickOffsetType) number_pixels; i++) destination[i]=source[i]; } #endif } Commit Message: CWE ID: CWE-189
static inline void CopyPixels(PixelPacket *destination,
168,811
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); fs_logger2("clone", dest); unlink(src); }
170,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void jsR_calllwfunction(js_State *J, int n, js_Function *F, js_Environment *scope) { js_Value v; int i; jsR_savescope(J, scope); if (n > F->numparams) { js_pop(J, F->numparams - n); n = F->numparams; } for (i = n; i < F->varlen; ++i) js_pushundefined(J); jsR_run(J, F); v = *stackidx(J, -1); TOP = --BOT; /* clear stack */ js_pushvalue(J, v); jsR_restorescope(J); } Commit Message: CWE ID: CWE-119
static void jsR_calllwfunction(js_State *J, int n, js_Function *F, js_Environment *scope) { js_Value v; int i; jsR_savescope(J, scope); if (n > F->numparams) { js_pop(J, n - F->numparams); n = F->numparams; } for (i = n; i < F->varlen; ++i) js_pushundefined(J); jsR_run(J, F); v = *stackidx(J, -1); TOP = --BOT; /* clear stack */ js_pushvalue(J, v); jsR_restorescope(J); }
165,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); if (!lua_checkstack(L, nargs)) return luaL_argerror(L, 0, "Too many arguments for MessagePack pack."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119
int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); if (!lua_checkstack(L, nargs)) return luaL_argerror(L, 0, "Too many arguments for MessagePack pack."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ luaL_checkstack(L, 1, "in function mp_check"); lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; }
169,241
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserRenderProcessHost::PropagateBrowserCommandLineToRenderer( const CommandLine& browser_cmd, CommandLine* renderer_cmd) const { static const char* const kSwitchNames[] = { switches::kChromeFrame, switches::kDisable3DAPIs, switches::kDisableAcceleratedCompositing, switches::kDisableApplicationCache, switches::kDisableAudio, switches::kDisableBreakpad, switches::kDisableDataTransferItems, switches::kDisableDatabases, switches::kDisableDesktopNotifications, switches::kDisableDeviceOrientation, switches::kDisableFileSystem, switches::kDisableGeolocation, switches::kDisableGLMultisampling, switches::kDisableGLSLTranslator, switches::kDisableGpuVsync, switches::kDisableIndexedDatabase, switches::kDisableJavaScriptI18NAPI, switches::kDisableLocalStorage, switches::kDisableLogging, switches::kDisableSeccompSandbox, switches::kDisableSessionStorage, switches::kDisableSharedWorkers, switches::kDisableSpeechInput, switches::kDisableWebAudio, switches::kDisableWebSockets, switches::kEnableAdaptive, switches::kEnableBenchmarking, switches::kEnableDCHECK, switches::kEnableGPUServiceLogging, switches::kEnableGPUClientLogging, switches::kEnableLogging, switches::kEnableMediaStream, switches::kEnablePepperTesting, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif switches::kEnableSeccompSandbox, switches::kEnableStatsTable, switches::kEnableVideoFullscreen, switches::kEnableVideoLogging, switches::kFullMemoryCrashReport, #if !defined (GOOGLE_CHROME_BUILD) switches::kInProcessPlugins, #endif // GOOGLE_CHROME_BUILD switches::kInProcessWebGL, switches::kJavaScriptFlags, switches::kLoggingLevel, switches::kLowLatencyAudio, switches::kNoJsRandomness, switches::kNoReferrers, switches::kNoSandbox, switches::kPlaybackMode, switches::kPpapiOutOfProcess, switches::kRecordMode, switches::kRegisterPepperPlugins, switches::kRendererAssertTest, #if !defined(OFFICIAL_BUILD) switches::kRendererCheckFalseTest, #endif // !defined(OFFICIAL_BUILD) switches::kRendererCrashTest, switches::kRendererStartupDialog, switches::kShowPaintRects, switches::kSimpleDataSource, switches::kTestSandbox, switches::kUseGL, switches::kUserAgent, switches::kV, switches::kVideoThreads, switches::kVModule, switches::kWebCoreLogChannels, }; renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames, arraysize(kSwitchNames)); if (profile()->IsOffTheRecord() && !browser_cmd.HasSwitch(switches::kDisableDatabases)) { renderer_cmd->AppendSwitch(switches::kDisableDatabases); } } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserRenderProcessHost::PropagateBrowserCommandLineToRenderer( const CommandLine& browser_cmd, CommandLine* renderer_cmd) const { static const char* const kSwitchNames[] = { switches::kChromeFrame, switches::kDisable3DAPIs, switches::kDisableAcceleratedCompositing, switches::kDisableApplicationCache, switches::kDisableAudio, switches::kDisableBreakpad, switches::kDisableDataTransferItems, switches::kDisableDatabases, switches::kDisableDesktopNotifications, switches::kDisableDeviceOrientation, switches::kDisableFileSystem, switches::kDisableGeolocation, switches::kDisableGLMultisampling, switches::kDisableGLSLTranslator, switches::kDisableGpuVsync, switches::kDisableIndexedDatabase, switches::kDisableJavaScriptI18NAPI, switches::kDisableLocalStorage, switches::kDisableLogging, switches::kDisableSeccompSandbox, switches::kDisableSessionStorage, switches::kDisableSharedWorkers, switches::kDisableSpeechInput, switches::kDisableWebAudio, switches::kDisableWebSockets, switches::kEnableAdaptive, switches::kEnableBenchmarking, switches::kEnableDCHECK, switches::kEnableGPUServiceLogging, switches::kEnableGPUClientLogging, switches::kEnableLogging, switches::kEnableMediaStream, switches::kEnablePepperTesting, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif switches::kEnableSeccompSandbox, switches::kEnableStatsTable, switches::kEnableVideoFullscreen, switches::kEnableVideoLogging, switches::kFullMemoryCrashReport, #if !defined (GOOGLE_CHROME_BUILD) switches::kInProcessPlugins, #endif // GOOGLE_CHROME_BUILD switches::kInProcessWebGL, switches::kJavaScriptFlags, switches::kLoggingLevel, switches::kLowLatencyAudio, switches::kNoJsRandomness, switches::kNoReferrers, switches::kNoSandbox, switches::kPlaybackMode, switches::kPpapiOutOfProcess, switches::kRecordMode, switches::kRegisterPepperPlugins, switches::kRemoteShellPort, switches::kRendererAssertTest, #if !defined(OFFICIAL_BUILD) switches::kRendererCheckFalseTest, #endif // !defined(OFFICIAL_BUILD) switches::kRendererCrashTest, switches::kRendererStartupDialog, switches::kShowPaintRects, switches::kSimpleDataSource, switches::kTestSandbox, switches::kUseGL, switches::kUserAgent, switches::kV, switches::kVideoThreads, switches::kVModule, switches::kWebCoreLogChannels, }; renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames, arraysize(kSwitchNames)); if (profile()->IsOffTheRecord() && !browser_cmd.HasSwitch(switches::kDisableDatabases)) { renderer_cmd->AppendSwitch(switches::kDisableDatabases); } }
170,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GDataFileSystem::OnSearch(const SearchCallback& callback, GetDocumentsParams* params, GDataFileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != GDATA_FILE_OK) { if (!callback.is_null()) callback.Run(error, GURL(), scoped_ptr<std::vector<SearchResultInfo> >()); return; } std::vector<SearchResultInfo>* results(new std::vector<SearchResultInfo>()); DCHECK_EQ(1u, params->feed_list->size()); DocumentFeed* feed = params->feed_list->at(0); GURL next_feed; feed->GetNextFeedURL(&next_feed); if (feed->entries().empty()) { scoped_ptr<std::vector<SearchResultInfo> > result_vec(results); if (!callback.is_null()) callback.Run(error, next_feed, result_vec.Pass()); return; } for (size_t i = 0; i < feed->entries().size(); ++i) { DocumentEntry* doc = const_cast<DocumentEntry*>(feed->entries()[i]); scoped_ptr<GDataEntry> entry( GDataEntry::FromDocumentEntry(NULL, doc, directory_service_.get())); if (!entry.get()) continue; DCHECK_EQ(doc->resource_id(), entry->resource_id()); DCHECK(!entry->is_deleted()); std::string entry_resource_id = entry->resource_id(); if (entry->AsGDataFile()) { scoped_ptr<GDataFile> entry_as_file(entry.release()->AsGDataFile()); directory_service_->RefreshFile(entry_as_file.Pass()); DCHECK(!entry.get()); } directory_service_->GetEntryByResourceIdAsync(entry_resource_id, base::Bind(&AddEntryToSearchResults, results, callback, base::Bind(&GDataFileSystem::CheckForUpdates, ui_weak_ptr_), error, i+1 == feed->entries().size(), next_feed)); } } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GDataFileSystem::OnSearch(const SearchCallback& callback, GetDocumentsParams* params, GDataFileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != GDATA_FILE_OK) { if (!callback.is_null()) callback.Run(error, GURL(), scoped_ptr<std::vector<SearchResultInfo> >()); return; } std::vector<SearchResultInfo>* results(new std::vector<SearchResultInfo>()); DCHECK_EQ(1u, params->feed_list->size()); DocumentFeed* feed = params->feed_list->at(0); GURL next_feed; feed->GetNextFeedURL(&next_feed); if (feed->entries().empty()) { scoped_ptr<std::vector<SearchResultInfo> > result_vec(results); if (!callback.is_null()) callback.Run(error, next_feed, result_vec.Pass()); return; } for (size_t i = 0; i < feed->entries().size(); ++i) { DocumentEntry* doc = const_cast<DocumentEntry*>(feed->entries()[i]); scoped_ptr<GDataEntry> entry(directory_service_->FromDocumentEntry(doc)); if (!entry.get()) continue; DCHECK_EQ(doc->resource_id(), entry->resource_id()); DCHECK(!entry->is_deleted()); std::string entry_resource_id = entry->resource_id(); if (entry->AsGDataFile()) { scoped_ptr<GDataFile> entry_as_file(entry.release()->AsGDataFile()); directory_service_->RefreshFile(entry_as_file.Pass()); DCHECK(!entry.get()); } directory_service_->GetEntryByResourceIdAsync(entry_resource_id, base::Bind(&AddEntryToSearchResults, results, callback, base::Bind(&GDataFileSystem::CheckForUpdates, ui_weak_ptr_), error, i+1 == feed->entries().size(), next_feed)); } }
171,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) { ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');"); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
void CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) { void CastConfigDelegateChromeos::StopCasting() { ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');"); // TODO(jdufault): Remove this after stopCastMirroring is properly exported. // The current beta/release versions of the cast extension do not export // stopCastMirroring, so we will also try to call the minified version. // See crbug.com/489929. ExecuteJavaScript("backgroundSetup.Qu('user-stop');"); }
171,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a, long offset,int ch, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); long i,j; int chptr=0; if (!v) return -1; for(i=offset;i<offset+n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++){ a[chptr++][i]+=v[j]; if(chptr==ch){ chptr=0; i++; } } } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a, long offset,int ch, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); long i,j; int chptr=0; if (!v) return -1; for(i=offset;i<offset+n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim && i < offset + n;j++){ a[chptr++][i]+=v[j]; if(chptr==ch){ chptr=0; i++; } } } } return 0; }
173,989
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); }
171,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); base::FundamentalValue ui_identifier(id_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); }
170,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } Commit Message: bpf: don't prune branches when a scalar is replaced with a pointer This could be made safe by passing through a reference to env and checking for env->allow_ptr_leaks, but it would only work one way and is probably not worth the hassle - not doing it will not directly lead to program rejection. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* We're trying to use a pointer in place of a scalar. * Even if the scalar was unbounded, this could lead to * pointer leaks because scalars are allowed to leak * while pointers are not. We could make this safe in * special cases if root is calling us, but it's * probably not worth the hassle. */ return false; } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; }
167,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR("%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } btif_config_remove_unpaired(config); alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR("%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR("%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } btif_config_remove_unpaired(config); // Cleanup temporary pairings if we have left guest mode if (!is_restricted_mode()) btif_config_remove_restricted(config); alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR("%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); }
173,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static PassRefPtrWillBeRawPtr<CreateFileResult> create() { return adoptRefWillBeNoop(new CreateFileResult()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
static PassRefPtrWillBeRawPtr<CreateFileResult> create() static CreateFileResult* create() { return new CreateFileResult(); }
171,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl; unsigned char *d; n=ctx->num; d=ctx->enc_data; ln=ctx->line_num; exp_nl=ctx->expect_nl; /* last line of input. */ if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF))) { rv=0; goto end; } /* We parse the input data */ for (i=0; i<inl; i++) { /* If the current line is > 80 characters, scream alot */ if (ln >= 80) { rv= -1; goto end; } /* Get char and put it into the buffer */ tmp= *(in++); v=conv_ascii2bin(tmp); /* only save the good data :-) */ if (!B64_NOT_BASE64(v)) { OPENSSL_assert(n < (int)sizeof(ctx->enc_data)); d[n++]=tmp; ln++; } else if (v == B64_ERROR) { rv= -1; goto end; } /* have we seen a '=' which is 'definitly' the last * input line. seof will point to the character that * holds it. and eof will hold how many characters to * chop off. */ if (tmp == '=') { if (seof == -1) seof=n; eof++; } if (v == B64_CR) { ln = 0; if (exp_nl) continue; } /* eoln */ if (v == B64_EOLN) { ln=0; if (exp_nl) { exp_nl=0; continue; } } exp_nl=0; /* If we are at the end of input and it looks like a * line, process it. */ if (((i+1) == inl) && (((n&3) == 0) || eof)) { v=B64_EOF; /* In case things were given us in really small records (so two '=' were given in separate updates), eof may contain the incorrect number of ending bytes to skip, so let's redo the count */ eof = 0; if (d[n-1] == '=') eof++; if (d[n-2] == '=') eof++; /* There will never be more than two '=' */ } if ((v == B64_EOF && (n&3) == 0) || (n >= 64)) { /* This is needed to work correctly on 64 byte input * lines. We process the line and then need to * accept the '\n' */ if ((v != B64_EOF) && (n >= 64)) exp_nl=1; if (n > 0) { v=EVP_DecodeBlock(out,d,n); n=0; if (v < 0) { rv=0; goto end; } ret+=(v-eof); } else eof=1; v=0; } /* This is the case where we have had a short * but valid input line */ if ((v < ctx->length) && eof) { rv=0; goto end; } else ctx->length=v; if (seof >= 0) { rv=0; goto end; } out+=v; } } Commit Message: CWE ID: CWE-119
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl; unsigned char *d; n=ctx->num; d=ctx->enc_data; ln=ctx->line_num; exp_nl=ctx->expect_nl; /* last line of input. */ if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF))) { rv=0; goto end; } /* We parse the input data */ for (i=0; i<inl; i++) { /* If the current line is > 80 characters, scream alot */ if (ln >= 80) { rv= -1; goto end; } /* Get char and put it into the buffer */ tmp= *(in++); v=conv_ascii2bin(tmp); /* only save the good data :-) */ if (!B64_NOT_BASE64(v)) { OPENSSL_assert(n < (int)sizeof(ctx->enc_data)); d[n++]=tmp; ln++; } else if (v == B64_ERROR) { rv= -1; goto end; } /* have we seen a '=' which is 'definitly' the last * input line. seof will point to the character that * holds it. and eof will hold how many characters to * chop off. */ if (tmp == '=') { if (seof == -1) seof=n; eof++; } if (v == B64_CR) { ln = 0; if (exp_nl) continue; } /* eoln */ if (v == B64_EOLN) { ln=0; if (exp_nl) { exp_nl=0; continue; } } exp_nl=0; /* If we are at the end of input and it looks like a * line, process it. */ if (((i+1) == inl) && (((n&3) == 0) || eof)) { v=B64_EOF; /* In case things were given us in really small records (so two '=' were given in separate updates), eof may contain the incorrect number of ending bytes to skip, so let's redo the count */ eof = 0; if (d[n-1] == '=') eof++; if (d[n-2] == '=') eof++; /* There will never be more than two '=' */ } if ((v == B64_EOF && (n&3) == 0) || (n >= 64)) { /* This is needed to work correctly on 64 byte input * lines. We process the line and then need to * accept the '\n' */ if ((v != B64_EOF) && (n >= 64)) exp_nl=1; if (n > 0) { v=EVP_DecodeBlock(out,d,n); n=0; if (v < 0) { rv=0; goto end; } if (eof > v) { rv=-1; goto end; } ret+=(v-eof); } else eof=1; v=0; } /* This is the case where we have had a short * but valid input line */ if ((v < ctx->length) && eof) { rv=0; goto end; } else ctx->length=v; if (seof >= 0) { rv=0; goto end; } out+=v; } }
164,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 phaseFrac; EAS_I32 acc0; const EAS_SAMPLE *pSamples; EAS_I32 samp1; EAS_I32 samp2; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum; phaseFrac = (EAS_I32)pWTVoice->phaseFrac; /* fetch adjacent samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif while (numSamples--) { /* linear interpolation */ acc0 = samp2 - samp1; acc0 = acc0 * phaseFrac; /*lint -e{704} <avoid divide>*/ acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS); /* save new output sample in buffer */ /*lint -e{704} <avoid divide>*/ *pOutputBuffer++ = (EAS_I16)(acc0 >> 2); /* increment phase */ phaseFrac += phaseInc; /*lint -e{704} <avoid divide>*/ acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS; /* next sample */ if (acc0 > 0) { /* advance sample pointer */ pSamples += acc0; phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK); /* fetch new samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif } } /* save pointer and phase */ pWTVoice->phaseAccum = (EAS_U32) pSamples; pWTVoice->phaseFrac = (EAS_U32) phaseFrac; } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 CWE ID: CWE-119
void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 phaseFrac; EAS_I32 acc0; const EAS_SAMPLE *pSamples; EAS_I32 samp1; EAS_I32 samp2; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); android_errorWriteLog(0x534e4554, "26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum; phaseFrac = (EAS_I32)pWTVoice->phaseFrac; /* fetch adjacent samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif while (numSamples--) { /* linear interpolation */ acc0 = samp2 - samp1; acc0 = acc0 * phaseFrac; /*lint -e{704} <avoid divide>*/ acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS); /* save new output sample in buffer */ /*lint -e{704} <avoid divide>*/ *pOutputBuffer++ = (EAS_I16)(acc0 >> 2); /* increment phase */ phaseFrac += phaseInc; /*lint -e{704} <avoid divide>*/ acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS; /* next sample */ if (acc0 > 0) { /* advance sample pointer */ pSamples += acc0; phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK); /* fetch new samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif } } /* save pointer and phase */ pWTVoice->phaseAccum = (EAS_U32) pSamples; pWTVoice->phaseFrac = (EAS_U32) phaseFrac; }
174,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; if (s->has_alpha) avctx->pix_fmt = AV_PIX_FMT_YUVA420P; } s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; } avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P; s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; }
168,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void gamma_transform_test(png_modifier *pm, PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth, PNG_CONST int palette_number, PNG_CONST int interlace_type, PNG_CONST double file_gamma, PNG_CONST double screen_gamma, PNG_CONST png_byte sbit, PNG_CONST int use_input_precision, PNG_CONST int scale16) { size_t pos = 0; char name[64]; if (sbit != bit_depth && sbit != 0) { pos = safecat(name, sizeof name, pos, "sbit("); pos = safecatn(name, sizeof name, pos, sbit); pos = safecat(name, sizeof name, pos, ") "); } else pos = safecat(name, sizeof name, pos, "gamma "); if (scale16) pos = safecat(name, sizeof name, pos, "16to8 "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, sbit, 0, name, use_input_precision, scale16, pm->test_gamma_expand16, 0 , 0, 0); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void gamma_transform_test(png_modifier *pm, const png_byte colour_type, const png_byte bit_depth, const int palette_number, const int interlace_type, const double file_gamma, const double screen_gamma, const png_byte sbit, const int use_input_precision, const int scale16) { size_t pos = 0; char name[64]; if (sbit != bit_depth && sbit != 0) { pos = safecat(name, sizeof name, pos, "sbit("); pos = safecatn(name, sizeof name, pos, sbit); pos = safecat(name, sizeof name, pos, ") "); } else pos = safecat(name, sizeof name, pos, "gamma "); if (scale16) pos = safecat(name, sizeof name, pos, "16to8 "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, sbit, 0, name, use_input_precision, scale16, pm->test_gamma_expand16, 0 , 0, 0); }
173,615
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; /* The remaining bits are in the top of the byte, the mask is the bits to * retain. */ mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth, int littleendian) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; if (littleendian) mask = 0xff << (bitWidth & 7); else mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } }
173,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TestJavaScriptDialogManager() : is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {} Commit Message: If a page shows a popup, end fullscreen. This was implemented in Blink r159834, but it is susceptible to a popup/fullscreen race. This CL reverts that implementation and re-implements it in WebContents. BUG=752003 TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f Reviewed-on: https://chromium-review.googlesource.com/606987 Commit-Queue: Avi Drissman <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Cr-Commit-Position: refs/heads/master@{#498171} CWE ID: CWE-20
TestJavaScriptDialogManager() TestWCDelegateForDialogsAndFullscreen() : is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
172,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: path_poly(PG_FUNCTION_ARGS) { PATH *path = PG_GETARG_PATH_P(0); POLYGON *poly; int size; int i; /* This is not very consistent --- other similar cases return NULL ... */ if (!path->closed) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("open path cannot be converted to polygon"))); size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts; poly = (POLYGON *) palloc(size); SET_VARSIZE(poly, size); poly->npts = path->npts; for (i = 0; i < path->npts; i++) { poly->p[i].x = path->p[i].x; poly->p[i].y = path->p[i].y; } make_bound_box(poly); PG_RETURN_POLYGON_P(poly); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
path_poly(PG_FUNCTION_ARGS) { PATH *path = PG_GETARG_PATH_P(0); POLYGON *poly; int size; int i; /* This is not very consistent --- other similar cases return NULL ... */ if (!path->closed) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("open path cannot be converted to polygon"))); /* * Never overflows: the old size fit in MaxAllocSize, and the new size is * just a small constant larger. */ size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts; poly = (POLYGON *) palloc(size); SET_VARSIZE(poly, size); poly->npts = path->npts; for (i = 0; i < path->npts; i++) { poly->p[i].x = path->p[i].x; poly->p[i].y = path->p[i].y; } make_bound_box(poly); PG_RETURN_POLYGON_P(poly); }
166,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *s, *t, c; int i, proto; const void *se; if (length <= 0) return; b = (uint8_t *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = (u_char *)p, t = b, i = length; i > 0; i--) { c = *s++; if (c == 0x7d) { if (i > 1) { i--; c = *s++ ^ 0x20; } else continue; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); } Commit Message: Do bounds checking when unescaping PPP. Clean up a const issue while we're at it. CWE ID: CWE-119
ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *t, c; const u_char *s; int i, proto; const void *se; if (length <= 0) return; b = (u_char *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { c = *s++; if (c == 0x7d) { if (i <= 1 || !ND_TTEST(*s)) break; i--; c = *s++ ^ 0x20; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); }
166,240