instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { PadContext *s = inlink->dst->priv; AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0], w + (s->w - s->in_w), h + (s->h - s->in_h)); int plane; if (!frame) return NULL; frame->width = w; frame->height = h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int hsub = s->draw.hsub[plane]; int vsub = s->draw.vsub[plane]; frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] + (s->y >> vsub) * frame->linesize[plane]; } return frame; } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { PadContext *s = inlink->dst->priv; AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0], w + (s->w - s->in_w), h + (s->h - s->in_h)); int plane; if (!frame) return NULL; frame->width = w; frame->height = h; for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) { int hsub = s->draw.hsub[plane]; int vsub = s->draw.vsub[plane]; frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] + (s->y >> vsub) * frame->linesize[plane]; } return frame; }
166,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string print_valuetype(Value::ValueType e) { switch (e) { case Value::TYPE_NULL: return "NULL "; case Value::TYPE_BOOLEAN: return "BOOL"; case Value::TYPE_INTEGER: return "INT"; case Value::TYPE_DOUBLE: return "DOUBLE"; case Value::TYPE_STRING: return "STRING"; case Value::TYPE_BINARY: return "BIN"; case Value::TYPE_DICTIONARY: return "DICT"; case Value::TYPE_LIST: return "LIST"; default: return "ERROR"; } } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
std::string print_valuetype(Value::ValueType e) {
170,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static long ioctl_file_dedupe_range(struct file *file, void __user *arg) { struct file_dedupe_range __user *argp = arg; struct file_dedupe_range *same = NULL; int ret; unsigned long size; u16 count; if (get_user(count, &argp->dest_count)) { ret = -EFAULT; goto out; } size = offsetof(struct file_dedupe_range __user, info[count]); same = memdup_user(argp, size); if (IS_ERR(same)) { ret = PTR_ERR(same); same = NULL; goto out; } ret = vfs_dedupe_file_range(file, same); if (ret) goto out; ret = copy_to_user(argp, same, size); if (ret) ret = -EFAULT; out: kfree(same); return ret; } Commit Message: vfs: ioctl: prevent double-fetch in dedupe ioctl This prevents a double-fetch from user space that can lead to to an undersized allocation and heap overflow. Fixes: 54dbc1517237 ("vfs: hoist the btrfs deduplication ioctl to the vfs") Signed-off-by: Scott Bauer <sbauer@plzdonthack.me> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
static long ioctl_file_dedupe_range(struct file *file, void __user *arg) { struct file_dedupe_range __user *argp = arg; struct file_dedupe_range *same = NULL; int ret; unsigned long size; u16 count; if (get_user(count, &argp->dest_count)) { ret = -EFAULT; goto out; } size = offsetof(struct file_dedupe_range __user, info[count]); same = memdup_user(argp, size); if (IS_ERR(same)) { ret = PTR_ERR(same); same = NULL; goto out; } same->dest_count = count; ret = vfs_dedupe_file_range(file, same); if (ret) goto out; ret = copy_to_user(argp, same, size); if (ret) ret = -EFAULT; out: kfree(same); return ret; }
166,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Avoid integer overflows in parsing fonts A malformed TTF can cause size calculations to overflow. This patch checks the maximum reasonable value so that the total size fits in 32 bits. It also adds some explicit casting to avoid possible technical undefined behavior when parsing sized unsigned values. Bug: 25645298 Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616 (cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274) CWE ID: CWE-19
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow // For all values < kMaxNGroups, kFirstGroupOffset + nGroups * kGroupSize fits in 32 bits. if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
173,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void TearDown() { vpx_svc_release(&svc_); delete(decoder_); if (codec_initialized_) vpx_codec_destroy(&codec_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void TearDown() { ReleaseEncoder(); delete(decoder_); } void InitializeEncoder() { const vpx_codec_err_t res = vpx_svc_init(&svc_, &codec_, vpx_codec_vp9_cx(), &codec_enc_); EXPECT_EQ(VPX_CODEC_OK, res); vpx_codec_control(&codec_, VP8E_SET_CPUUSED, 4); // Make the test faster vpx_codec_control(&codec_, VP9E_SET_TILE_COLUMNS, tile_columns_); vpx_codec_control(&codec_, VP9E_SET_TILE_ROWS, tile_rows_); codec_initialized_ = true; } void ReleaseEncoder() { vpx_svc_release(&svc_); if (codec_initialized_) vpx_codec_destroy(&codec_); codec_initialized_ = false; } void GetStatsData(std::string *const stats_buf) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *cx_pkt; while ((cx_pkt = vpx_codec_get_cx_data(&codec_, &iter)) != NULL) { if (cx_pkt->kind == VPX_CODEC_STATS_PKT) { EXPECT_GT(cx_pkt->data.twopass_stats.sz, 0U); ASSERT_TRUE(cx_pkt->data.twopass_stats.buf != NULL); stats_buf->append(static_cast<char*>(cx_pkt->data.twopass_stats.buf), cx_pkt->data.twopass_stats.sz); } } } void Pass1EncodeNFrames(const int n, const int layers, std::string *const stats_buf) { vpx_codec_err_t res; ASSERT_GT(n, 0); ASSERT_GT(layers, 0); svc_.spatial_layers = layers; codec_enc_.g_pass = VPX_RC_FIRST_PASS; InitializeEncoder(); libvpx_test::I420VideoSource video(test_file_name_, codec_enc_.g_w, codec_enc_.g_h, codec_enc_.g_timebase.den, codec_enc_.g_timebase.num, 0, 30); video.Begin(); for (int i = 0; i < n; ++i) { res = vpx_svc_encode(&svc_, &codec_, video.img(), video.pts(), video.duration(), VPX_DL_GOOD_QUALITY); ASSERT_EQ(VPX_CODEC_OK, res); GetStatsData(stats_buf); video.Next(); } // Flush encoder and test EOS packet. res = vpx_svc_encode(&svc_, &codec_, NULL, video.pts(), video.duration(), VPX_DL_GOOD_QUALITY); ASSERT_EQ(VPX_CODEC_OK, res); GetStatsData(stats_buf); ReleaseEncoder(); } void StoreFrames(const size_t max_frame_received, struct vpx_fixed_buf *const outputs, size_t *const frame_received) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *cx_pkt; while ((cx_pkt = vpx_codec_get_cx_data(&codec_, &iter)) != NULL) { if (cx_pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const size_t frame_size = cx_pkt->data.frame.sz; EXPECT_GT(frame_size, 0U); ASSERT_TRUE(cx_pkt->data.frame.buf != NULL); ASSERT_LT(*frame_received, max_frame_received); if (*frame_received == 0) EXPECT_EQ(1, !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)); outputs[*frame_received].buf = malloc(frame_size + 16); ASSERT_TRUE(outputs[*frame_received].buf != NULL); memcpy(outputs[*frame_received].buf, cx_pkt->data.frame.buf, frame_size); outputs[*frame_received].sz = frame_size; ++(*frame_received); } } } void Pass2EncodeNFrames(std::string *const stats_buf, const int n, const int layers, struct vpx_fixed_buf *const outputs) { vpx_codec_err_t res; size_t frame_received = 0; ASSERT_TRUE(outputs != NULL); ASSERT_GT(n, 0); ASSERT_GT(layers, 0); svc_.spatial_layers = layers; codec_enc_.rc_target_bitrate = 500; if (codec_enc_.g_pass == VPX_RC_LAST_PASS) { ASSERT_TRUE(stats_buf != NULL); ASSERT_GT(stats_buf->size(), 0U); codec_enc_.rc_twopass_stats_in.buf = &(*stats_buf)[0]; codec_enc_.rc_twopass_stats_in.sz = stats_buf->size(); } InitializeEncoder(); libvpx_test::I420VideoSource video(test_file_name_, codec_enc_.g_w, codec_enc_.g_h, codec_enc_.g_timebase.den, codec_enc_.g_timebase.num, 0, 30); video.Begin(); for (int i = 0; i < n; ++i) { res = vpx_svc_encode(&svc_, &codec_, video.img(), video.pts(), video.duration(), VPX_DL_GOOD_QUALITY); ASSERT_EQ(VPX_CODEC_OK, res); StoreFrames(n, outputs, &frame_received); video.Next(); } // Flush encoder. res = vpx_svc_encode(&svc_, &codec_, NULL, 0, video.duration(), VPX_DL_GOOD_QUALITY); EXPECT_EQ(VPX_CODEC_OK, res); StoreFrames(n, outputs, &frame_received); EXPECT_EQ(frame_received, static_cast<size_t>(n)); ReleaseEncoder(); } void DecodeNFrames(const struct vpx_fixed_buf *const inputs, const int n) { int decoded_frames = 0; int received_frames = 0; ASSERT_TRUE(inputs != NULL); ASSERT_GT(n, 0); for (int i = 0; i < n; ++i) { ASSERT_TRUE(inputs[i].buf != NULL); ASSERT_GT(inputs[i].sz, 0U); const vpx_codec_err_t res_dec = decoder_->DecodeFrame(static_cast<const uint8_t *>(inputs[i].buf), inputs[i].sz); ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder_->DecodeError(); ++decoded_frames; DxDataIterator dec_iter = decoder_->GetDxData(); while (dec_iter.Next() != NULL) { ++received_frames; } } EXPECT_EQ(decoded_frames, n); EXPECT_EQ(received_frames, n); } void DropEnhancementLayers(struct vpx_fixed_buf *const inputs, const int num_super_frames, const int remained_spatial_layers) { ASSERT_TRUE(inputs != NULL); ASSERT_GT(num_super_frames, 0); ASSERT_GT(remained_spatial_layers, 0); for (int i = 0; i < num_super_frames; ++i) { uint32_t frame_sizes[8] = {0}; int frame_count = 0; int frames_found = 0; int frame; ASSERT_TRUE(inputs[i].buf != NULL); ASSERT_GT(inputs[i].sz, 0U); vpx_codec_err_t res = vp9_parse_superframe_index(static_cast<const uint8_t*>(inputs[i].buf), inputs[i].sz, frame_sizes, &frame_count, NULL, NULL); ASSERT_EQ(VPX_CODEC_OK, res); if (frame_count == 0) { // There's no super frame but only a single frame. ASSERT_EQ(1, remained_spatial_layers); } else { // Found a super frame. uint8_t *frame_data = static_cast<uint8_t*>(inputs[i].buf); uint8_t *frame_start = frame_data; for (frame = 0; frame < frame_count; ++frame) { // Looking for a visible frame. if (frame_data[0] & 0x02) { ++frames_found; if (frames_found == remained_spatial_layers) break; } frame_data += frame_sizes[frame]; } ASSERT_LT(frame, frame_count) << "Couldn't find a visible frame. " << "remained_spatial_layers: " << remained_spatial_layers << " super_frame: " << i; if (frame == frame_count - 1) continue; frame_data += frame_sizes[frame]; // We need to add one more frame for multiple frame contexts. uint8_t marker = static_cast<const uint8_t*>(inputs[i].buf)[inputs[i].sz - 1]; const uint32_t mag = ((marker >> 3) & 0x3) + 1; const size_t index_sz = 2 + mag * frame_count; const size_t new_index_sz = 2 + mag * (frame + 1); marker &= 0x0f8; marker |= frame; // Copy existing frame sizes. memmove(frame_data + 1, frame_start + inputs[i].sz - index_sz + 1, new_index_sz - 2); // New marker. frame_data[0] = marker; frame_data += (mag * (frame + 1) + 1); *frame_data++ = marker; inputs[i].sz = frame_data - frame_start; } } } void FreeBitstreamBuffers(struct vpx_fixed_buf *const inputs, const int n) { ASSERT_TRUE(inputs != NULL); ASSERT_GT(n, 0); for (int i = 0; i < n; ++i) { free(inputs[i].buf); inputs[i].buf = NULL; inputs[i].sz = 0; } }
174,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int PrintPreviewDataService::GetAvailableDraftPageCount( const std::string& preview_ui_addr_str) { if (data_store_map_.find(preview_ui_addr_str) != data_store_map_.end()) return data_store_map_[preview_ui_addr_str]->GetAvailableDraftPageCount(); return 0; } 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
int PrintPreviewDataService::GetAvailableDraftPageCount( int PrintPreviewDataService::GetAvailableDraftPageCount(int32 preview_ui_id) { PreviewDataStoreMap::const_iterator it = data_store_map_.find(preview_ui_id); return (it == data_store_map_.end()) ? 0 : it->second->GetAvailableDraftPageCount(); }
170,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <zzoru007@gmail.com> Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Willem de Bruijn <willemb@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-125
void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && SKB_EXT_ERR(skb)->opt_stats) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } }
170,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) { struct addr_t *entry; int i; if (!bin->entry && !bin->sects) { return NULL; } if (!(entry = calloc (1, sizeof (struct addr_t)))) { return NULL; } if (bin->entry) { entry->addr = entry_to_vaddr (bin); entry->offset = addr_to_offset (bin, entry->addr); entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0); } if (!bin->entry || entry->offset == 0) { for (i = 0; i < bin->nsects; i++) { if (!strncmp (bin->sects[i].sectname, "__text", 6)) { entry->offset = (ut64)bin->sects[i].offset; sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0); entry->addr = (ut64)bin->sects[i].addr; if (!entry->addr) { // workaround for object files entry->addr = entry->offset; } break; } } bin->entry = entry->addr; } return entry; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) { struct addr_t *entry; int i; if (!bin->entry && !bin->sects) { return NULL; } if (!(entry = calloc (1, sizeof (struct addr_t)))) { return NULL; } if (bin->entry) { entry->addr = entry_to_vaddr (bin); entry->offset = addr_to_offset (bin, entry->addr); entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0); } if (!bin->entry || entry->offset == 0) { for (i = 0; i < bin->nsects; i++) { if (!strncmp (bin->sects[i].sectname, "__text", 6)) { entry->offset = (ut64)bin->sects[i].offset; sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0); entry->addr = (ut64)bin->sects[i].addr; if (!entry->addr) { // workaround for object files entry->addr = entry->offset; } break; } } bin->entry = entry->addr; } return entry; }
168,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ } Commit Message: CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len(). After we advance the pointer by the length value in the buffer, make sure it points to something in the captured data. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; ND_TCHECK2(*s, 1); } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ }
167,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: asn1_get_bit_der (const unsigned char *der, int der_len, int *ret_len, unsigned char *str, int str_size, int *bit_len) { int len_len, len_byte; if (der_len <= 0) return ASN1_GENERIC_ERROR; len_byte = asn1_get_length_der (der, der_len, &len_len) - 1; if (len_byte < 0) return ASN1_DER_ERROR; *ret_len = len_byte + len_len + 1; *bit_len = len_byte * 8 - der[len_len]; if (str_size >= len_byte) memcpy (str, der + len_len + 1, len_byte); } Commit Message: CWE ID: CWE-189
asn1_get_bit_der (const unsigned char *der, int der_len, int *ret_len, unsigned char *str, int str_size, int *bit_len) { int len_len = 0, len_byte; if (der_len <= 0) return ASN1_GENERIC_ERROR; len_byte = asn1_get_length_der (der, der_len, &len_len) - 1; if (len_byte < 0) return ASN1_DER_ERROR; *ret_len = len_byte + len_len + 1; *bit_len = len_byte * 8 - der[len_len]; if (*bit_len <= 0) return ASN1_DER_ERROR; if (str_size >= len_byte) memcpy (str, der + len_len + 1, len_byte); }
165,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; int n_dicts = 0; for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) n_dicts++; } return (n_dicts); } Commit Message: CWE ID: CWE-119
jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; uint32_t n_dicts = 0; for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) n_dicts++; } return (n_dicts); }
165,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t MediaPlayer::setDataSource( const sp<IMediaHTTPService> &httpService, const char *url, const KeyedVector<String8, String8> *headers) { ALOGV("setDataSource(%s)", url); status_t err = BAD_VALUE; if (url != NULL) { const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); } err = attachNewPlayer(player); } } return err; } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476
status_t MediaPlayer::setDataSource( const sp<IMediaHTTPService> &httpService, const char *url, const KeyedVector<String8, String8> *headers) { ALOGV("setDataSource(%s)", url); status_t err = BAD_VALUE; if (url != NULL) { const sp<IMediaPlayerService> service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); } err = attachNewPlayer(player); } } return err; }
173,537
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync( Blob* blob) { loader_->Start(blob->GetBlobDataHandle()); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync( void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync(Blob* blob) { loader_->Start(blob->GetBlobDataHandle()); }
173,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long mkvparser::UnserializeUInt( IMkvReader* pReader, long long pos, long long size) { assert(pReader); assert(pos >= 0); if ((size <= 0) || (size > 8)) return E_FILE_FORMAT_INVALID; long long result = 0; for (long long i = 0; 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 result; } 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 long mkvparser::UnserializeUInt( 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; }
174,450
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; size_t value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(size_t) (buffer[0] << 24); value|=buffer[1] << 16; value|=buffer[2] << 8; value|=buffer[3]; quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; unsigned int value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); }
169,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; struct sshbuf *b = NULL; int r; const u_char *inblob, *outblob; size_t inl, outl; if ((r = sshbuf_froms(m, &b)) != 0) goto out; if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 || (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0) goto out; if (inl == 0) state->compression_in_started = 0; else if (inl != sizeof(state->compression_in_stream)) { r = SSH_ERR_INTERNAL_ERROR; goto out; } else { state->compression_in_started = 1; memcpy(&state->compression_in_stream, inblob, inl); } if (outl == 0) state->compression_out_started = 0; else if (outl != sizeof(state->compression_out_stream)) { r = SSH_ERR_INTERNAL_ERROR; goto out; } else { state->compression_out_started = 1; memcpy(&state->compression_out_stream, outblob, outl); } r = 0; out: sshbuf_free(b); return r; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
168,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Null(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> location = callDebuggerMethod("getGeneratorObjectLocation", 1, argv).ToLocalChecked(); if (!location->IsObject()) return v8::Null(m_isolate); v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate); if (!markAsInternal(context, v8::Local<v8::Object>::Cast(location), V8InternalValueType::kLocation)) return v8::Null(m_isolate); return location; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Object> object) v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Context> context, v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Null(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> location = callDebuggerMethod("getGeneratorObjectLocation", 1, argv).ToLocalChecked(); v8::Local<v8::Value> copied; if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, location).ToLocal(&copied) || !copied->IsObject()) return v8::Null(m_isolate); if (!markAsInternal(context, v8::Local<v8::Object>::Cast(copied), V8InternalValueType::kLocation)) return v8::Null(m_isolate); return copied; }
172,067
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; } Commit Message: Fix #7152 - Null deref in cms CWE ID: CWE-476
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects || !object->list.objects[0] || !object->list.objects[1] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; }
168,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); DCHECK(begin_frame_source_); scoped_ptr<cc::CompositorFrame> frame = output_surface_->DemandDrawHw(surface_size, transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority); if (frame.get()) UpdateFrameMetaData(frame->metadata); return frame.Pass(); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw( const gfx::Size& surface_size, const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); DCHECK(begin_frame_source_); scoped_ptr<cc::CompositorFrame> frame = output_surface_->DemandDrawHw(surface_size, transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority); if (frame.get()) UpdateFrameMetaData(frame->metadata); return frame.Pass(); }
171,619
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void TearDownTestCase() { vpx_free(input_ - 1); input_ = NULL; vpx_free(output_); output_ = NULL; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void TearDownTestCase() { vpx_free(input_ - 1); input_ = NULL; vpx_free(output_); output_ = NULL; vpx_free(output_ref_); output_ref_ = NULL; #if CONFIG_VP9_HIGHBITDEPTH vpx_free(input16_ - 1); input16_ = NULL; vpx_free(output16_); output16_ = NULL; vpx_free(output16_ref_); output16_ref_ = NULL; #endif }
174,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); }
169,798
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: random_32(void) { for(;;) { png_byte mark[4]; png_uint_32 result; store_pool_mark(mark); result = png_get_uint_32(mark); if (result != 0) return result; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
random_32(void) { for (;;) { png_byte mark[4]; png_uint_32 result; store_pool_mark(mark); result = png_get_uint_32(mark); if (result != 0) return result; } }
173,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void HostCache::RecordSet(SetOutcome outcome, base::TimeTicks now, const Entry* old_entry, const Entry& new_entry) { CACHE_HISTOGRAM_ENUM("Set", outcome, MAX_SET_OUTCOME); switch (outcome) { case SET_INSERT: case SET_UPDATE_VALID: break; case SET_UPDATE_STALE: { EntryStaleness stale; old_entry->GetStaleness(now, network_changes_, &stale); CACHE_HISTOGRAM_TIME("UpdateStale.ExpiredBy", stale.expired_by); CACHE_HISTOGRAM_COUNT("UpdateStale.NetworkChanges", stale.network_changes); CACHE_HISTOGRAM_COUNT("UpdateStale.StaleHits", stale.stale_hits); if (old_entry->error() == OK && new_entry.error() == OK) { AddressListDeltaType delta = FindAddressListDeltaType( old_entry->addresses(), new_entry.addresses()); RecordUpdateStale(delta, stale); } break; } case MAX_SET_OUTCOME: NOTREACHED(); break; } } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID:
void HostCache::RecordSet(SetOutcome outcome, base::TimeTicks now, const Entry* old_entry, const Entry& new_entry, AddressListDeltaType delta) { CACHE_HISTOGRAM_ENUM("Set", outcome, MAX_SET_OUTCOME); switch (outcome) { case SET_INSERT: case SET_UPDATE_VALID: break; case SET_UPDATE_STALE: { EntryStaleness stale; old_entry->GetStaleness(now, network_changes_, &stale); CACHE_HISTOGRAM_TIME("UpdateStale.ExpiredBy", stale.expired_by); CACHE_HISTOGRAM_COUNT("UpdateStale.NetworkChanges", stale.network_changes); CACHE_HISTOGRAM_COUNT("UpdateStale.StaleHits", stale.stale_hits); if (old_entry->error() == OK && new_entry.error() == OK) { RecordUpdateStale(delta, stale); } break; } case MAX_SET_OUTCOME: NOTREACHED(); break; } }
172,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const Chapters::Atom* Chapters::Edition::GetAtom(int index) const { if (index < 0) return NULL; if (index >= m_atoms_count) return NULL; return m_atoms + index; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Chapters::Atom* Chapters::Edition::GetAtom(int index) const const Chapters::Display* Chapters::Atom::GetDisplay(int index) const { if (index < 0) return NULL; if (index >= m_displays_count) return NULL; return m_displays + index; }
174,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) { if (!storage_partition_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); }
172,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AccessControlStatus ScriptResource::CalculateAccessControlStatus() const { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return kOpaqueResource; if (IsSameOriginOrCORSSuccessful()) return kSharableCrossOrigin; return kNotSharableCrossOrigin; } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <hiroshige@chromium.org> Reviewed-by: Kouhei Ueno <kouhei@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Takeshi Yoshino <tyoshino@chromium.org> Cr-Commit-Position: refs/heads/master@{#535176} CWE ID: CWE-200
AccessControlStatus ScriptResource::CalculateAccessControlStatus() const { AccessControlStatus ScriptResource::CalculateAccessControlStatus( const SecurityOrigin* security_origin) const { if (GetResponse().WasFetchedViaServiceWorker()) { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return kOpaqueResource; return kSharableCrossOrigin; } if (security_origin && PassesAccessControlCheck(*security_origin)) return kSharableCrossOrigin; return kNotSharableCrossOrigin; }
172,889
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0600); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } copy_file_as_user(src, dest, getuid(), getgid(), 0600); fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() { return keyboard_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
KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() {
170,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: smb_com_flush(smb_request_t *sr) { smb_ofile_t *file; smb_llist_t *flist; int rc; if (smb_flush_required == 0) { rc = smbsr_encode_empty_result(sr); return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR); } if (sr->smb_fid != 0xffff) { smbsr_lookup_file(sr); if (sr->fid_ofile == NULL) { smbsr_error(sr, NT_STATUS_INVALID_HANDLE, ERRDOS, ERRbadfid); return (SDRC_ERROR); } smb_flush_file(sr, sr->fid_ofile); } else { flist = &sr->tid_tree->t_ofile_list; smb_llist_enter(flist, RW_READER); file = smb_llist_head(flist); while (file) { mutex_enter(&file->f_mutex); smb_flush_file(sr, file); mutex_exit(&file->f_mutex); file = smb_llist_next(flist, file); } smb_llist_exit(flist); } rc = smbsr_encode_empty_result(sr); return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR); } Commit Message: 7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv Reviewed by: Gordon Ross <gwr@nexenta.com> Reviewed by: Matt Barden <matt.barden@nexenta.com> Reviewed by: Evan Layton <evan.layton@nexenta.com> Reviewed by: Dan McDonald <danmcd@omniti.com> Approved by: Gordon Ross <gwr@nexenta.com> CWE ID: CWE-476
smb_com_flush(smb_request_t *sr) { smb_ofile_t *file; smb_llist_t *flist; int rc; if (smb_flush_required == 0) { rc = smbsr_encode_empty_result(sr); return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR); } if (sr->smb_fid != 0xffff) { smbsr_lookup_file(sr); if (sr->fid_ofile == NULL) { smbsr_error(sr, NT_STATUS_INVALID_HANDLE, ERRDOS, ERRbadfid); return (SDRC_ERROR); } smb_ofile_flush(sr, sr->fid_ofile); } else { flist = &sr->tid_tree->t_ofile_list; smb_llist_enter(flist, RW_READER); file = smb_llist_head(flist); while (file) { mutex_enter(&file->f_mutex); smb_ofile_flush(sr, file); mutex_exit(&file->f_mutex); file = smb_llist_next(flist, file); } smb_llist_exit(flist); } rc = smbsr_encode_empty_result(sr); return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR); }
168,826
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx); } } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <mattjd@gmail.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Acked-by: Ian Campbell <ian.campbell@citrix.com> Acked-by: Jan Beulich <JBeulich@suse.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY); } }
166,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool DataReductionProxySettings::IsDataSaverEnabledByUser() const { //// static if (params::ShouldForceEnableDataReductionProxy()) return true; if (spdy_proxy_auth_enabled_.GetPrefName().empty()) return false; return spdy_proxy_auth_enabled_.GetValue(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
bool DataReductionProxySettings::IsDataSaverEnabledByUser() const { //// static bool DataReductionProxySettings::IsDataSaverEnabledByUser(PrefService* prefs) { if (params::ShouldForceEnableDataReductionProxy()) return true; return prefs && prefs->GetBoolean(prefs::kDataSaverEnabled); }
172,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Cluster::EOS() const //// long long element_size) { return (m_pSegment == NULL); } 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
bool Cluster::EOS() const pEntry = NULL; if (index < 0) return -1; // generic error if (m_entries_count < 0) return E_BUFFER_NOT_FULL; assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (index < m_entries_count) { pEntry = m_entries[index]; assert(pEntry); return 1; // found entry } if (m_element_size < 0) // we don't know cluster end yet return E_BUFFER_NOT_FULL; // underflow const long long element_stop = m_element_start + m_element_size; if (m_pos >= element_stop) return 0; // nothing left to parse return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed } Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) //// long long element_size) { assert(pSegment); assert(off >= 0); const long long element_start = pSegment->m_start + off; Cluster* const pCluster = new Cluster(pSegment, idx, element_start); // element_size); assert(pCluster); return pCluster; }
174,270
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: _gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; return session->internals.handshake_header_buffer.packet_length; } ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; } Commit Message: CWE ID: CWE-189
_gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; if (*recv_type != type) { gnutls_assert (); _gnutls_handshake_log ("HSK[%x]: Handshake type mismatch (under attack?)\n", session); return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET; } return session->internals.handshake_header_buffer.packet_length; } ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; }
165,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: __ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
__ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; }
166,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void TearDown() { delete[] src_; delete[] ref_; libvpx_test::ClearSystemState(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void TearDown() { if (!use_high_bit_depth_) { vpx_free(src_); delete[] ref_; #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_free(CONVERT_TO_SHORTPTR(src_)); delete[] CONVERT_TO_SHORTPTR(ref_); #endif // CONFIG_VP9_HIGHBITDEPTH } libvpx_test::ClearSystemState(); }
174,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos, long long size) { assert(pReader); assert(pos >= 0); if ((size <= 0) || (size > 8)) return E_FILE_FORMAT_INVALID; long long result = 0; for (long long i = 0; 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 result; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos, long long UnserializeUInt(IMkvReader* pReader, long long pos, long long size) { if (!pReader || pos < 0 || (size <= 0) || (size > 8)) return E_FILE_FORMAT_INVALID; long long result = 0; for (long long i = 0; 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 result; }
173,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) { frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); if (droppable_nframes_ > 0 && (cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) { for (unsigned int i = 0; i < droppable_nframes_; ++i) { if (droppable_frames_[i] == video->frame()) { std::cout << " Encoding droppable frame: " << droppable_frames_[i] << "\n"; frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); return; } } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) { // // Frame flags and layer id for temporal layers. // For two layers, test pattern is: // 1 3 // 0 2 ..... // LAST is updated on base/layer 0, GOLDEN updated on layer 1. // Non-zero pattern_switch parameter means pattern will switch to // not using LAST for frame_num >= pattern_switch. int SetFrameFlags(int frame_num, int num_temp_layers, int pattern_switch) { int frame_flags = 0; if (num_temp_layers == 2) { if (frame_num % 2 == 0) { if (frame_num < pattern_switch || pattern_switch == 0) { // Layer 0: predict from LAST and ARF, update LAST. frame_flags = VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF; } else { // Layer 0: predict from GF and ARF, update GF. frame_flags = VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF; } } else { if (frame_num < pattern_switch || pattern_switch == 0) { // Layer 1: predict from L, GF, and ARF, update GF. frame_flags = VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_LAST; } else { // Layer 1: predict from GF and ARF, update GF. frame_flags = VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF; } } } return frame_flags; } virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); // For temporal layer case. if (cfg_.ts_number_layers > 1) { frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers, pattern_switch_); for (unsigned int i = 0; i < droppable_nframes_; ++i) { if (droppable_frames_[i] == video->frame()) { std::cout << "Encoding droppable frame: " << droppable_frames_[i] << "\n"; } } } else { if (droppable_nframes_ > 0 && (cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) { for (unsigned int i = 0; i < droppable_nframes_; ++i) { if (droppable_frames_[i] == video->frame()) { std::cout << "Encoding droppable frame: " << droppable_frames_[i] << "\n"; frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); return; } } } } }
174,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void SocketStream::CheckPrivacyMode() { if (context_.get() && context_->network_delegate()) { bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_, url_); privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled; if (enable) server_ssl_config_.channel_id_enabled = false; } } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SocketStream::CheckPrivacyMode() { if (context_ && context_->network_delegate()) { bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_, url_); privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled; if (enable) server_ssl_config_.channel_id_enabled = false; } }
171,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(); check_return_status(status); } 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
void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(false); check_return_status(status); }
173,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; return 0; } Commit Message: CWE ID: CWE-311
static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; size_t fixlen = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; return 0; }
165,137
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: explicit ImageDecodedHandlerWithTimeout( const base::Callback<void(const SkBitmap&)>& image_decoded_callback) : image_decoded_callback_(image_decoded_callback), weak_ptr_factory_(this) {} Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
explicit ImageDecodedHandlerWithTimeout(
171,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); if (free_source) { efree(source); } zend_shared_alloc_register_xlat_entry(source, retval); return retval; } Commit Message: CWE ID: CWE-416
void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); zend_shared_alloc_register_xlat_entry(source, retval); if (free_source) { efree(source); } return retval; }
164,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void IOHandler::Read( const std::string& handle, Maybe<int> offset, Maybe<int> max_size, std::unique_ptr<ReadCallback> callback) { static const size_t kDefaultChunkSize = 10 * 1024 * 1024; static const char kBlobPrefix[] = "blob:"; scoped_refptr<DevToolsIOContext::ROStream> stream = io_context_->GetByHandle(handle); if (!stream && process_host_ && StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) { BrowserContext* browser_context = process_host_->GetBrowserContext(); ChromeBlobStorageContext* blob_context = ChromeBlobStorageContext::GetFor(browser_context); StoragePartition* storage_partition = process_host_->GetStoragePartition(); std::string uuid = handle.substr(strlen(kBlobPrefix)); stream = io_context_->OpenBlob(blob_context, storage_partition, handle, uuid); } if (!stream) { callback->sendFailure(Response::InvalidParams("Invalid stream handle")); return; } stream->Read( offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize), base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(), base::Passed(std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void IOHandler::Read( const std::string& handle, Maybe<int> offset, Maybe<int> max_size, std::unique_ptr<ReadCallback> callback) { static const size_t kDefaultChunkSize = 10 * 1024 * 1024; static const char kBlobPrefix[] = "blob:"; scoped_refptr<DevToolsIOContext::ROStream> stream = io_context_->GetByHandle(handle); if (!stream && browser_context_ && StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) { ChromeBlobStorageContext* blob_context = ChromeBlobStorageContext::GetFor(browser_context_); std::string uuid = handle.substr(strlen(kBlobPrefix)); stream = io_context_->OpenBlob(blob_context, storage_partition_, handle, uuid); } if (!stream) { callback->sendFailure(Response::InvalidParams("Invalid stream handle")); return; } stream->Read( offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize), base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(), base::Passed(std::move(callback)))); }
172,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cJSON *cJSON_CreateStringArray( const char **strings, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateString( strings[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_CreateStringArray( const char **strings, int count ) cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int64_t)num;}return item;} cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);if(!item->valuestring){cJSON_Delete(item);return 0;}}return item;} cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} /* Create Arrays: */ cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} /* Duplication */ cJSON *cJSON_Duplicate(cJSON *item,int recurse) { cJSON *newitem,*cptr,*nptr=0,*newchild; /* Bail on bad ptr */ if (!item) return 0; /* Create new item */ newitem=cJSON_New_Item(); if (!newitem) return 0; /* Copy over all vars */ newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} /* If non-recursive, then we're done! */ if (!recurse) return newitem; /* Walk the ->next chain for the child. */ cptr=item->child; while (cptr) { newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ if (!newchild) {cJSON_Delete(newitem);return 0;} if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ cptr=cptr->next; } return newitem; } void cJSON_Minify(char *json) { char *into=json; while (*json) { if (*json==' ') json++; else if (*json=='\t') json++; /* Whitespace characters. */ else if (*json=='\r') json++; else if (*json=='\n') json++; else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */ else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */ else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */ else *into++=*json++; /* All other characters. */ } *into=0; /* and null-terminate. */ }
167,279
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool AXARIAGridCell::isAriaColumnHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringCase(role, "columnheader"); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXARIAGridCell::isAriaColumnHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringASCIICase(role, "columnheader"); }
171,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <fs@opera.com> Commit-Queue: Chris Harrelson <chrishtr@chromium.org> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased), origin_tainted_by_content_(false) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); }
172,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ImageTransportClientTexture( WebKit::WebGraphicsContext3D* host_context, const gfx::Size& size, float device_scale_factor, uint64 surface_id) : ui::Texture(true, size, device_scale_factor), host_context_(host_context), texture_id_(surface_id) { } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
ImageTransportClientTexture(
171,362
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void XMLHttpRequest::didTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::didTimeout() void XMLHttpRequest::handleDidTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); m_exceptionCode = TimeoutError; handleDidFailGeneric(); if (!m_async) { m_state = DONE; return; } changeState(DONE); dispatchEventAndLoadEnd(eventNames().timeoutEvent); }
171,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const wchar_t* GetIntegrityLevelString(IntegrityLevel integrity_level) { switch (integrity_level) { case INTEGRITY_LEVEL_SYSTEM: return L"S-1-16-16384"; case INTEGRITY_LEVEL_HIGH: return L"S-1-16-12288"; case INTEGRITY_LEVEL_MEDIUM: return L"S-1-16-8192"; case INTEGRITY_LEVEL_MEDIUM_LOW: return L"S-1-16-6144"; case INTEGRITY_LEVEL_LOW: return L"S-1-16-4096"; case INTEGRITY_LEVEL_BELOW_LOW: return L"S-1-16-2048"; case INTEGRITY_LEVEL_LAST: return NULL; } NOTREACHED(); return NULL; } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
const wchar_t* GetIntegrityLevelString(IntegrityLevel integrity_level) { switch (integrity_level) { case INTEGRITY_LEVEL_SYSTEM: return L"S-1-16-16384"; case INTEGRITY_LEVEL_HIGH: return L"S-1-16-12288"; case INTEGRITY_LEVEL_MEDIUM: return L"S-1-16-8192"; case INTEGRITY_LEVEL_MEDIUM_LOW: return L"S-1-16-6144"; case INTEGRITY_LEVEL_LOW: return L"S-1-16-4096"; case INTEGRITY_LEVEL_BELOW_LOW: return L"S-1-16-2048"; case INTEGRITY_LEVEL_UNTRUSTED: return L"S-1-16-0"; case INTEGRITY_LEVEL_LAST: return NULL; } NOTREACHED(); return NULL; }
170,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) { int start = 0; u32 prev_legacy, cur_legacy; mutex_lock(&kvm->arch.vpit->pit_state.lock); prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY; cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY; if (!prev_legacy && cur_legacy) start = 1; memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels, sizeof(kvm->arch.vpit->pit_state.channels)); kvm->arch.vpit->pit_state.flags = ps->flags; kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID:
static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) { int start = 0; int i; u32 prev_legacy, cur_legacy; mutex_lock(&kvm->arch.vpit->pit_state.lock); prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY; cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY; if (!prev_legacy && cur_legacy) start = 1; memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels, sizeof(kvm->arch.vpit->pit_state.channels)); kvm->arch.vpit->pit_state.flags = ps->flags; for (i = 0; i < 3; i++) kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; }
167,561
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: mm_answer_pam_init_ctx(int sock, Buffer *m) { debug3("%s", __func__); authctxt->user = buffer_get_string(m, NULL); sshpam_ctxt = (sshpam_device.init_ctx)(authctxt); sshpam_authok = NULL; buffer_clear(m); if (sshpam_ctxt != NULL) { monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1); buffer_put_int(m, 1); } else { buffer_put_int(m, 0); } mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m); return (0); } Commit Message: Don't resend username to PAM; it already has it. Pointed out by Moritz Jodeit; ok dtucker@ CWE ID: CWE-20
mm_answer_pam_init_ctx(int sock, Buffer *m) { debug3("%s", __func__); sshpam_ctxt = (sshpam_device.init_ctx)(authctxt); sshpam_authok = NULL; buffer_clear(m); if (sshpam_ctxt != NULL) { monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1); buffer_put_int(m, 1); } else { buffer_put_int(m, 0); } mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m); return (0); }
166,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length) { } Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used. These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect. BUG=552749 Review URL: https://codereview.chromium.org/1419293005 Cr-Commit-Position: refs/heads/master@{#359229} CWE ID: CWE-310
void TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length) { RELEASE_ASSERT_NOT_REACHED(); }
172,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: get_control(png_const_structrp png_ptr) { /* This just returns the (file*). The chunk and idat control structures * don't always exist. */ struct control *control = png_voidcast(struct control*, png_get_error_ptr(png_ptr)); return &control->file; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
get_control(png_const_structrp png_ptr) { /* This just returns the (file*). The chunk and idat control structures * don't always exist. */ struct control *control = voidcast(struct control*, png_get_error_ptr(png_ptr)); return &control->file; }
173,732
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_expand_16_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* expand_16 does something unless the bit depth is already 16. */ return bit_depth < 16; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* expand_16 does something unless the bit depth is already 16. */ return bit_depth < 16; }
173,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* Error in the linear composition arithmetic - only relevant when * composition actually happens (0 < alpha < 1). */ if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxcalc16; else if (pm->assume_16_bit_calculations) return pm->maxcalcG; else return pm->maxcalc8; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double calcerr(const png_modifier *pm, int in_depth, int out_depth) { /* Error in the linear composition arithmetic - only relevant when * composition actually happens (0 < alpha < 1). */ if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxcalc16; else if (pm->assume_16_bit_calculations) return pm->maxcalcG; else return pm->maxcalc8; }
173,604
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double outlog(const png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; }
173,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AutofillDialogViews::SectionContainer::SetActive(bool active) { bool is_active = active && proxy_button_->visible(); if (is_active == !!background()) return; set_background(is_active ? views::Background::CreateSolidBackground(kShadingColor) : NULL); SchedulePaint(); } Commit Message: Clear out some minor TODOs. BUG=none Review URL: https://codereview.chromium.org/1047063002 Cr-Commit-Position: refs/heads/master@{#322959} CWE ID: CWE-20
void AutofillDialogViews::SectionContainer::SetActive(bool active) { bool is_active = active && proxy_button_->visible(); if (is_active == !!background()) return; set_background( is_active ? views::Background::CreateSolidBackground(kLightShadingColor) : NULL); SchedulePaint(); }
171,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_pixel_setf(image_pixel *this, unsigned int max) { this->redf = this->red / (double)max; this->greenf = this->green / (double)max; this->bluef = this->blue / (double)max; this->alphaf = this->alpha / (double)max; if (this->red < max) this->rede = this->redf * DBL_EPSILON; else this->rede = 0; if (this->green < max) this->greene = this->greenf * DBL_EPSILON; else this->greene = 0; if (this->blue < max) this->bluee = this->bluef * DBL_EPSILON; else this->bluee = 0; if (this->alpha < max) this->alphae = this->alphaf * DBL_EPSILON; else this->alphae = 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_pixel_setf(image_pixel *this, unsigned int max) image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax, unsigned int bMax, unsigned int aMax) { this->redf = this->red / (double)rMax; this->greenf = this->green / (double)gMax; this->bluef = this->blue / (double)bMax; this->alphaf = this->alpha / (double)aMax; if (this->red < rMax) this->rede = this->redf * DBL_EPSILON; else this->rede = 0; if (this->green < gMax) this->greene = this->greenf * DBL_EPSILON; else this->greene = 0; if (this->blue < bMax) this->bluee = this->bluef * DBL_EPSILON; else this->bluee = 0; if (this->alpha < aMax) this->alphae = this->alphaf * DBL_EPSILON; else this->alphae = 0; }
173,618
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */ { time_t timestamp = 0; php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; assert(ms != NULL); memset(ssb, 0, sizeof(php_stream_statbuf)); /* read-only across the board */ ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666; ssb->sb.st_size = ms->fsize; ssb->sb.st_mode |= S_IFREG; /* regular file */ #ifdef NETWARE ssb->sb.st_mtime.tv_sec = timestamp; ssb->sb.st_atime.tv_sec = timestamp; ssb->sb.st_ctime.tv_sec = timestamp; #else ssb->sb.st_mtime = timestamp; ssb->sb.st_atime = timestamp; ssb->sb.st_ctime = timestamp; #endif ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; /* this is only for APC, so use /dev/null device - no chance of conflict there! */ ssb->sb.st_dev = 0xC; /* generate unique inode number for alias/filename, so no phars will conflict */ ssb->sb.st_ino = 0; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; #endif #if !defined(PHP_WIN32) && !defined(__BEOS__) ssb->sb.st_blocks = -1; #endif return 0; } /* }}} */ Commit Message: CWE ID: CWE-20
static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */ { time_t timestamp = 0; php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; assert(ms != NULL); memset(ssb, 0, sizeof(php_stream_statbuf)); /* read-only across the board */ ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666; ssb->sb.st_size = ms->fsize; ssb->sb.st_mode |= S_IFREG; /* regular file */ #ifdef NETWARE ssb->sb.st_mtime.tv_sec = timestamp; ssb->sb.st_atime.tv_sec = timestamp; ssb->sb.st_ctime.tv_sec = timestamp; #else ssb->sb.st_mtime = timestamp; ssb->sb.st_atime = timestamp; ssb->sb.st_ctime = timestamp; #endif ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; /* this is only for APC, so use /dev/null device - no chance of conflict there! */ ssb->sb.st_dev = 0xC; /* generate unique inode number for alias/filename, so no phars will conflict */ ssb->sb.st_ino = 0; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; #endif #if !defined(PHP_WIN32) && !defined(__BEOS__) ssb->sb.st_blocks = -1; #endif return 0; } /* }}} */
165,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CanOnlyDiscardOnceTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); ExpectCanDiscardTrueAllReasons(background_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kExternal); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kProactive); #if defined(OS_CHROMEOS) ExpectCanDiscardTrue(background_lifecycle_unit, DiscardReason::kUrgent); #else ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kUrgent); #endif } 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 <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void CanOnlyDiscardOnceTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); ExpectCanDiscardTrueAllReasons(background_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kExternal); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kProactive); #if defined(OS_CHROMEOS) ExpectCanDiscardTrue(background_lifecycle_unit, DiscardReason::kUrgent); #else ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kUrgent); #endif }
172,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Document::open(Document* entered_document, ExceptionState& exception_state) { if (ImportLoader()) { exception_state.ThrowDOMException( kInvalidStateError, "Imported document doesn't support open()."); return; } if (!IsHTMLDocument()) { exception_state.ThrowDOMException(kInvalidStateError, "Only HTML documents support open()."); return; } if (throw_on_dynamic_markup_insertion_count_) { exception_state.ThrowDOMException( kInvalidStateError, "Custom Element constructor should not use open()."); return; } if (entered_document) { if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin( entered_document->GetSecurityOrigin())) { exception_state.ThrowSecurityError( "Can only call open() on same-origin documents."); return; } SetSecurityOrigin(entered_document->GetSecurityOrigin()); if (this != entered_document) { KURL new_url = entered_document->Url(); new_url.SetFragmentIdentifier(String()); SetURL(new_url); } cookie_url_ = entered_document->CookieURL(); } open(); } Commit Message: Inherit referrer and policy when creating a nested browsing context BUG=763194 R=estark@chromium.org Change-Id: Ide3950269adf26ba221f573dfa088e95291ab676 Reviewed-on: https://chromium-review.googlesource.com/732652 Reviewed-by: Emily Stark <estark@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#511211} CWE ID: CWE-20
void Document::open(Document* entered_document, ExceptionState& exception_state) { if (ImportLoader()) { exception_state.ThrowDOMException( kInvalidStateError, "Imported document doesn't support open()."); return; } if (!IsHTMLDocument()) { exception_state.ThrowDOMException(kInvalidStateError, "Only HTML documents support open()."); return; } if (throw_on_dynamic_markup_insertion_count_) { exception_state.ThrowDOMException( kInvalidStateError, "Custom Element constructor should not use open()."); return; } if (entered_document) { if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin( entered_document->GetSecurityOrigin())) { exception_state.ThrowSecurityError( "Can only call open() on same-origin documents."); return; } SetSecurityOrigin(entered_document->GetSecurityOrigin()); if (this != entered_document) { KURL new_url = entered_document->Url(); new_url.SetFragmentIdentifier(String()); SetURL(new_url); SetReferrerPolicy(entered_document->GetReferrerPolicy()); } cookie_url_ = entered_document->CookieURL(); } open(); }
172,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; cdtext_destroy (p_env->cdtext); free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } } Commit Message: CWE ID: CWE-415
get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } }
165,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret) { int ok = 0; BIGNUM *q = NULL; *ret = 0; q = BN_new(); if (q == NULL) goto err; BN_set_word(q, 1); if (BN_cmp(pub_key, q) <= 0) *ret |= DH_CHECK_PUBKEY_TOO_SMALL; BN_copy(q, dh->p); BN_sub_word(q, 1); if (BN_cmp(pub_key, q) >= 0) *ret |= DH_CHECK_PUBKEY_TOO_LARGE; ok = 1; err: if (q != NULL) BN_free(q); return (ok); } Commit Message: CWE ID: CWE-200
int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret) { int ok = 0; BIGNUM *tmp = NULL; BN_CTX *ctx = NULL; *ret = 0; ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; BN_set_word(tmp, 1); if (BN_cmp(pub_key, tmp) <= 0) *ret |= DH_CHECK_PUBKEY_TOO_SMALL; BN_copy(tmp, dh->p); BN_sub_word(tmp, 1); if (BN_cmp(pub_key, tmp) >= 0) *ret |= DH_CHECK_PUBKEY_TOO_LARGE; if (dh->q != NULL) { /* Check pub_key^q == 1 mod p */ if (!BN_mod_exp(tmp, pub_key, dh->q, dh->p, ctx)) goto err; if (!BN_is_one(tmp)) *ret |= DH_CHECK_PUBKEY_INVALID; } ok = 1; err: if (ctx != NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); } return (ok); }
165,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (printer_query.get()) { CancelableTask* task = NewRunnableMethod( this, &PrintingMessageFilter::OnUpdatePrintSettingsReply, printer_query, reply_msg); printer_query->SetSettings(job_settings, task); } } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; if (!print_job_manager_->printing_enabled()) { // Reply with NULL query. OnUpdatePrintSettingsReply(printer_query, reply_msg); return; } print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (!printer_query.get()) printer_query = new printing::PrinterQuery; CancelableTask* task = NewRunnableMethod( this, &PrintingMessageFilter::OnUpdatePrintSettingsReply, printer_query, reply_msg); printer_query->SetSettings(job_settings, task); }
170,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); final_p = fl6_update_dst(fl6, np->opt, &final); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); rcu_read_lock(); final_p = fl6_update_dst(fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; }
167,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int GetAvailableDraftPageCount() { int page_data_map_size = page_data_map_.size(); if (page_data_map_.find(printing::COMPLETE_PREVIEW_DOCUMENT_INDEX) != page_data_map_.end()) { page_data_map_size--; } return page_data_map_size; } 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
int GetAvailableDraftPageCount() { int page_data_map_size = page_data_map_.size(); if (ContainsKey(page_data_map_, printing::COMPLETE_PREVIEW_DOCUMENT_INDEX)) page_data_map_size--; return page_data_map_size; }
170,819
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool BaseSettingChange::Init(Profile* profile) { DCHECK(profile); profile_ = profile; return true; } Commit Message: [protector] Refactoring of --no-protector code. *) On DSE change, new provider is not pushed to Sync. *) Simplified code in BrowserInit. BUG=None TEST=protector.py Review URL: http://codereview.chromium.org/10065016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132398 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool BaseSettingChange::Init(Profile* profile) { DCHECK(profile && !profile_); profile_ = profile; return true; }
170,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(locale_accept_from_http) { UEnumeration *available; char *http_accept = NULL; int http_accept_len; UErrorCode status = 0; int len; char resultLocale[INTL_MAX_LOCALE_LEN+1]; UAcceptResult outResult; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC ); RETURN_FALSE; } available = ures_openAvailableLocales(NULL, &status); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list"); len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN, &outResult, http_accept, available, &status); uenum_close(available); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale"); if (len < 0 || outResult == ULOC_ACCEPT_FAILED) { RETURN_FALSE; } RETURN_STRINGL(resultLocale, len, 1); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_accept_from_http) { UEnumeration *available; char *http_accept = NULL; int http_accept_len; UErrorCode status = 0; int len; char resultLocale[INTL_MAX_LOCALE_LEN+1]; UAcceptResult outResult; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC ); RETURN_FALSE; } available = ures_openAvailableLocales(NULL, &status); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list"); len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN, &outResult, http_accept, available, &status); uenum_close(available); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale"); if (len < 0 || outResult == ULOC_ACCEPT_FAILED) { RETURN_FALSE; } RETURN_STRINGL(resultLocale, len, 1); }
167,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*) sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (table->DeleteSecurityContext == NULL) return SEC_E_UNSUPPORTED_FUNCTION; status = table->DeleteSecurityContext(phContext); return status; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext) { char* Name = NULL; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*) sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (table->DeleteSecurityContext == NULL) return SEC_E_UNSUPPORTED_FUNCTION; status = table->DeleteSecurityContext(phContext); return status; }
167,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) { DCHECK(!renderer_process_); if (base::GetProcId(renderer_process) == renderer_pid_) renderer_process_ = renderer_process; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) {
170,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; CuePoint** const qq = new CuePoint* [n]; CuePoint** q = qq; // beginning of target CuePoint** p = m_cue_points; // beginning of source CuePoint** const pp = p + m_preload_count; // end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { bool Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { if (m_count != 0) return false; if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; CuePoint** const qq = new (std::nothrow) CuePoint*[n]; if (qq == NULL) return false; CuePoint** q = qq; // beginning of target CuePoint** p = m_cue_points; // beginning of source CuePoint** const pp = p + m_preload_count; // end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new (std::nothrow) CuePoint(m_preload_count, pos); if (pCP == NULL) return false; m_cue_points[m_preload_count++] = pCP; return true; }
173,861
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t OMXNodeInstance::useGraphicBuffer2_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id *buffer) { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; OMX_ERRORTYPE err = OMX_GetParameter(mHandle, OMX_IndexParamPortDefinition, &def); if (err != OMX_ErrorNone) { OMX_INDEXTYPE index = OMX_IndexParamPortDefinition; CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u", asString(index), index, portString(portIndex), portIndex); return UNKNOWN_ERROR; } BufferMeta *bufferMeta = new BufferMeta(graphicBuffer); OMX_BUFFERHEADERTYPE *header = NULL; OMX_U8* bufferHandle = const_cast<OMX_U8*>( reinterpret_cast<const OMX_U8*>(graphicBuffer->handle)); err = OMX_UseBuffer( mHandle, &header, portIndex, bufferMeta, def.nBufferSize, bufferHandle); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, BUFFER_FMT(portIndex, "%u@%p", def.nBufferSize, bufferHandle)); delete bufferMeta; bufferMeta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pBuffer, bufferHandle); CHECK_EQ(header->pAppPrivate, bufferMeta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); CLOG_BUFFER(useGraphicBuffer2, NEW_BUFFER_FMT( *buffer, portIndex, "%u@%p", def.nBufferSize, bufferHandle)); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::useGraphicBuffer2_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id *buffer) { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; OMX_ERRORTYPE err = OMX_GetParameter(mHandle, OMX_IndexParamPortDefinition, &def); if (err != OMX_ErrorNone) { OMX_INDEXTYPE index = OMX_IndexParamPortDefinition; CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u", asString(index), index, portString(portIndex), portIndex); return UNKNOWN_ERROR; } BufferMeta *bufferMeta = new BufferMeta(graphicBuffer, portIndex); OMX_BUFFERHEADERTYPE *header = NULL; OMX_U8* bufferHandle = const_cast<OMX_U8*>( reinterpret_cast<const OMX_U8*>(graphicBuffer->handle)); err = OMX_UseBuffer( mHandle, &header, portIndex, bufferMeta, def.nBufferSize, bufferHandle); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, BUFFER_FMT(portIndex, "%u@%p", def.nBufferSize, bufferHandle)); delete bufferMeta; bufferMeta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pBuffer, bufferHandle); CHECK_EQ(header->pAppPrivate, bufferMeta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); CLOG_BUFFER(useGraphicBuffer2, NEW_BUFFER_FMT( *buffer, portIndex, "%u@%p", def.nBufferSize, bufferHandle)); return OK; }
173,535
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { // The class is not designed to handle recursive messages. This is not // expected during regular flow. However, during rendering of content for // printing, lower level code may run nested message loop. E.g. PDF may has // script to show message box http://crbug.com/502562. In that moment browser // may receive updated printer capabilities and decide to restart print // preview generation. When this happened message handling function may // choose to ignore message or safely crash process. ++ipc_nesting_level_; bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() --ipc_nesting_level_; return handled; }
171,872
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PreresolveJob::PreresolveJob(PreconnectRequest preconnect_request, PreresolveInfo* info) : url(std::move(preconnect_request.origin)), num_sockets(preconnect_request.num_sockets), allow_credentials(preconnect_request.allow_credentials), network_isolation_key( std::move(preconnect_request.network_isolation_key)), info(info) { DCHECK_GE(num_sockets, 0); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
PreresolveJob::PreresolveJob(PreconnectRequest preconnect_request, PreresolveInfo* info) : url(preconnect_request.origin.GetURL()), num_sockets(preconnect_request.num_sockets), allow_credentials(preconnect_request.allow_credentials), network_isolation_key( std::move(preconnect_request.network_isolation_key)), info(info) { DCHECK_GE(num_sockets, 0); }
172,376
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void TransportTexture::OnTexturesCreated(std::vector<int> textures) { bool ret = decoder_->MakeCurrent(); if (!ret) { LOG(ERROR) << "Failed to switch context"; return; } output_textures_->clear(); for (size_t i = 0; i < textures.size(); ++i) { uint32 gl_texture = 0; ret = decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; output_textures_->push_back(gl_texture); texture_map_.insert(std::make_pair(gl_texture, textures[i])); } create_task_->Run(); create_task_.reset(); output_textures_ = NULL; } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void TransportTexture::OnTexturesCreated(std::vector<int> textures) { void TransportTexture::OnTexturesCreated(const std::vector<int>& textures) { bool ret = decoder_->MakeCurrent(); if (!ret) { LOG(ERROR) << "Failed to switch context"; return; } output_textures_->clear(); for (size_t i = 0; i < textures.size(); ++i) { uint32 gl_texture = 0; ret = decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; output_textures_->push_back(gl_texture); texture_map_.insert(std::make_pair(gl_texture, textures[i])); } create_task_->Run(); create_task_.reset(); output_textures_ = NULL; }
170,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int can_open_delegated(struct nfs_delegation *delegation, mode_t open_flags) { if ((delegation->type & open_flags) != open_flags) return 0; if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags)) return 0; nfs_mark_delegation_referenced(delegation); return 1; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static int can_open_delegated(struct nfs_delegation *delegation, mode_t open_flags) static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode) { if ((delegation->type & fmode) != fmode) return 0; if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags)) return 0; nfs_mark_delegation_referenced(delegation); return 1; }
165,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DevToolsSession::AddHandler( std::unique_ptr<protocol::DevToolsDomainHandler> handler) { handler->Wire(dispatcher_.get()); handler->SetRenderer(process_, host_); handlers_[handler->name()] = std::move(handler); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DevToolsSession::AddHandler( std::unique_ptr<protocol::DevToolsDomainHandler> handler) { handler->Wire(dispatcher_.get()); handler->SetRenderer(process_host_id_, host_); handlers_[handler->name()] = std::move(handler); }
172,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol) { struct snd_ctl_elem_id id; unsigned int idx; unsigned int count; int err = -EINVAL; if (! kcontrol) return err; if (snd_BUG_ON(!card || !kcontrol->info)) goto error; id = kcontrol->id; down_write(&card->controls_rwsem); if (snd_ctl_find_id(card, &id)) { up_write(&card->controls_rwsem); dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n", id.iface, id.device, id.subdevice, id.name, id.index); err = -EBUSY; goto error; } if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); err = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; count = kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return err; } Commit Message: ALSA: control: Make sure that id->index does not overflow The ALSA control code expects that the range of assigned indices to a control is continuous and does not overflow. Currently there are no checks to enforce this. If a control with a overflowing index range is created that control becomes effectively inaccessible and unremovable since snd_ctl_find_id() will not be able to find it. This patch adds a check that makes sure that controls with a overflowing index range can not be created. Signed-off-by: Lars-Peter Clausen <lars@metafoo.de> Acked-by: Jaroslav Kysela <perex@perex.cz> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-189
int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol) { struct snd_ctl_elem_id id; unsigned int idx; unsigned int count; int err = -EINVAL; if (! kcontrol) return err; if (snd_BUG_ON(!card || !kcontrol->info)) goto error; id = kcontrol->id; if (id.index > UINT_MAX - kcontrol->count) goto error; down_write(&card->controls_rwsem); if (snd_ctl_find_id(card, &id)) { up_write(&card->controls_rwsem); dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n", id.iface, id.device, id.subdevice, id.name, id.index); err = -EBUSY; goto error; } if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); err = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; count = kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return err; }
169,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool asn1_write_BOOLEAN(struct asn1_data *data, bool v) { asn1_push_tag(data, ASN1_BOOLEAN); asn1_write_uint8(data, v ? 0xFF : 0); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_BOOLEAN(struct asn1_data *data, bool v) { if (!asn1_push_tag(data, ASN1_BOOLEAN)) return false; if (!asn1_write_uint8(data, v ? 0xFF : 0)) return false; return asn1_pop_tag(data); }
164,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey) { int ok = 0; unsigned char challenge[30]; unsigned char signature[256]; unsigned int siglen = sizeof signature; const EVP_MD *md = EVP_sha1(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); EVP_PKEY *privkey = PKCS11_get_private_key(authkey); EVP_PKEY *pubkey = PKCS11_get_public_key(authkey); /* Verify a SHA-1 hash of random data, signed by the key. * * Note that this will not work keys that aren't eligible for signing. * Unfortunately, libp11 currently has no way of checking * C_GetAttributeValue(CKA_SIGN), see * https://github.com/OpenSC/libp11/issues/219. Since we don't want to * implement try and error, we live with this limitation */ if (1 != randomize(pamh, challenge, sizeof challenge)) { goto err; } if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md || !EVP_SignInit(md_ctx, md) || !EVP_SignUpdate(md_ctx, challenge, sizeof challenge) || !EVP_SignFinal(md_ctx, signature, &siglen, privkey) || !EVP_MD_CTX_reset(md_ctx) || !EVP_VerifyInit(md_ctx, md) || !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge) || 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) { pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n", ERR_reason_error_string(ERR_get_error())); prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key")); goto err; } ok = 1; err: if (NULL != pubkey) EVP_PKEY_free(pubkey); if (NULL != privkey) EVP_PKEY_free(privkey); if (NULL != md_ctx) { EVP_MD_CTX_free(md_ctx); } return ok; } Commit Message: Use EVP_PKEY_size() to allocate correct size of signature buffer. (#18) Do not use fixed buffer size for signature, EVP_SignFinal() requires buffer for signature at least EVP_PKEY_size(pkey) bytes in size. Fixes crash when using 4K RSA signatures (https://github.com/OpenSC/pam_p11/issues/16, https://github.com/OpenSC/pam_p11/issues/15) CWE ID: CWE-119
static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey) { int ok = 0; unsigned char challenge[30]; unsigned char *signature = NULL; unsigned int siglen; const EVP_MD *md = EVP_sha1(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); EVP_PKEY *privkey = PKCS11_get_private_key(authkey); EVP_PKEY *pubkey = PKCS11_get_public_key(authkey); if (NULL == privkey) goto err; siglen = EVP_PKEY_size(privkey); if (siglen <= 0) goto err; signature = malloc(siglen); if (NULL == signature) goto err; /* Verify a SHA-1 hash of random data, signed by the key. * * Note that this will not work keys that aren't eligible for signing. * Unfortunately, libp11 currently has no way of checking * C_GetAttributeValue(CKA_SIGN), see * https://github.com/OpenSC/libp11/issues/219. Since we don't want to * implement try and error, we live with this limitation */ if (1 != randomize(pamh, challenge, sizeof challenge)) { goto err; } if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md || !EVP_SignInit(md_ctx, md) || !EVP_SignUpdate(md_ctx, challenge, sizeof challenge) || !EVP_SignFinal(md_ctx, signature, &siglen, privkey) || !EVP_MD_CTX_reset(md_ctx) || !EVP_VerifyInit(md_ctx, md) || !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge) || 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) { pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n", ERR_reason_error_string(ERR_get_error())); prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key")); goto err; } ok = 1; err: free(signature); if (NULL != pubkey) EVP_PKEY_free(pubkey); if (NULL != privkey) EVP_PKEY_free(privkey); if (NULL != md_ctx) { EVP_MD_CTX_free(md_ctx); } return ok; }
169,513
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } if (!ND_TTEST(rp->rm_call.cb_proc)) return (0); xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); }
167,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void SavePayload(size_t handle, uint32_t *payload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp && payload) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fwrite(payload, 1, mp4->metasizes[index], mp4->mediafp); } return; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
void SavePayload(size_t handle, uint32_t *payload, uint32_t index) void LongSeek(mp4object *mp4, int64_t offset) { if (mp4 && offset) { if (mp4->filepos + offset < mp4->filesize) { LONGSEEK(mp4->mediafp, offset, SEEK_CUR); mp4->filepos += offset; } else { mp4->filepos = mp4->filesize; } } }
169,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) { if (prev_options != NULL) { *prev_options = MBREX(regex_default_options); } if (prev_syntax != NULL) { *prev_syntax = MBREX(regex_default_syntax); } MBREX(regex_default_options) = options; MBREX(regex_default_syntax) = syntax; } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) { if (prev_options != NULL) { *prev_options = MBREX(regex_default_options); } if (prev_syntax != NULL) { *prev_syntax = MBREX(regex_default_syntax); } MBREX(regex_default_options) = options; MBREX(regex_default_syntax) = syntax; }
167,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } } Commit Message: net: fix infoleak in llc The stack object “info” has a total size of 12 bytes. Its last byte is padding which is not initialized and leaked via “put_cmsg”. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; memset(&info, 0, sizeof(info)); info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } }
167,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: user_change_icon_file_authorized_cb (Daemon *daemon, User *user, GDBusMethodInvocation *context, gpointer data) { g_autofree gchar *filename = NULL; g_autoptr(GFile) file = NULL; g_autoptr(GFileInfo) info = NULL; guint32 mode; GFileType type; guint64 size; filename = g_strdup (data); if (filename == NULL || *filename == '\0') { g_autofree gchar *dest_path = NULL; g_autoptr(GFile) dest = NULL; g_autoptr(GError) error = NULL; g_clear_pointer (&filename, g_free); dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL); dest = g_file_new_for_path (dest_path); if (!g_file_delete (dest, NULL, &error) && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message); return; } goto icon_saved; } file = g_file_new_for_path (filename); info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "," G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, return; } Commit Message: CWE ID: CWE-22
user_change_icon_file_authorized_cb (Daemon *daemon, User *user, GDBusMethodInvocation *context, gpointer data) { g_autofree gchar *filename = NULL; g_autoptr(GFile) file = NULL; g_autoptr(GFileInfo) info = NULL; guint32 mode; GFileType type; guint64 size; filename = g_strdup (data); if (filename == NULL || *filename == '\0') { g_autofree gchar *dest_path = NULL; g_autoptr(GFile) dest = NULL; g_autoptr(GError) error = NULL; g_clear_pointer (&filename, g_free); dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL); dest = g_file_new_for_path (dest_path); if (!g_file_delete (dest, NULL, &error) && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message); return; } goto icon_saved; } file = g_file_new_for_path (filename); g_clear_pointer (&filename, g_free); /* Canonicalize path so we can call g_str_has_prefix on it * below without concern for ../ path components moving outside * the prefix */ filename = g_file_get_path (file); info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "," G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, return; }
164,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int prepare_binprm(struct linux_binprm *bprm) { struct inode *inode = file_inode(bprm->file); umode_t mode = inode->i_mode; int retval; /* clear any previous set[ug]id data from a previous binary */ bprm->cred->euid = current_euid(); bprm->cred->egid = current_egid(); if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) && !task_no_new_privs(current) && kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) && kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) { /* Set-uid? */ if (mode & S_ISUID) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->euid = inode->i_uid; } /* Set-gid? */ /* * If setgid is set but no group execute bit then this * is a candidate for mandatory locking, not a setgid * executable. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->egid = inode->i_gid; } } /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); } Commit Message: fs: take i_mutex during prepare_binprm for set[ug]id executables This prevents a race between chown() and execve(), where chowning a setuid-user binary to root would momentarily make the binary setuid root. This patch was mostly written by Linus Torvalds. Signed-off-by: Jann Horn <jann@thejh.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
int prepare_binprm(struct linux_binprm *bprm) { int retval; bprm_fill_uid(bprm); /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); }
166,625
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len) { int offset = 0; const uint8_t *ptr = NULL; if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE)) goto end_get_sig; if (asn1_sig[offset++] != ASN1_OCTET_STRING) goto end_get_sig; *len = get_asn1_length(asn1_sig, &offset); ptr = &asn1_sig[offset]; /* all ok */ end_get_sig: return ptr; } Commit Message: Apply CVE fixes for X509 parsing Apply patches developed by Sze Yiu which correct a vulnerability in X509 parsing. See CVE-2018-16150 and CVE-2018-16149 for more info. CWE ID: CWE-347
static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len)
169,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; }
169,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: explicit SyncInternal(const std::string& name) : name_(name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), enable_sync_tabs_for_other_clients_(false), registrar_(NULL), change_delegate_(NULL), initialized_(false), testing_mode_(NON_TEST), observing_ip_address_changes_(false), traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord), encryptor_(NULL), unrecoverable_error_handler_(NULL), report_unrecoverable_error_function_(NULL), created_on_loop_(MessageLoop::current()), nigori_overwrite_count_(0) { for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { notification_info_map_.insert( std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); } BindJsMessageHandler( "getNotificationState", &SyncManager::SyncInternal::GetNotificationState); BindJsMessageHandler( "getNotificationInfo", &SyncManager::SyncInternal::GetNotificationInfo); BindJsMessageHandler( "getRootNodeDetails", &SyncManager::SyncInternal::GetRootNodeDetails); BindJsMessageHandler( "getNodeSummariesById", &SyncManager::SyncInternal::GetNodeSummariesById); BindJsMessageHandler( "getNodeDetailsById", &SyncManager::SyncInternal::GetNodeDetailsById); BindJsMessageHandler( "getAllNodes", &SyncManager::SyncInternal::GetAllNodes); BindJsMessageHandler( "getChildNodeIds", &SyncManager::SyncInternal::GetChildNodeIds); BindJsMessageHandler( "getClientServerTraffic", &SyncManager::SyncInternal::GetClientServerTraffic); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
explicit SyncInternal(const std::string& name) : name_(name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), registrar_(NULL), change_delegate_(NULL), initialized_(false), testing_mode_(NON_TEST), observing_ip_address_changes_(false), traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord), encryptor_(NULL), unrecoverable_error_handler_(NULL), report_unrecoverable_error_function_(NULL), created_on_loop_(MessageLoop::current()), nigori_overwrite_count_(0) { for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { notification_info_map_.insert( std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); } BindJsMessageHandler( "getNotificationState", &SyncManager::SyncInternal::GetNotificationState); BindJsMessageHandler( "getNotificationInfo", &SyncManager::SyncInternal::GetNotificationInfo); BindJsMessageHandler( "getRootNodeDetails", &SyncManager::SyncInternal::GetRootNodeDetails); BindJsMessageHandler( "getNodeSummariesById", &SyncManager::SyncInternal::GetNodeSummariesById); BindJsMessageHandler( "getNodeDetailsById", &SyncManager::SyncInternal::GetNodeDetailsById); BindJsMessageHandler( "getAllNodes", &SyncManager::SyncInternal::GetAllNodes); BindJsMessageHandler( "getChildNodeIds", &SyncManager::SyncInternal::GetChildNodeIds); BindJsMessageHandler( "getClientServerTraffic", &SyncManager::SyncInternal::GetClientServerTraffic); }
170,797
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebGraphicsContext3DCommandBufferImpl::FlipVertically( uint8* framebuffer, unsigned int width, unsigned int height) { uint8* scanline = scanline_.get(); if (!scanline) return; unsigned int row_bytes = width * 4; unsigned int count = height / 2; for (unsigned int i = 0; i < count; i++) { uint8* row_a = framebuffer + i * row_bytes; uint8* row_b = framebuffer + (height - i - 1) * row_bytes; memcpy(scanline, row_b, row_bytes); memcpy(row_b, row_a, row_bytes); memcpy(row_a, scanline, row_bytes); } } Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip. BUG=116637 TEST=manual test from bug report with ASAN Review URL: https://chromiumcodereview.appspot.com/9617038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void WebGraphicsContext3DCommandBufferImpl::FlipVertically( uint8* framebuffer, unsigned int width, unsigned int height) { if (width == 0) return; scanline_.resize(width * 4); uint8* scanline = &scanline_[0]; unsigned int row_bytes = width * 4; unsigned int count = height / 2; for (unsigned int i = 0; i < count; i++) { uint8* row_a = framebuffer + i * row_bytes; uint8* row_b = framebuffer + (height - i - 1) * row_bytes; memcpy(scanline, row_b, row_bytes); memcpy(row_b, row_a, row_bytes); memcpy(row_a, scanline, row_bytes); } }
171,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response, const GURL& url) { //// static DCHECK(response && response->headers.get()); std::string location; if (!response->headers->IsRedirect(&location)) return false; std::string fake_response_headers = base::StringPrintf("HTTP/1.0 302 Found\n" "Location: %s\n" "Content-length: 0\n" "Connection: close\n" "\n", location.c_str()); std::string raw_headers = HttpUtil::AssembleRawHeaders(fake_response_headers.data(), fake_response_headers.length()); response->headers = new HttpResponseHeaders(raw_headers); return true; } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19
bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response, bool ProxyClientSocket::SanitizeProxyAuth(HttpResponseInfo* response) { DCHECK(response && response->headers.get()); scoped_refptr<HttpResponseHeaders> old_headers = response->headers; const char kHeaders[] = "HTTP/1.1 407 Proxy Authentication Required\n\n"; scoped_refptr<HttpResponseHeaders> new_headers = new HttpResponseHeaders( HttpUtil::AssembleRawHeaders(kHeaders, arraysize(kHeaders))); new_headers->ReplaceStatusLine(old_headers->GetStatusLine()); CopyHeaderValues(old_headers, new_headers, "Connection"); CopyHeaderValues(old_headers, new_headers, "Proxy-Authenticate"); response->headers = new_headers; return true; } //// static bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response) { DCHECK(response && response->headers.get()); std::string location; if (!response->headers->IsRedirect(&location)) return false; // Return minimal headers; set "Content-Length: 0" to ignore response body. std::string fake_response_headers = base::StringPrintf( "HTTP/1.0 302 Found\n" "Location: %s\n" "Content-Length: 0\n" "Connection: close\n" "\n", location.c_str()); std::string raw_headers = HttpUtil::AssembleRawHeaders(fake_response_headers.data(), fake_response_headers.length()); response->headers = new HttpResponseHeaders(raw_headers); return true; }
172,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DictionaryValue* NigoriSpecificsToValue( const sync_pb::NigoriSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET(encrypted, EncryptedDataToValue); SET_BOOL(using_explicit_passphrase); SET_BOOL(encrypt_bookmarks); SET_BOOL(encrypt_preferences); SET_BOOL(encrypt_autofill_profile); SET_BOOL(encrypt_autofill); SET_BOOL(encrypt_themes); SET_BOOL(encrypt_typed_urls); SET_BOOL(encrypt_extension_settings); SET_BOOL(encrypt_extensions); SET_BOOL(encrypt_sessions); SET_BOOL(encrypt_app_settings); SET_BOOL(encrypt_apps); SET_BOOL(encrypt_search_engines); SET_BOOL(sync_tabs); SET_BOOL(encrypt_everything); SET_REP(device_information, DeviceInformationToValue); SET_BOOL(sync_tab_favicons); return value; } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
DictionaryValue* NigoriSpecificsToValue( const sync_pb::NigoriSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET(encrypted, EncryptedDataToValue); SET_BOOL(using_explicit_passphrase); SET_BOOL(encrypt_bookmarks); SET_BOOL(encrypt_preferences); SET_BOOL(encrypt_autofill_profile); SET_BOOL(encrypt_autofill); SET_BOOL(encrypt_themes); SET_BOOL(encrypt_typed_urls); SET_BOOL(encrypt_extension_settings); SET_BOOL(encrypt_extensions); SET_BOOL(encrypt_sessions); SET_BOOL(encrypt_app_settings); SET_BOOL(encrypt_apps); SET_BOOL(encrypt_search_engines); SET_BOOL(encrypt_everything); SET_REP(device_information, DeviceInformationToValue); SET_BOOL(sync_tab_favicons); return value; }
170,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 0) encoder->Control(VP8E_SET_NOISE_SENSITIVITY, denoiser_on_); if (denoiser_offon_test_) { ASSERT_GT(denoiser_offon_period_, 0) << "denoiser_offon_period_ is not positive."; if ((video->frame() + 1) % denoiser_offon_period_ == 0) { // Flip denoiser_on_ periodically denoiser_on_ ^= 1; } encoder->Control(VP8E_SET_NOISE_SENSITIVITY, denoiser_on_); } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
174,515
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid) { const char *perm = "add"; if (uid >= AID_APP) { return 0; /* Don't allow apps to register services */ } return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0; } Commit Message: ServiceManager: Allow system services running as secondary users to add services This should be reverted when all system services have been cleaned up to not do this. A process looking up a service while running in the background will see the service registered by the active user (assuming the service is registered on every user switch), not the service registered by the user that the process itself belongs to. BUG: 30795333 Change-Id: I1b74d58be38ed358f43c163692f9e704f8f31dbe (cherry picked from commit e6bbe69ba739c8a08837134437aaccfea5f1d943) CWE ID: CWE-264
static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid) { const char *perm = "add"; if (multiuser_get_app_id(uid) >= AID_APP) { return 0; /* Don't allow apps to register services */ } return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0; }
173,403
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChangeCurrentInputMethodFromId(const std::string& input_method_id) { const chromeos::InputMethodDescriptor* descriptor = chromeos::input_method::GetInputMethodDescriptorFromId( input_method_id); if (descriptor) { ChangeCurrentInputMethod(*descriptor); } else { LOG(ERROR) << "Descriptor is not found for: " << input_method_id; } } 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 ChangeCurrentInputMethodFromId(const std::string& input_method_id) { const input_method::InputMethodDescriptor* descriptor = input_method::GetInputMethodDescriptorFromId( input_method_id); if (descriptor) { ChangeCurrentInputMethod(*descriptor); } else { LOG(ERROR) << "Descriptor is not found for: " << input_method_id; } }
170,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct rpc_cred *cred; struct nfs4_state *state; cred = rpc_lookup_cred(); if (IS_ERR(cred)) return PTR_ERR(cred); state = nfs4_do_open(dir, &path, openflags, NULL, cred); put_rpccred(cred); if (IS_ERR(state)) { switch (PTR_ERR(state)) { case -EPERM: case -EACCES: case -EDQUOT: case -ENOSPC: case -EROFS: lookup_instantiate_filp(nd, (struct dentry *)state, NULL); return 1; default: goto out_drop; } } if (state->inode == dentry->d_inode) { nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); nfs4_intent_set_file(nd, &path, state); return 1; } nfs4_close_sync(&path, state, openflags); out_drop: d_drop(dentry); return 0; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct rpc_cred *cred; struct nfs4_state *state; fmode_t fmode = openflags & (FMODE_READ | FMODE_WRITE); cred = rpc_lookup_cred(); if (IS_ERR(cred)) return PTR_ERR(cred); state = nfs4_do_open(dir, &path, fmode, openflags, NULL, cred); put_rpccred(cred); if (IS_ERR(state)) { switch (PTR_ERR(state)) { case -EPERM: case -EACCES: case -EDQUOT: case -ENOSPC: case -EROFS: lookup_instantiate_filp(nd, (struct dentry *)state, NULL); return 1; default: goto out_drop; } } if (state->inode == dentry->d_inode) { nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); nfs4_intent_set_file(nd, &path, state, fmode); return 1; } nfs4_close_sync(&path, state, fmode); out_drop: d_drop(dentry); return 0; }
165,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string ContextualSearchDelegate::BuildRequestUrl(std::string selection) { if (!template_url_service_ || !template_url_service_->GetDefaultSearchProvider()) { return std::string(); } std::string selected_text(net::EscapeQueryParamValue(selection, true)); TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); TemplateURLRef::SearchTermsArgs search_terms_args = TemplateURLRef::SearchTermsArgs(base::string16()); int now_on_tap_version = field_trial_->IsNowOnTapBarIntegrationEnabled() ? kNowOnTapVersion : 0; TemplateURLRef::SearchTermsArgs::ContextualSearchParams params( kContextualSearchRequestVersion, selected_text, std::string(), now_on_tap_version); search_terms_args.contextual_search_params = params; std::string request( template_url->contextual_search_url_ref().ReplaceSearchTerms( search_terms_args, template_url_service_->search_terms_data(), NULL)); std::string replacement_url = field_trial_->GetResolverURLPrefix(); if (!replacement_url.empty()) { size_t pos = request.find(kContextualSearchServerEndpoint); if (pos != std::string::npos) { request.replace(0, pos + strlen(kContextualSearchServerEndpoint), replacement_url); } } return request; } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
std::string ContextualSearchDelegate::BuildRequestUrl(std::string selection) { if (!template_url_service_ || !template_url_service_->GetDefaultSearchProvider()) { return std::string(); } std::string selected_text(net::EscapeQueryParamValue(selection, true)); TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); TemplateURLRef::SearchTermsArgs search_terms_args = TemplateURLRef::SearchTermsArgs(base::string16()); int contextual_cards_version = field_trial_->IsContextualCardsBarIntegrationEnabled() ? kContextualCardsVersion : 0; TemplateURLRef::SearchTermsArgs::ContextualSearchParams params( kContextualSearchRequestVersion, selected_text, std::string(), contextual_cards_version); search_terms_args.contextual_search_params = params; std::string request( template_url->contextual_search_url_ref().ReplaceSearchTerms( search_terms_args, template_url_service_->search_terms_data(), NULL)); std::string replacement_url = field_trial_->GetResolverURLPrefix(); if (!replacement_url.empty()) { size_t pos = request.find(kContextualSearchServerEndpoint); if (pos != std::string::npos) { request.replace(0, pos + strlen(kContextualSearchServerEndpoint), replacement_url); } } return request; }
171,641
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { return usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), RTL8150_REQ_GET_REGS, RTL8150_REQT_READ, indx, 0, data, size, 500); } Commit Message: rtl8150: Use heap buffers for all register access Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { void *buf; int ret; buf = kmalloc(size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), RTL8150_REQ_GET_REGS, RTL8150_REQT_READ, indx, 0, buf, size, 500); if (ret > 0 && ret <= size) memcpy(data, buf, ret); kfree(buf); return ret; }
168,214