instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NaClProcessHost::StartNaClExecution() { NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); nacl::NaClStartParams params; params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled(); params.validation_cache_key = nacl_browser->GetValidationCacheKey(); params.version = chrome::VersionInfo().CreateVersionString(); params.enable_exception_handling = enable_exception_handling_; params.enable_debug_stub = CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaClDebug); params.enable_ipc_proxy = enable_ipc_proxy_; base::PlatformFile irt_file = nacl_browser->IrtFile(); CHECK_NE(irt_file, base::kInvalidPlatformFileValue); const ChildProcessData& data = process_->GetData(); for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) { if (!ShareHandleToSelLdr(data.handle, internal_->sockets_for_sel_ldr[i], true, &params.handles)) { return false; } } if (!ShareHandleToSelLdr(data.handle, irt_file, false, &params.handles)) return false; #if defined(OS_MACOSX) base::SharedMemory memory_buffer; base::SharedMemoryCreateOptions options; options.size = 1; options.executable = true; if (!memory_buffer.Create(options)) { DLOG(ERROR) << "Failed to allocate memory buffer"; return false; } nacl::FileDescriptor memory_fd; memory_fd.fd = dup(memory_buffer.handle().fd); if (memory_fd.fd < 0) { DLOG(ERROR) << "Failed to dup() a file descriptor"; return false; } memory_fd.auto_close = true; params.handles.push_back(memory_fd); #endif process_->Send(new NaClProcessMsg_Start(params)); internal_->sockets_for_sel_ldr.clear(); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool NaClProcessHost::StartNaClExecution() { NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); nacl::NaClStartParams params; params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled(); params.validation_cache_key = nacl_browser->GetValidationCacheKey(); params.version = chrome::VersionInfo().CreateVersionString(); params.enable_exception_handling = enable_exception_handling_; params.enable_debug_stub = CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaClDebug); base::PlatformFile irt_file = nacl_browser->IrtFile(); CHECK_NE(irt_file, base::kInvalidPlatformFileValue); const ChildProcessData& data = process_->GetData(); for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) { if (!ShareHandleToSelLdr(data.handle, internal_->sockets_for_sel_ldr[i], true, &params.handles)) { return false; } } if (!ShareHandleToSelLdr(data.handle, irt_file, false, &params.handles)) return false; #if defined(OS_MACOSX) base::SharedMemory memory_buffer; base::SharedMemoryCreateOptions options; options.size = 1; options.executable = true; if (!memory_buffer.Create(options)) { DLOG(ERROR) << "Failed to allocate memory buffer"; return false; } nacl::FileDescriptor memory_fd; memory_fd.fd = dup(memory_buffer.handle().fd); if (memory_fd.fd < 0) { DLOG(ERROR) << "Failed to dup() a file descriptor"; return false; } memory_fd.auto_close = true; params.handles.push_back(memory_fd); #endif process_->Send(new NaClProcessMsg_Start(params)); internal_->sockets_for_sel_ldr.clear(); return true; }
170,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback, int id, const GURL& image_url, image_downloader::DownloadResultPtr result) { DCHECK(result); const std::vector<SkBitmap> images = result->images.To<std::vector<SkBitmap>>(); const std::vector<gfx::Size> original_image_sizes = result->original_image_sizes.To<std::vector<gfx::Size>>(); callback.Run(id, result->http_status_code, image_url, images, original_image_sizes); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
172,209
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_data(void *opaque, uint8_t *buf, int buf_size) { struct playlist *v = opaque; HLSContext *c = v->parent->priv_data; int ret, i; int just_opened = 0; restart: if (!v->needed) return AVERROR_EOF; if (!v->input) { int64_t reload_interval; struct segment *seg; /* Check that the playlist is still needed before opening a new * segment. */ if (v->ctx && v->ctx->nb_streams) { v->needed = 0; for (i = 0; i < v->n_main_streams; i++) { if (v->main_streams[i]->discard < AVDISCARD_ALL) { v->needed = 1; break; } } } if (!v->needed) { av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n", v->index); return AVERROR_EOF; } /* If this is a live stream and the reload interval has elapsed since * the last playlist reload, reload the playlists now. */ reload_interval = default_reload_interval(v); reload: if (!v->finished && av_gettime_relative() - v->last_load_time >= reload_interval) { if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) { av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n", v->index); return ret; } /* If we need to reload the playlist again below (if * there's still no more segments), switch to a reload * interval of half the target duration. */ reload_interval = v->target_duration / 2; } if (v->cur_seq_no < v->start_seq_no) { av_log(NULL, AV_LOG_WARNING, "skipping %d segments ahead, expired from playlists\n", v->start_seq_no - v->cur_seq_no); v->cur_seq_no = v->start_seq_no; } if (v->cur_seq_no >= v->start_seq_no + v->n_segments) { if (v->finished) return AVERROR_EOF; while (av_gettime_relative() - v->last_load_time < reload_interval) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_usleep(100*1000); } /* Enough time has elapsed since the last reload */ goto reload; } seg = current_segment(v); /* load/update Media Initialization Section, if any */ ret = update_init_section(v, seg); if (ret) return ret; ret = open_input(c, v, seg); if (ret < 0) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n", v->index); v->cur_seq_no += 1; goto reload; } just_opened = 1; } if (v->init_sec_buf_read_offset < v->init_sec_data_len) { /* Push init section out first before first actual segment */ int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size); memcpy(buf, v->init_sec_buf, copy_size); v->init_sec_buf_read_offset += copy_size; return copy_size; } ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL); if (ret > 0) { if (just_opened && v->is_id3_timestamped != 0) { /* Intercept ID3 tags here, elementary audio streams are required * to convey timestamps using them in the beginning of each segment. */ intercept_id3(v, buf, buf_size, &ret); } return ret; } ff_format_io_close(v->parent, &v->input); v->cur_seq_no++; c->cur_seq_no = v->cur_seq_no; goto restart; } Commit Message: avformat/hls: Fix DoS due to infinite loop Fixes: loop.m3u The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome Found-by: Xiaohei and Wangchu from Alibaba Security Team Previous version reviewed-by: Steven Liu <lingjiujianke@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-835
static int read_data(void *opaque, uint8_t *buf, int buf_size) { struct playlist *v = opaque; HLSContext *c = v->parent->priv_data; int ret, i; int just_opened = 0; int reload_count = 0; restart: if (!v->needed) return AVERROR_EOF; if (!v->input) { int64_t reload_interval; struct segment *seg; /* Check that the playlist is still needed before opening a new * segment. */ if (v->ctx && v->ctx->nb_streams) { v->needed = 0; for (i = 0; i < v->n_main_streams; i++) { if (v->main_streams[i]->discard < AVDISCARD_ALL) { v->needed = 1; break; } } } if (!v->needed) { av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n", v->index); return AVERROR_EOF; } /* If this is a live stream and the reload interval has elapsed since * the last playlist reload, reload the playlists now. */ reload_interval = default_reload_interval(v); reload: reload_count++; if (reload_count > c->max_reload) return AVERROR_EOF; if (!v->finished && av_gettime_relative() - v->last_load_time >= reload_interval) { if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) { av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n", v->index); return ret; } /* If we need to reload the playlist again below (if * there's still no more segments), switch to a reload * interval of half the target duration. */ reload_interval = v->target_duration / 2; } if (v->cur_seq_no < v->start_seq_no) { av_log(NULL, AV_LOG_WARNING, "skipping %d segments ahead, expired from playlists\n", v->start_seq_no - v->cur_seq_no); v->cur_seq_no = v->start_seq_no; } if (v->cur_seq_no >= v->start_seq_no + v->n_segments) { if (v->finished) return AVERROR_EOF; while (av_gettime_relative() - v->last_load_time < reload_interval) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_usleep(100*1000); } /* Enough time has elapsed since the last reload */ goto reload; } seg = current_segment(v); /* load/update Media Initialization Section, if any */ ret = update_init_section(v, seg); if (ret) return ret; ret = open_input(c, v, seg); if (ret < 0) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n", v->index); v->cur_seq_no += 1; goto reload; } just_opened = 1; } if (v->init_sec_buf_read_offset < v->init_sec_data_len) { /* Push init section out first before first actual segment */ int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size); memcpy(buf, v->init_sec_buf, copy_size); v->init_sec_buf_read_offset += copy_size; return copy_size; } ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL); if (ret > 0) { if (just_opened && v->is_id3_timestamped != 0) { /* Intercept ID3 tags here, elementary audio streams are required * to convey timestamps using them in the beginning of each segment. */ intercept_id3(v, buf, buf_size, &ret); } return ret; } ff_format_io_close(v->parent, &v->input); v->cur_seq_no++; c->cur_seq_no = v->cur_seq_no; goto restart; }
167,774
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req, size_t *acl_len) { __be32 *savep; uint32_t attrlen, bitmap[3] = {0}; struct kvec *iov = req->rq_rcv_buf.head; int status; *acl_len = 0; if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0) goto out; if ((status = decode_attr_bitmap(xdr, bitmap)) != 0) goto out; if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0) goto out; if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_ACL)) { size_t hdrlen; u32 recvd; /* We ignore &savep and don't do consistency checks on * the attr length. Let userspace figure it out.... */ hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base; recvd = req->rq_rcv_buf.len - hdrlen; if (attrlen > recvd) { dprintk("NFS: server cheating in getattr" " acl reply: attrlen %u > recvd %u\n", attrlen, recvd); return -EINVAL; } xdr_read_pages(xdr, attrlen); *acl_len = attrlen; } else status = -EOPNOTSUPP; out: return status; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: stable@kernel.org Signed-off-by: Andy Adamson <andros@netapp.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req, struct nfs_getaclres *res) { __be32 *savep, *bm_p; uint32_t attrlen, bitmap[3] = {0}; struct kvec *iov = req->rq_rcv_buf.head; int status; res->acl_len = 0; if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0) goto out; bm_p = xdr->p; if ((status = decode_attr_bitmap(xdr, bitmap)) != 0) goto out; if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0) goto out; if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_ACL)) { size_t hdrlen; u32 recvd; /* The bitmap (xdr len + bitmaps) and the attr xdr len words * are stored with the acl data to handle the problem of * variable length bitmaps.*/ xdr->p = bm_p; res->acl_data_offset = be32_to_cpup(bm_p) + 2; res->acl_data_offset <<= 2; /* We ignore &savep and don't do consistency checks on * the attr length. Let userspace figure it out.... */ hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base; attrlen += res->acl_data_offset; recvd = req->rq_rcv_buf.len - hdrlen; if (attrlen > recvd) { if (res->acl_flags & NFS4_ACL_LEN_REQUEST) { /* getxattr interface called with a NULL buf */ res->acl_len = attrlen; goto out; } dprintk("NFS: acl reply: attrlen %u > recvd %u\n", attrlen, recvd); return -EINVAL; } xdr_read_pages(xdr, attrlen); res->acl_len = attrlen; } else status = -EOPNOTSUPP; out: return status; }
165,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Track::ParseContentEncodingsEntry(long long start, long long size) { IMkvReader* const pReader = m_pSegment->m_pReader; assert(pReader); long long pos = start; const long long stop = start + size; int count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x2240) // ContentEncoding ID ++count; pos += size; // consume payload assert(pos <= stop); } if (count <= 0) return -1; content_encoding_entries_ = new (std::nothrow) ContentEncoding* [count]; if (!content_encoding_entries_) return -1; content_encoding_entries_end_ = content_encoding_entries_; pos = start; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x2240) { // ContentEncoding ID ContentEncoding* const content_encoding = new (std::nothrow) ContentEncoding(); if (!content_encoding) return -1; status = content_encoding->ParseContentEncodingEntry(pos, size, pReader); if (status) { delete content_encoding; return status; } *content_encoding_entries_end_++ = content_encoding; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Track::ParseContentEncodingsEntry(long long start, long long size) { IMkvReader* const pReader = m_pSegment->m_pReader; assert(pReader); long long pos = start; const long long stop = start + size; int count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x2240) // ContentEncoding ID ++count; pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (count <= 0) return -1; content_encoding_entries_ = new (std::nothrow) ContentEncoding*[count]; if (!content_encoding_entries_) return -1; content_encoding_entries_end_ = content_encoding_entries_; pos = start; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x2240) { // ContentEncoding ID ContentEncoding* const content_encoding = new (std::nothrow) ContentEncoding(); if (!content_encoding) return -1; status = content_encoding->ParseContentEncodingEntry(pos, size, pReader); if (status) { delete content_encoding; return status; } *content_encoding_entries_end_++ = content_encoding; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; }
173,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void KioskNextHomeInterfaceBrokerImpl::GetAppController( mojom::AppControllerRequest request) { app_controller_->BindRequest(std::move(request)); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void KioskNextHomeInterfaceBrokerImpl::GetAppController( mojom::AppControllerRequest request) { AppControllerService::Get(context_)->BindRequest(std::move(request)); }
172,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { CheckThread(); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; }
172,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); StoragePartition* partition = process_->GetStoragePartition(); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } partition->ClearData(remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, 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 StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!storage_partition_) return callback->sendFailure(Response::InternalError()); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } storage_partition_->ClearData( remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); }
172,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool HasPermissionsForFile(const FilePath& file, int permissions) { FilePath current_path = file.StripTrailingSeparators(); FilePath last_path; while (current_path != last_path) { if (file_permissions_.find(current_path) != file_permissions_.end()) return (file_permissions_[current_path] & permissions) == permissions; last_path = current_path; current_path = current_path.DirName(); } return false; } Commit Message: Apply missing kParentDirectory check BUG=161564 Review URL: https://chromiumcodereview.appspot.com/11414046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168692 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool HasPermissionsForFile(const FilePath& file, int permissions) { FilePath current_path = file.StripTrailingSeparators(); FilePath last_path; int skip = 0; while (current_path != last_path) { FilePath base_name = current_path.BaseName(); if (base_name.value() == FilePath::kParentDirectory) { ++skip; } else if (skip > 0) { if (base_name.value() != FilePath::kCurrentDirectory) --skip; } else { if (file_permissions_.find(current_path) != file_permissions_.end()) return (file_permissions_[current_path] & permissions) == permissions; } last_path = current_path; current_path = current_path.DirName(); } return false; }
170,673
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cma_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event) { struct rdma_id_private *listen_id, *conn_id; struct rdma_cm_event event; int offset, ret; u8 smac[ETH_ALEN]; u8 alt_smac[ETH_ALEN]; u8 *psmac = smac; u8 *palt_smac = alt_smac; int is_iboe = ((rdma_node_get_transport(cm_id->device->node_type) == RDMA_TRANSPORT_IB) && (rdma_port_get_link_layer(cm_id->device, ib_event->param.req_rcvd.port) == IB_LINK_LAYER_ETHERNET)); listen_id = cm_id->context; if (!cma_check_req_qp_type(&listen_id->id, ib_event)) return -EINVAL; if (cma_disable_callback(listen_id, RDMA_CM_LISTEN)) return -ECONNABORTED; memset(&event, 0, sizeof event); offset = cma_user_data_offset(listen_id); event.event = RDMA_CM_EVENT_CONNECT_REQUEST; if (ib_event->event == IB_CM_SIDR_REQ_RECEIVED) { conn_id = cma_new_udp_id(&listen_id->id, ib_event); event.param.ud.private_data = ib_event->private_data + offset; event.param.ud.private_data_len = IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE - offset; } else { conn_id = cma_new_conn_id(&listen_id->id, ib_event); cma_set_req_event_data(&event, &ib_event->param.req_rcvd, ib_event->private_data, offset); } if (!conn_id) { ret = -ENOMEM; goto err1; } mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING); ret = cma_acquire_dev(conn_id, listen_id); if (ret) goto err2; conn_id->cm_id.ib = cm_id; cm_id->context = conn_id; cm_id->cm_handler = cma_ib_handler; /* * Protect against the user destroying conn_id from another thread * until we're done accessing it. */ atomic_inc(&conn_id->refcount); ret = conn_id->id.event_handler(&conn_id->id, &event); if (ret) goto err3; if (is_iboe) { if (ib_event->param.req_rcvd.primary_path != NULL) rdma_addr_find_smac_by_sgid( &ib_event->param.req_rcvd.primary_path->sgid, psmac, NULL); else psmac = NULL; if (ib_event->param.req_rcvd.alternate_path != NULL) rdma_addr_find_smac_by_sgid( &ib_event->param.req_rcvd.alternate_path->sgid, palt_smac, NULL); else palt_smac = NULL; } /* * Acquire mutex to prevent user executing rdma_destroy_id() * while we're accessing the cm_id. */ mutex_lock(&lock); if (is_iboe) ib_update_cm_av(cm_id, psmac, palt_smac); if (cma_comp(conn_id, RDMA_CM_CONNECT) && (conn_id->id.qp_type != IB_QPT_UD)) ib_send_cm_mra(cm_id, CMA_CM_MRA_SETTING, NULL, 0); mutex_unlock(&lock); mutex_unlock(&conn_id->handler_mutex); mutex_unlock(&listen_id->handler_mutex); cma_deref_id(conn_id); return 0; err3: cma_deref_id(conn_id); /* Destroy the CM ID by returning a non-zero value. */ conn_id->cm_id.ib = NULL; err2: cma_exch(conn_id, RDMA_CM_DESTROYING); mutex_unlock(&conn_id->handler_mutex); err1: mutex_unlock(&listen_id->handler_mutex); if (conn_id) rdma_destroy_id(&conn_id->id); return ret; } Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler The code that resolves the passive side source MAC within the rdma_cm connection request handler was both redundant and buggy, so remove it. It was redundant since later, when an RC QP is modified to RTR state, the resolution will take place in the ib_core module. It was buggy because this callback also deals with UD SIDR exchange, for which we incorrectly looked at the REQ member of the CM event and dereferenced a random value. Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures") Signed-off-by: Moni Shoua <monis@mellanox.com> Signed-off-by: Or Gerlitz <ogerlitz@mellanox.com> Signed-off-by: Roland Dreier <roland@purestorage.com> CWE ID: CWE-20
static int cma_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event) { struct rdma_id_private *listen_id, *conn_id; struct rdma_cm_event event; int offset, ret; listen_id = cm_id->context; if (!cma_check_req_qp_type(&listen_id->id, ib_event)) return -EINVAL; if (cma_disable_callback(listen_id, RDMA_CM_LISTEN)) return -ECONNABORTED; memset(&event, 0, sizeof event); offset = cma_user_data_offset(listen_id); event.event = RDMA_CM_EVENT_CONNECT_REQUEST; if (ib_event->event == IB_CM_SIDR_REQ_RECEIVED) { conn_id = cma_new_udp_id(&listen_id->id, ib_event); event.param.ud.private_data = ib_event->private_data + offset; event.param.ud.private_data_len = IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE - offset; } else { conn_id = cma_new_conn_id(&listen_id->id, ib_event); cma_set_req_event_data(&event, &ib_event->param.req_rcvd, ib_event->private_data, offset); } if (!conn_id) { ret = -ENOMEM; goto err1; } mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING); ret = cma_acquire_dev(conn_id, listen_id); if (ret) goto err2; conn_id->cm_id.ib = cm_id; cm_id->context = conn_id; cm_id->cm_handler = cma_ib_handler; /* * Protect against the user destroying conn_id from another thread * until we're done accessing it. */ atomic_inc(&conn_id->refcount); ret = conn_id->id.event_handler(&conn_id->id, &event); if (ret) goto err3; /* * Acquire mutex to prevent user executing rdma_destroy_id() * while we're accessing the cm_id. */ mutex_lock(&lock); if (cma_comp(conn_id, RDMA_CM_CONNECT) && (conn_id->id.qp_type != IB_QPT_UD)) ib_send_cm_mra(cm_id, CMA_CM_MRA_SETTING, NULL, 0); mutex_unlock(&lock); mutex_unlock(&conn_id->handler_mutex); mutex_unlock(&listen_id->handler_mutex); cma_deref_id(conn_id); return 0; err3: cma_deref_id(conn_id); /* Destroy the CM ID by returning a non-zero value. */ conn_id->cm_id.ib = NULL; err2: cma_exch(conn_id, RDMA_CM_DESTROYING); mutex_unlock(&conn_id->handler_mutex); err1: mutex_unlock(&listen_id->handler_mutex); if (conn_id) rdma_destroy_id(&conn_id->id); return ret; }
166,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct page *pages[NFS4ACL_MAXPAGES] = {NULL, }; struct nfs_getaclargs args = { .fh = NFS_FH(inode), .acl_pages = pages, .acl_len = buflen, }; struct nfs_getaclres res = { .acl_len = buflen, }; void *resp_buf; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL], .rpc_argp = &args, .rpc_resp = &res, }; int ret = -ENOMEM, npages, i, acl_len = 0; npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT; /* As long as we're doing a round trip to the server anyway, * let's be prepared for a page of acl data. */ if (npages == 0) npages = 1; for (i = 0; i < npages; i++) { pages[i] = alloc_page(GFP_KERNEL); if (!pages[i]) goto out_free; } if (npages > 1) { /* for decoding across pages */ res.acl_scratch = alloc_page(GFP_KERNEL); if (!res.acl_scratch) goto out_free; } args.acl_len = npages * PAGE_SIZE; args.acl_pgbase = 0; /* Let decode_getfacl know not to fail if the ACL data is larger than * the page we send as a guess */ if (buf == NULL) res.acl_flags |= NFS4_ACL_LEN_REQUEST; resp_buf = page_address(pages[0]); dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n", __func__, buf, buflen, npages, args.acl_len); ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0); if (ret) goto out_free; acl_len = res.acl_len - res.acl_data_offset; if (acl_len > args.acl_len) nfs4_write_cached_acl(inode, NULL, acl_len); else nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset, acl_len); if (buf) { ret = -ERANGE; if (acl_len > buflen) goto out_free; _copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len); } ret = acl_len; out_free: for (i = 0; i < npages; i++) if (pages[i]) __free_page(pages[i]); if (res.acl_scratch) __free_page(res.acl_scratch); return ret; } Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached _copy_from_pages() used to copy data from the temporary buffer to the user passed buffer is passed the wrong size parameter when copying data. res.acl_len contains both the bitmap and acl lenghts while acl_len contains the acl length after adjusting for the bitmap size. Signed-off-by: Sachin Prabhu <sprabhu@redhat.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct page *pages[NFS4ACL_MAXPAGES] = {NULL, }; struct nfs_getaclargs args = { .fh = NFS_FH(inode), .acl_pages = pages, .acl_len = buflen, }; struct nfs_getaclres res = { .acl_len = buflen, }; void *resp_buf; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL], .rpc_argp = &args, .rpc_resp = &res, }; int ret = -ENOMEM, npages, i, acl_len = 0; npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT; /* As long as we're doing a round trip to the server anyway, * let's be prepared for a page of acl data. */ if (npages == 0) npages = 1; for (i = 0; i < npages; i++) { pages[i] = alloc_page(GFP_KERNEL); if (!pages[i]) goto out_free; } if (npages > 1) { /* for decoding across pages */ res.acl_scratch = alloc_page(GFP_KERNEL); if (!res.acl_scratch) goto out_free; } args.acl_len = npages * PAGE_SIZE; args.acl_pgbase = 0; /* Let decode_getfacl know not to fail if the ACL data is larger than * the page we send as a guess */ if (buf == NULL) res.acl_flags |= NFS4_ACL_LEN_REQUEST; resp_buf = page_address(pages[0]); dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n", __func__, buf, buflen, npages, args.acl_len); ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0); if (ret) goto out_free; acl_len = res.acl_len - res.acl_data_offset; if (acl_len > args.acl_len) nfs4_write_cached_acl(inode, NULL, acl_len); else nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset, acl_len); if (buf) { ret = -ERANGE; if (acl_len > buflen) goto out_free; _copy_from_pages(buf, pages, res.acl_data_offset, acl_len); } ret = acl_len; out_free: for (i = 0; i < npages; i++) if (pages[i]) __free_page(pages[i]); if (res.acl_scratch) __free_page(res.acl_scratch); return ret; }
165,598
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_compress_check_input(struct snd_compr_params *params) { /* first let's check the buffer parameter's */ if (params->buffer.fragment_size == 0 || params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size) return -EINVAL; /* now codec parameters */ if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX) return -EINVAL; if (params->codec.ch_in == 0 || params->codec.ch_out == 0) return -EINVAL; return 0; } Commit Message: ALSA: compress: fix an integer overflow check I previously added an integer overflow check here but looking at it now, it's still buggy. The bug happens in snd_compr_allocate_buffer(). We multiply ".fragments" and ".fragment_size" and that doesn't overflow but then we save it in an unsigned int so it truncates the high bits away and we allocate a smaller than expected size. Fixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()') Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID:
static int snd_compress_check_input(struct snd_compr_params *params) { /* first let's check the buffer parameter's */ if (params->buffer.fragment_size == 0 || params->buffer.fragments > INT_MAX / params->buffer.fragment_size) return -EINVAL; /* now codec parameters */ if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX) return -EINVAL; if (params->codec.ch_in == 0 || params->codec.ch_out == 0) return -EINVAL; return 0; }
167,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_generic_init) { char *key, *iv; int key_len, iv_len; zval *mcryptind; unsigned char *key_s, *iv_s; int max_key_size, key_size, iv_size; php_mcrypt *pm; int result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); max_key_size = mcrypt_enc_get_key_size(pm->td); iv_size = mcrypt_enc_get_iv_size(pm->td); if (key_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0"); } key_s = emalloc(key_len); memset(key_s, 0, key_len); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); if (key_len > max_key_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size); key_size = max_key_size; } else { key_size = key_len; } memcpy(key_s, key, key_len); if (iv_len != iv_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size); if (iv_len > iv_size) { iv_len = iv_size; } } memcpy(iv_s, iv, iv_len); mcrypt_generic_deinit(pm->td); result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s); /* If this function fails, close the mcrypt module to prevent crashes * when further functions want to access this resource */ if (result < 0) { zend_list_delete(Z_LVAL_P(mcryptind)); switch (result) { case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect"); break; case -4: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error"); break; case -1: default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error"); break; } } else { pm->init = 1; } RETVAL_LONG(result); efree(iv_s); efree(key_s); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_generic_init) { char *key, *iv; int key_len, iv_len; zval *mcryptind; unsigned char *key_s, *iv_s; int max_key_size, key_size, iv_size; php_mcrypt *pm; int result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); max_key_size = mcrypt_enc_get_key_size(pm->td); iv_size = mcrypt_enc_get_iv_size(pm->td); if (key_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0"); } key_s = emalloc(key_len); memset(key_s, 0, key_len); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); if (key_len > max_key_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size); key_size = max_key_size; } else { key_size = key_len; } memcpy(key_s, key, key_len); if (iv_len != iv_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size); if (iv_len > iv_size) { iv_len = iv_size; } } memcpy(iv_s, iv, iv_len); mcrypt_generic_deinit(pm->td); result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s); /* If this function fails, close the mcrypt module to prevent crashes * when further functions want to access this resource */ if (result < 0) { zend_list_delete(Z_LVAL_P(mcryptind)); switch (result) { case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect"); break; case -4: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error"); break; case -1: default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error"); break; } } else { pm->init = 1; } RETVAL_LONG(result); efree(iv_s); efree(key_s); }
167,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; assert((cc%stride)==0); if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; if((cc%stride)!=0) { TIFFErrorExt(tif->tif_clientdata, "horAcc8", "%s", "(cc%stride)!=0"); return 0; } if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } return 1; }
166,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MaybeReportDownloadDeepScanningVerdict( Profile* profile, const GURL& url, const std::string& file_name, const std::string& download_digest_sha256, BinaryUploadService::Result result, DeepScanningClientResponse response) { if (response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::UWS || response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::MALWARE) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256); } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <drubery@chromium.org> Reviewed-by: Karan Bhatia <karandeepb@chromium.org> Reviewed-by: Roger Tawa <rogerta@chromium.org> Cr-Commit-Position: refs/heads/master@{#691371} CWE ID: CWE-416
void MaybeReportDownloadDeepScanningVerdict( Profile* profile, const GURL& url, const std::string& file_name, const std::string& download_digest_sha256, BinaryUploadService::Result result, DeepScanningClientResponse response) { if (result != BinaryUploadService::Result::SUCCESS) return; if (!g_browser_process->local_state()->GetBoolean( policy::policy_prefs::kUnsafeEventsReportingEnabled)) return; if (response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::UWS || response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::MALWARE) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256); } if (response.dlp_scan_verdict().status() == DlpDeepScanningVerdict::SUCCESS) { if (!response.dlp_scan_verdict().triggered_rules().empty()) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnSensitiveDataEvent(response.dlp_scan_verdict(), url, file_name, download_digest_sha256); } } }
172,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; if (cmd & 0x01) off = *delta++; if (cmd & 0x02) off |= *delta++ << 8UL; if (cmd & 0x04) off |= *delta++ << 16UL; if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL); if (cmd & 0x10) len = *delta++; if (cmd & 0x20) len |= *delta++ << 8UL; if (cmd & 0x40) len |= *delta++ << 16UL; if (!len) len = 0x10000; if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; } Commit Message: delta: fix out-of-bounds read of delta When computing the offset and length of the delta base, we repeatedly increment the `delta` pointer without checking whether we have advanced past its end already, which can thus result in an out-of-bounds read. Fix this by repeatedly checking whether we have reached the end. Add a test which would cause Valgrind to produce an error. Reported-by: Riccardo Schirone <rschiron@redhat.com> Test-provided-by: Riccardo Schirone <rschiron@redhat.com> CWE ID: CWE-125
int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
169,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::updateGraphicBufferInMeta( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex); return updateGraphicBufferInMeta_l( portIndex, graphicBuffer, buffer, header, portIndex == kPortIndexOutput /* updateCodecBuffer */); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::updateGraphicBufferInMeta( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex); return updateGraphicBufferInMeta_l( portIndex, graphicBuffer, buffer, header, true /* updateCodecBuffer */); }
174,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char* Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) //should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len+1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
int Track::Info::CopyStr(char* Info::*str, Info& dst_) const if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len + 1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; }
174,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DWORD UnprivilegedProcessDelegate::GetExitCode() { DCHECK(main_task_runner_->BelongsToCurrentThread()); DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } return exit_code; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
DWORD UnprivilegedProcessDelegate::GetExitCode() { DWORD UnprivilegedProcessDelegate::GetProcessId() const { if (worker_process_.IsValid()) { return ::GetProcessId(worker_process_); } else { return 0; } } bool UnprivilegedProcessDelegate::IsPermanentError(int failure_count) const { // Get exit code of the worker process if it is available. DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } // Stop trying to restart the worker process if it exited due to // misconfiguration. return (kMinPermanentErrorExitCode <= exit_code && exit_code <= kMaxPermanentErrorExitCode); }
171,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[1024]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { sprintf (pathName, destFileName, pageNo); GooString *gpageName = new GooString (pathName); int errCode = doc->savePageAs(gpageName, pageNo); if ( errCode != errNone) { delete gpageName; delete gfileName; return false; } delete gpageName; } delete gfileName; return true; } Commit Message: CWE ID: CWE-119
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); int errCode = doc->savePageAs(gpageName, pageNo); if ( errCode != errNone) { delete gpageName; delete gfileName; return false; } delete gpageName; } delete gfileName; return true; }
164,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { php_mcrypt *pm = (php_mcrypt *) rsrc->ptr; if (pm) { mcrypt_generic_deinit(pm->td); mcrypt_module_close(pm->td); efree(pm); pm = NULL; } } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { php_mcrypt *pm = (php_mcrypt *) rsrc->ptr; if (pm) { mcrypt_generic_deinit(pm->td); mcrypt_module_close(pm->td); efree(pm); pm = NULL; } } /* }}} */
167,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PowerLibrary* CrosLibrary::GetPowerLibrary() { return power_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
PowerLibrary* CrosLibrary::GetPowerLibrary() {
170,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::CreateBlock( long long id, long long pos, //absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); //BlockGroup or SimpleBlock if (m_entries_count < 0) //haven't parsed anything yet { assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new BlockEntry*[m_entries_size]; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new BlockEntry*[entries_size]; assert(entries); BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) //BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else //SimpleBlock ID return CreateSimpleBlock(pos, size); } 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 Cluster::CreateBlock( if (status < 0) { // error pFirst = NULL; return status; } if (m_entries_count <= 0) { // empty cluster pFirst = NULL; return 0; } } assert(m_entries); pFirst = m_entries[0]; assert(pFirst); return 0; // success }
174,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC) { char buffer[4096]; char buffer2[4096]; char *buf = buffer, *buf2 = buffer2, *d, *d_url; int l; if (name_len > sizeof(buffer)-2) { buf = estrndup(name, name_len); } else { memcpy(buf, name, name_len); buf[name_len] = 0; } name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { encrypt_return_plain: if (buf != buffer) { efree(buf); } return estrndup(value, value_len); } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto encrypt_return_plain; } } if (strlen(value) <= sizeof(buffer2)-2) { memcpy(buf2, value, value_len); buf2[value_len] = 0; } else { buf2 = estrndup(value, value_len); } value_len = php_url_decode(buf2, value_len); d = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC); d_url = php_url_encode(d, strlen(d), &l); efree(d); if (buf != buffer) { efree(buf); } if (buf2 != buffer2) { efree(buf2); } return d_url; } Commit Message: Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory) CWE ID: CWE-119
char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC) { char *buf, *buf2, *d, *d_url; int l; buf = estrndup(name, name_len); name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { encrypt_return_plain: efree(buf); return estrndup(value, value_len); } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto encrypt_return_plain; } } buf2 = estrndup(value, value_len); value_len = php_url_decode(buf2, value_len); d = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC); d_url = php_url_encode(d, strlen(d), &l); efree(d); efree(buf); efree(buf2); return d_url; }
165,650
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical, struct buffer_head *exbh) { struct inode *inode = mpd->inode; struct address_space *mapping = inode->i_mapping; int blocks = exbh->b_size >> inode->i_blkbits; sector_t pblock = exbh->b_blocknr, cur_logical; struct buffer_head *head, *bh; pgoff_t index, end; struct pagevec pvec; int nr_pages, i; index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits); end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits); cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits); pagevec_init(&pvec, 0); while (index <= end) { /* XXX: optimize tail */ nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; index = page->index; if (index > end) break; index++; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); BUG_ON(!page_has_buffers(page)); bh = page_buffers(page); head = bh; /* skip blocks out of the range */ do { if (cur_logical >= logical) break; cur_logical++; } while ((bh = bh->b_this_page) != head); do { if (cur_logical >= logical + blocks) break; if (buffer_delay(bh) || buffer_unwritten(bh)) { BUG_ON(bh->b_bdev != inode->i_sb->s_bdev); if (buffer_delay(bh)) { clear_buffer_delay(bh); bh->b_blocknr = pblock; } else { /* * unwritten already should have * blocknr assigned. Verify that */ clear_buffer_unwritten(bh); BUG_ON(bh->b_blocknr != pblock); } } else if (buffer_mapped(bh)) BUG_ON(bh->b_blocknr != pblock); cur_logical++; pblock++; } while ((bh = bh->b_this_page) != head); } pagevec_release(&pvec); } } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical, struct buffer_head *exbh) { struct inode *inode = mpd->inode; struct address_space *mapping = inode->i_mapping; int blocks = exbh->b_size >> inode->i_blkbits; sector_t pblock = exbh->b_blocknr, cur_logical; struct buffer_head *head, *bh; pgoff_t index, end; struct pagevec pvec; int nr_pages, i; index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits); end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits); cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits); pagevec_init(&pvec, 0); while (index <= end) { /* XXX: optimize tail */ nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; index = page->index; if (index > end) break; index++; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); BUG_ON(!page_has_buffers(page)); bh = page_buffers(page); head = bh; /* skip blocks out of the range */ do { if (cur_logical >= logical) break; cur_logical++; } while ((bh = bh->b_this_page) != head); do { if (cur_logical >= logical + blocks) break; if (buffer_delay(bh) || buffer_unwritten(bh)) { BUG_ON(bh->b_bdev != inode->i_sb->s_bdev); if (buffer_delay(bh)) { clear_buffer_delay(bh); bh->b_blocknr = pblock; } else { /* * unwritten already should have * blocknr assigned. Verify that */ clear_buffer_unwritten(bh); BUG_ON(bh->b_blocknr != pblock); } } else if (buffer_mapped(bh)) BUG_ON(bh->b_blocknr != pblock); if (buffer_uninit(exbh)) set_buffer_uninit(bh); cur_logical++; pblock++; } while ((bh = bh->b_this_page) != head); } pagevec_release(&pvec); } }
167,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle(iconv_handle, src, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } Commit Message: CWE ID: CWE-200
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; }
164,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id, int do_interlace, int use_update_info) { memset(dp, 0, sizeof *dp); dp->ps = ps; dp->colour_type = COL_FROM_ID(id); dp->bit_depth = DEPTH_FROM_ID(id); if (dp->bit_depth < 1 || dp->bit_depth > 16) internal_error(ps, "internal: bad bit depth"); if (dp->colour_type == 3) dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8; else dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = dp->bit_depth; dp->interlace_type = INTERLACE_FROM_ID(id); check_interlace_type(dp->interlace_type); dp->id = id; /* All the rest are filled in after the read_info: */ dp->w = 0; dp->h = 0; dp->npasses = 0; dp->pixel_size = 0; dp->bit_width = 0; dp->cbRow = 0; dp->do_interlace = do_interlace; dp->is_transparent = 0; dp->speed = ps->speed; dp->use_update_info = use_update_info; dp->npalette = 0; /* Preset the transparent color to black: */ memset(&dp->transparent, 0, sizeof dp->transparent); /* Preset the palette to full intensity/opaque througout: */ memset(dp->palette, 0xff, sizeof dp->palette); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id, int do_interlace, int use_update_info) { memset(dp, 0, sizeof *dp); dp->ps = ps; dp->colour_type = COL_FROM_ID(id); dp->bit_depth = DEPTH_FROM_ID(id); if (dp->bit_depth < 1 || dp->bit_depth > 16) internal_error(ps, "internal: bad bit depth"); if (dp->colour_type == 3) dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8; else dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = dp->bit_depth; dp->interlace_type = INTERLACE_FROM_ID(id); check_interlace_type(dp->interlace_type); dp->id = id; /* All the rest are filled in after the read_info: */ dp->w = 0; dp->h = 0; dp->npasses = 0; dp->pixel_size = 0; dp->bit_width = 0; dp->cbRow = 0; dp->do_interlace = do_interlace; dp->littleendian = 0; dp->is_transparent = 0; dp->speed = ps->speed; dp->use_update_info = use_update_info; dp->npalette = 0; /* Preset the transparent color to black: */ memset(&dp->transparent, 0, sizeof dp->transparent); /* Preset the palette to full intensity/opaque througout: */ memset(dp->palette, 0xff, sizeof dp->palette); }
173,697
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */
167,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void _xml_unparsedEntityDeclHandler(void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName) { xml_parser *parser = (xml_parser *)userData; if (parser && parser->unparsedEntityDeclHandler) { zval *retval, *args[6]; args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding); args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding); args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding); args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding); args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) { zval_ptr_dtor(&retval); } } } Commit Message: CWE ID: CWE-119
void _xml_unparsedEntityDeclHandler(void *userData, void _xml_unparsedEntityDeclHandler(void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName) { xml_parser *parser = (xml_parser *)userData; if (parser && parser->unparsedEntityDeclHandler) { zval *retval, *args[6]; args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding); args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding); args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding); args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding); args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) { zval_ptr_dtor(&retval); } } }
165,043
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) { enabled_bindings_ |= enabled_bindings_flags; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) { enabled_bindings_ |= enabled_bindings_flags; // Keep track of the total bindings accumulated in this process. RenderProcess::current()->AddBindings(enabled_bindings_flags); }
171,018
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end, const uint8_t *name, uint8_t *dst, int dst_size) { int namelen = strlen(name); int len; while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) { len = ff_amf_tag_size(data, data_end); if (len < 0) len = data_end - data; data += len; } if (data_end - data < 3) return -1; data++; for (;;) { int size = bytestream_get_be16(&data); if (!size) break; if (size < 0 || size >= data_end - data) return -1; data += size; if (size == namelen && !memcmp(data-size, name, namelen)) { switch (*data++) { case AMF_DATA_TYPE_NUMBER: snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data))); break; case AMF_DATA_TYPE_BOOL: snprintf(dst, dst_size, "%s", *data ? "true" : "false"); break; case AMF_DATA_TYPE_STRING: len = bytestream_get_be16(&data); av_strlcpy(dst, data, FFMIN(len+1, dst_size)); break; default: return -1; } return 0; } len = ff_amf_tag_size(data, data_end); if (len < 0 || len >= data_end - data) return -1; data += len; } return -1; } Commit Message: avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2 Fixes: out of array accesses Found-by: JunDong Xie of Ant-financial Light-Year Security Lab Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-20
int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end, static int amf_get_field_value2(GetByteContext *gb, const uint8_t *name, uint8_t *dst, int dst_size) { int namelen = strlen(name); int len; while (bytestream2_peek_byte(gb) != AMF_DATA_TYPE_OBJECT && bytestream2_get_bytes_left(gb) > 0) { int ret = amf_tag_skip(gb); if (ret < 0) return -1; } if (bytestream2_get_bytes_left(gb) < 3) return -1; bytestream2_get_byte(gb); for (;;) { int size = bytestream2_get_be16(gb); if (!size) break; if (size < 0 || size >= bytestream2_get_bytes_left(gb)) return -1; bytestream2_skip(gb, size); if (size == namelen && !memcmp(gb->buffer-size, name, namelen)) { switch (bytestream2_get_byte(gb)) { case AMF_DATA_TYPE_NUMBER: snprintf(dst, dst_size, "%g", av_int2double(bytestream2_get_be64(gb))); break; case AMF_DATA_TYPE_BOOL: snprintf(dst, dst_size, "%s", bytestream2_get_byte(gb) ? "true" : "false"); break; case AMF_DATA_TYPE_STRING: len = bytestream2_get_be16(gb); if (dst_size < 1) return -1; if (dst_size < len + 1) len = dst_size - 1; bytestream2_get_buffer(gb, dst, len); dst[len] = 0; break; default: return -1; } return 0; } len = amf_tag_skip(gb); if (len < 0 || bytestream2_get_bytes_left(gb) <= 0) return -1; } return -1; }
168,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { struct zip *intern; zval *self = getThis(); struct zip_stat sb; struct zip_file *zf; zend_long index = -1; zend_long flags = 0; zend_long len = 0; zend_string *filename; zend_string *buffer; int n = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (type == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); } if (sb.size < 1) { RETURN_EMPTY_STRING(); } if (len < 1) { len = sb.size; } if (index >= 0) { zf = zip_fopen_index(intern, index, flags); } else { zf = zip_fopen(intern, ZSTR_VAL(filename), flags); } if (zf == NULL) { RETURN_FALSE; } buffer = zend_string_alloc(len, 0); n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n < 1) { zend_string_free(buffer); RETURN_EMPTY_STRING(); } zip_fclose(zf); ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } /* }}} */ Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom* CWE ID: CWE-190
static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { struct zip *intern; zval *self = getThis(); struct zip_stat sb; struct zip_file *zf; zend_long index = -1; zend_long flags = 0; zend_long len = 0; zend_string *filename; zend_string *buffer; int n = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (type == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); } if (sb.size < 1) { RETURN_EMPTY_STRING(); } if (len < 1) { len = sb.size; } if (index >= 0) { zf = zip_fopen_index(intern, index, flags); } else { zf = zip_fopen(intern, ZSTR_VAL(filename), flags); } if (zf == NULL) { RETURN_FALSE; } buffer = zend_string_safe_alloc(1, len, 0, 0); n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n < 1) { zend_string_free(buffer); RETURN_EMPTY_STRING(); } zip_fclose(zf); ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } /* }}} */
167,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CloudPolicyController::SetState( CloudPolicyController::ControllerState new_state) { state_ = new_state; backend_.reset(); // Discard any pending requests. base::Time now(base::Time::NowFromSystemTime()); base::Time refresh_at; base::Time last_refresh(cache_->last_policy_refresh_time()); if (last_refresh.is_null()) last_refresh = now; bool inform_notifier_done = false; switch (state_) { case STATE_TOKEN_UNMANAGED: notifier_->Inform(CloudPolicySubsystem::UNMANAGED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_UNAVAILABLE: case STATE_TOKEN_VALID: refresh_at = now; break; case STATE_POLICY_VALID: effective_policy_refresh_error_delay_ms_ = kPolicyRefreshErrorDelayInMilliseconds; refresh_at = last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay()); notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_ERROR: notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::BAD_DMTOKEN, PolicyNotifier::POLICY_CONTROLLER); inform_notifier_done = true; case STATE_POLICY_ERROR: if (!inform_notifier_done) { notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); } refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); effective_policy_refresh_error_delay_ms_ = std::min(effective_policy_refresh_error_delay_ms_ * 2, policy_refresh_rate_ms_); break; case STATE_POLICY_UNAVAILABLE: effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_; refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); break; } scheduler_->CancelDelayedWork(); if (!refresh_at.is_null()) { int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0); scheduler_->PostDelayedWork( base::Bind(&CloudPolicyController::DoWork, base::Unretained(this)), delay); } } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CloudPolicyController::SetState( CloudPolicyController::ControllerState new_state) { state_ = new_state; backend_.reset(); // Stop any pending requests. base::Time now(base::Time::NowFromSystemTime()); base::Time refresh_at; base::Time last_refresh(cache_->last_policy_refresh_time()); if (last_refresh.is_null()) last_refresh = now; bool inform_notifier_done = false; switch (state_) { case STATE_TOKEN_UNMANAGED: notifier_->Inform(CloudPolicySubsystem::UNMANAGED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_UNAVAILABLE: case STATE_TOKEN_VALID: refresh_at = now; break; case STATE_POLICY_VALID: effective_policy_refresh_error_delay_ms_ = kPolicyRefreshErrorDelayInMilliseconds; refresh_at = last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay()); notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_ERROR: notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::BAD_DMTOKEN, PolicyNotifier::POLICY_CONTROLLER); inform_notifier_done = true; case STATE_POLICY_ERROR: if (!inform_notifier_done) { notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); } refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); effective_policy_refresh_error_delay_ms_ = std::min(effective_policy_refresh_error_delay_ms_ * 2, policy_refresh_rate_ms_); break; case STATE_POLICY_UNAVAILABLE: effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_; refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); break; } scheduler_->CancelDelayedWork(); if (!refresh_at.is_null()) { int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0); scheduler_->PostDelayedWork( base::Bind(&CloudPolicyController::DoWork, base::Unretained(this)), delay); } }
170,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; } Commit Message: CWE ID: CWE-20
ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_FIXED_SIZE(xXFixesSetCursorNameReq, stuff->nbytes); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; }
165,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LockContentsView::UserState::UserState(AccountId account_id) : account_id(account_id) {} Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
LockContentsView::UserState::UserState(AccountId account_id)
172,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest() : event(false, false), gpu_process_handle(base::kNullProcessHandle) { } 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:
BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest() : event(false, false) { }
170,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); } Commit Message: Limit extent of webstore app to just chrome.google.com/webstore. BUG=93497 TEST=Try installing extensions and apps from the webstore, starting both being initially logged in, and not. Review URL: http://codereview.chromium.org/7719003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); // We also allow the download to be from a small set of trusted paths. if (!download_valid) { for (size_t i = 0; i < arraysize(kAllowedDownloadURLPatterns); i++) { URLPattern pattern(URLPattern::SCHEME_HTTPS, kAllowedDownloadURLPatterns[i]); if (pattern.MatchesURL(download_url)) { download_valid = true; break; } } } GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); }
170,320
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintingDone(bool success) { notify_browser_of_print_failure_ = false; if (!success) LOG(ERROR) << "Failure in OnPrintingDone"; DidFinishPrinting(success ? OK : FAIL_PRINT); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintingDone(bool success) { CHECK_LE(ipc_nesting_level_, 1); notify_browser_of_print_failure_ = false; if (!success) LOG(ERROR) << "Failure in OnPrintingDone"; DidFinishPrinting(success ? OK : FAIL_PRINT); }
171,877
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += ( map->rows - 1 ) * map->pitch; for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } } Commit Message: CWE ID: CWE-189
gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += (unsigned)( ( map->rows - 1 ) * map->pitch ); for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } }
165,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int trigger_fpga_config(void) { int ret = 0; /* if the FPGA is already configured, we do not want to * reconfigure it */ skip = 0; if (fpga_done()) { printf("PCIe FPGA config: skipped\n"); skip = 1; return 0; } if (check_boco2()) { /* we have a BOCO2, this has to be triggered here */ /* make sure the FPGA_can access the EEPROM */ ret = boco_clear_bits(SPI_REG, CFG_EEPROM); if (ret) return ret; /* trigger the config start */ ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B); if (ret) return ret; /* small delay for the pulse */ udelay(10); /* up signal for pulse end */ ret = boco_set_bits(SPI_REG, FPGA_PROG); if (ret) return ret; /* finally, raise INIT_B to remove the config delay */ ret = boco_set_bits(SPI_REG, FPGA_INIT_B); if (ret) return ret; } else { /* we do it the old way, with the gpio pin */ kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1); kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0); /* small delay for the pulse */ udelay(10); kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN); } return 0; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int trigger_fpga_config(void) { int ret = 0; skip = 0; #ifndef CONFIG_KM_FPGA_FORCE_CONFIG /* if the FPGA is already configured, we do not want to * reconfigure it */ skip = 0; if (fpga_done()) { printf("PCIe FPGA config: skipped\n"); skip = 1; return 0; } #endif /* CONFIG_KM_FPGA_FORCE_CONFIG */ if (check_boco2()) { /* we have a BOCO2, this has to be triggered here */ /* make sure the FPGA_can access the EEPROM */ ret = boco_clear_bits(SPI_REG, CFG_EEPROM); if (ret) return ret; /* trigger the config start */ ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B); if (ret) return ret; /* small delay for the pulse */ udelay(10); /* up signal for pulse end */ ret = boco_set_bits(SPI_REG, FPGA_PROG); if (ret) return ret; /* finally, raise INIT_B to remove the config delay */ ret = boco_set_bits(SPI_REG, FPGA_INIT_B); if (ret) return ret; } else { /* we do it the old way, with the gpio pin */ kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1); kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0); /* small delay for the pulse */ udelay(10); kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN); } return 0; }
169,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AppCacheDispatcherHost::AppCacheDispatcherHost( ChromeAppCacheService* appcache_service, int process_id) : BrowserMessageFilter(AppCacheMsgStart), appcache_service_(appcache_service), frontend_proxy_(this), process_id_(process_id) { } Commit Message: AppCache: Use WeakPtr<> to fix a potential uaf bug. BUG=554908 Review URL: https://codereview.chromium.org/1441683004 Cr-Commit-Position: refs/heads/master@{#359930} CWE ID:
AppCacheDispatcherHost::AppCacheDispatcherHost( ChromeAppCacheService* appcache_service, int process_id) : BrowserMessageFilter(AppCacheMsgStart), appcache_service_(appcache_service), frontend_proxy_(this), process_id_(process_id), weak_factory_(this) { }
171,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ShowExtensionInstallDialogImpl( ExtensionInstallPromptShowParams* show_params, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ExtensionInstallDialogView* dialog = new ExtensionInstallDialogView(show_params->profile(), show_params->GetParentWebContents(), delegate, prompt); constrained_window::CreateBrowserModalDialogViews( dialog, show_params->GetParentWindow())->Show(); } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} CWE ID: CWE-17
void ShowExtensionInstallDialogImpl( ExtensionInstallPromptShowParams* show_params, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ExtensionInstallDialogView* dialog = new ExtensionInstallDialogView(show_params->profile(), show_params->GetParentWebContents(), delegate, prompt); if (prompt->ShouldUseTabModalDialog()) { content::WebContents* parent_web_contents = show_params->GetParentWebContents(); if (parent_web_contents) constrained_window::ShowWebModalDialogViews(dialog, parent_web_contents); } else { constrained_window::CreateBrowserModalDialogViews( dialog, show_params->GetParentWindow()) ->Show(); } }
172,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int iwgif_read_image(struct iwgifrcontext *rctx) { int retval=0; struct lzwdeccontext d; size_t subblocksize; int has_local_ct; int local_ct_size; unsigned int root_codesize; if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; rctx->image_left = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->image_top = (int)iw_get_ui16le(&rctx->rbuf[2]); rctx->image_width = (int)iw_get_ui16le(&rctx->rbuf[4]); rctx->image_height = (int)iw_get_ui16le(&rctx->rbuf[6]); rctx->interlaced = (int)((rctx->rbuf[8]>>6)&0x01); has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); rctx->colortable.num_entries = 1<<(1+local_ct_size); } if(has_local_ct) { if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; } if(rctx->has_transparency) { rctx->colortable.entry[rctx->trans_color_index].a = 0; } if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; root_codesize = (unsigned int)rctx->rbuf[0]; if(root_codesize<2 || root_codesize>11) { iw_set_error(rctx->ctx,"Invalid LZW minimum code size"); goto done; } if(!iwgif_init_screen(rctx)) goto done; rctx->total_npixels = (size_t)rctx->image_width * (size_t)rctx->image_height; if(!iwgif_make_row_pointers(rctx)) goto done; lzw_init(&d,root_codesize); lzw_clear(&d); while(1) { if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; subblocksize = (size_t)rctx->rbuf[0]; if(subblocksize==0) break; if(!iwgif_read(rctx,rctx->rbuf,subblocksize)) goto done; if(!lzw_process_bytes(rctx,&d,rctx->rbuf,subblocksize)) goto done; if(d.eoi_flag) break; if(rctx->pixels_set >= rctx->total_npixels) break; } retval=1; done: return retval; } Commit Message: Fixed a GIF decoding bug (divide by zero) Fixes issue #15 CWE ID: CWE-369
static int iwgif_read_image(struct iwgifrcontext *rctx) { int retval=0; struct lzwdeccontext d; size_t subblocksize; int has_local_ct; int local_ct_size; unsigned int root_codesize; if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; rctx->image_left = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->image_top = (int)iw_get_ui16le(&rctx->rbuf[2]); rctx->image_width = (int)iw_get_ui16le(&rctx->rbuf[4]); rctx->image_height = (int)iw_get_ui16le(&rctx->rbuf[6]); if(rctx->image_width<1 || rctx->image_height<1) { iw_set_error(rctx->ctx, "Invalid image dimensions"); goto done; } rctx->interlaced = (int)((rctx->rbuf[8]>>6)&0x01); has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); rctx->colortable.num_entries = 1<<(1+local_ct_size); } if(has_local_ct) { if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; } if(rctx->has_transparency) { rctx->colortable.entry[rctx->trans_color_index].a = 0; } if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; root_codesize = (unsigned int)rctx->rbuf[0]; if(root_codesize<2 || root_codesize>11) { iw_set_error(rctx->ctx,"Invalid LZW minimum code size"); goto done; } if(!iwgif_init_screen(rctx)) goto done; rctx->total_npixels = (size_t)rctx->image_width * (size_t)rctx->image_height; if(!iwgif_make_row_pointers(rctx)) goto done; lzw_init(&d,root_codesize); lzw_clear(&d); while(1) { if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; subblocksize = (size_t)rctx->rbuf[0]; if(subblocksize==0) break; if(!iwgif_read(rctx,rctx->rbuf,subblocksize)) goto done; if(!lzw_process_bytes(rctx,&d,rctx->rbuf,subblocksize)) goto done; if(d.eoi_flag) break; if(rctx->pixels_set >= rctx->total_npixels) break; } retval=1; done: return retval; }
168,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: modify_policy_2_svc(mpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, NULL, NULL)) { log_unauth("kadm5_modify_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_MODIFY; } else { ret.code = kadm5_modify_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
modify_policy_2_svc(mpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, NULL, NULL)) { log_unauth("kadm5_modify_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_MODIFY; } else { ret.code = kadm5_modify_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void SetUpTestCase() { source_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBlockSize)); reference_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBufferSize)); } 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 SetUpTestCase() { source_data8_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBlockSize)); reference_data8_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBufferSize)); second_pred8_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, 64*64)); source_data16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, kDataBlockSize*sizeof(uint16_t))); reference_data16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, kDataBufferSize*sizeof(uint16_t))); second_pred16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, 64*64*sizeof(uint16_t))); }
174,578
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::DisplayPasskey( const dbus::ObjectPath& device_path, uint32 passkey, uint16 entered) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": DisplayPasskey: " << passkey << " (" << entered << " entered)"; if (entered == 0) UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_DISPLAY_PASSKEY, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); if (entered == 0) pairing_delegate_->DisplayPasskey(this, passkey); pairing_delegate_->KeysEntered(this, entered); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::DisplayPasskey(
171,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { void IBusBusConnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is recovered."; MaybeRestoreConnections(); }
170,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CoordinatorImpl::GetVmRegionsForHeapProfiler( const GetVmRegionsForHeapProfilerCallback& callback) { RequestGlobalMemoryDump( MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, callback); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void CoordinatorImpl::GetVmRegionsForHeapProfiler( const GetVmRegionsForHeapProfilerCallback& callback) { // This merely strips out the |dump_guid| argument. auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t dump_guid, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args( MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); }
172,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == nameAttr) { removeFromRadioButtonGroup(); m_name = value; addToRadioButtonGroup(); HTMLTextFormControlElement::parseAttribute(name, value); } else if (name == autocompleteAttr) { if (equalIgnoringCase(value, "off")) m_autocomplete = Off; else { if (value.isEmpty()) m_autocomplete = Uninitialized; else m_autocomplete = On; } } else if (name == typeAttr) updateType(); else if (name == valueAttr) { if (!hasDirtyValue()) { updatePlaceholderVisibility(false); setNeedsStyleRecalc(); } setFormControlValueMatchesRenderer(false); setNeedsValidityCheck(); m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress; m_inputType->valueAttributeChanged(); } else if (name == checkedAttr) { if (!m_parsingInProgress && m_reflectsCheckedAttribute) { setChecked(!value.isNull()); m_reflectsCheckedAttribute = true; } } else if (name == maxlengthAttr) parseMaxLengthAttribute(value); else if (name == sizeAttr) { int oldSize = m_size; int valueAsInteger = value.toInt(); m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize; if (m_size != oldSize && renderer()) renderer()->setNeedsLayoutAndPrefWidthsRecalc(); } else if (name == altAttr) m_inputType->altAttributeChanged(); else if (name == srcAttr) m_inputType->srcAttributeChanged(); else if (name == usemapAttr || name == accesskeyAttr) { } else if (name == onsearchAttr) { setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value)); } else if (name == resultsAttr) { int oldResults = m_maxResults; m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1; if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0)) lazyReattachIfAttached(); setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::ResultsAttribute); } else if (name == incrementalAttr) { setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::IncrementalAttribute); } else if (name == minAttr) { m_inputType->minOrMaxAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::MinAttribute); } else if (name == maxAttr) { m_inputType->minOrMaxAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::MaxAttribute); } else if (name == multipleAttr) { m_inputType->multipleAttributeChanged(); setNeedsValidityCheck(); } else if (name == stepAttr) { m_inputType->stepAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::StepAttribute); } else if (name == patternAttr) { setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::PatternAttribute); } else if (name == precisionAttr) { setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::PrecisionAttribute); } else if (name == disabledAttr) { HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->disabledAttributeChanged(); } else if (name == readonlyAttr) { HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->readonlyAttributeChanged(); } else if (name == listAttr) { m_hasNonEmptyList = !value.isEmpty(); if (m_hasNonEmptyList) { resetListAttributeTargetObserver(); listAttributeTargetChanged(); } UseCounter::count(document(), UseCounter::ListAttribute); } #if ENABLE(INPUT_SPEECH) else if (name == webkitspeechAttr) { if (renderer()) { detach(); m_inputType->destroyShadowSubtree(); m_inputType->createShadowSubtree(); if (!attached()) attach(); } else { m_inputType->destroyShadowSubtree(); m_inputType->createShadowSubtree(); } setFormControlValueMatchesRenderer(false); setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute); } else if (name == onwebkitspeechchangeAttr) setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value)); #endif else if (name == webkitdirectoryAttr) { HTMLTextFormControlElement::parseAttribute(name, value); UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute); } else HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->attributeChanged(); } Commit Message: Setting input.x-webkit-speech should not cause focus change In r150866, we introduced element()->focus() in destroyShadowSubtree() to retain focus on <input> when its type attribute gets changed. But when x-webkit-speech attribute is changed, the element is detached before calling destroyShadowSubtree() and element()->focus() failed This patch moves detach() after destroyShadowSubtree() to fix the problem. BUG=243818 TEST=fast/forms/input-type-change-focusout.html NOTRY=true Review URL: https://chromiumcodereview.appspot.com/16084005 git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == nameAttr) { removeFromRadioButtonGroup(); m_name = value; addToRadioButtonGroup(); HTMLTextFormControlElement::parseAttribute(name, value); } else if (name == autocompleteAttr) { if (equalIgnoringCase(value, "off")) m_autocomplete = Off; else { if (value.isEmpty()) m_autocomplete = Uninitialized; else m_autocomplete = On; } } else if (name == typeAttr) updateType(); else if (name == valueAttr) { if (!hasDirtyValue()) { updatePlaceholderVisibility(false); setNeedsStyleRecalc(); } setFormControlValueMatchesRenderer(false); setNeedsValidityCheck(); m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress; m_inputType->valueAttributeChanged(); } else if (name == checkedAttr) { if (!m_parsingInProgress && m_reflectsCheckedAttribute) { setChecked(!value.isNull()); m_reflectsCheckedAttribute = true; } } else if (name == maxlengthAttr) parseMaxLengthAttribute(value); else if (name == sizeAttr) { int oldSize = m_size; int valueAsInteger = value.toInt(); m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize; if (m_size != oldSize && renderer()) renderer()->setNeedsLayoutAndPrefWidthsRecalc(); } else if (name == altAttr) m_inputType->altAttributeChanged(); else if (name == srcAttr) m_inputType->srcAttributeChanged(); else if (name == usemapAttr || name == accesskeyAttr) { } else if (name == onsearchAttr) { setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value)); } else if (name == resultsAttr) { int oldResults = m_maxResults; m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1; if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0)) lazyReattachIfAttached(); setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::ResultsAttribute); } else if (name == incrementalAttr) { setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::IncrementalAttribute); } else if (name == minAttr) { m_inputType->minOrMaxAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::MinAttribute); } else if (name == maxAttr) { m_inputType->minOrMaxAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::MaxAttribute); } else if (name == multipleAttr) { m_inputType->multipleAttributeChanged(); setNeedsValidityCheck(); } else if (name == stepAttr) { m_inputType->stepAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::StepAttribute); } else if (name == patternAttr) { setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::PatternAttribute); } else if (name == precisionAttr) { setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::PrecisionAttribute); } else if (name == disabledAttr) { HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->disabledAttributeChanged(); } else if (name == readonlyAttr) { HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->readonlyAttributeChanged(); } else if (name == listAttr) { m_hasNonEmptyList = !value.isEmpty(); if (m_hasNonEmptyList) { resetListAttributeTargetObserver(); listAttributeTargetChanged(); } UseCounter::count(document(), UseCounter::ListAttribute); } #if ENABLE(INPUT_SPEECH) else if (name == webkitspeechAttr) { if (renderer()) { m_inputType->destroyShadowSubtree(); detach(); m_inputType->createShadowSubtree(); if (!attached()) attach(); } else { m_inputType->destroyShadowSubtree(); m_inputType->createShadowSubtree(); } setFormControlValueMatchesRenderer(false); setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute); } else if (name == onwebkitspeechchangeAttr) setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value)); #endif else if (name == webkitdirectoryAttr) { HTMLTextFormControlElement::parseAttribute(name, value); UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute); } else HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->attributeChanged(); }
171,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), Min(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } SkipDXTMipmaps(image, dds_info, 16); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); }
168,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); } Commit Message: Security fix: integer overflow on checking image size Test is left in another CL (codereview.chromiu,.org/11274036) to avoid conflict there. Hope it's fine. BUG=160926 Review URL: https://chromiumcodereview.appspot.com/11410081 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167882 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-190
bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) >= std::numeric_limits<int32>::max() / 4) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); }
170,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int create_fixed_stream_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { struct audioformat *fp; struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; int stream, err; unsigned *rate_table = NULL; fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL); if (!fp) { usb_audio_err(chip, "cannot memdup\n"); return -ENOMEM; } if (fp->nr_rates > MAX_NR_RATES) { kfree(fp); return -EINVAL; } if (fp->nr_rates > 0) { rate_table = kmemdup(fp->rate_table, sizeof(int) * fp->nr_rates, GFP_KERNEL); if (!rate_table) { kfree(fp); return -ENOMEM; } fp->rate_table = rate_table; } stream = (fp->endpoint & USB_DIR_IN) ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK; err = snd_usb_add_audio_stream(chip, stream, fp); if (err < 0) { kfree(fp); kfree(rate_table); return err; } if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber || fp->altset_idx >= iface->num_altsetting) { kfree(fp); kfree(rate_table); return -EINVAL; } alts = &iface->altsetting[fp->altset_idx]; altsd = get_iface_desc(alts); fp->protocol = altsd->bInterfaceProtocol; if (fp->datainterval == 0) fp->datainterval = snd_usb_parse_datainterval(chip, alts); if (fp->maxpacksize == 0) fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize); usb_set_interface(chip->dev, fp->iface, 0); snd_usb_init_pitch(chip, fp->iface, alts, fp); snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max); return 0; } Commit Message: ALSA: usb-audio: Fix NULL dereference in create_fixed_stream_quirk() create_fixed_stream_quirk() may cause a NULL-pointer dereference by accessing the non-existing endpoint when a USB device with a malformed USB descriptor is used. This patch avoids it simply by adding a sanity check of bNumEndpoints before the accesses. Bugzilla: https://bugzilla.suse.com/show_bug.cgi?id=971125 Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID:
static int create_fixed_stream_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { struct audioformat *fp; struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; int stream, err; unsigned *rate_table = NULL; fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL); if (!fp) { usb_audio_err(chip, "cannot memdup\n"); return -ENOMEM; } if (fp->nr_rates > MAX_NR_RATES) { kfree(fp); return -EINVAL; } if (fp->nr_rates > 0) { rate_table = kmemdup(fp->rate_table, sizeof(int) * fp->nr_rates, GFP_KERNEL); if (!rate_table) { kfree(fp); return -ENOMEM; } fp->rate_table = rate_table; } stream = (fp->endpoint & USB_DIR_IN) ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK; err = snd_usb_add_audio_stream(chip, stream, fp); if (err < 0) { kfree(fp); kfree(rate_table); return err; } if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber || fp->altset_idx >= iface->num_altsetting) { kfree(fp); kfree(rate_table); return -EINVAL; } alts = &iface->altsetting[fp->altset_idx]; altsd = get_iface_desc(alts); if (altsd->bNumEndpoints < 1) { kfree(fp); kfree(rate_table); return -EINVAL; } fp->protocol = altsd->bInterfaceProtocol; if (fp->datainterval == 0) fp->datainterval = snd_usb_parse_datainterval(chip, alts); if (fp->maxpacksize == 0) fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize); usb_set_interface(chip->dev, fp->iface, 0); snd_usb_init_pitch(chip, fp->iface, alts, fp); snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max); return 0; }
167,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct tcp_sock_t *tcp_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("callocing this failed"); goto error; } this->sd = -1; this->sd = socket(AF_INET6, SOCK_STREAM, 0); if (this->sd < 0) { ERR("sockect open failed"); goto error; } struct sockaddr_in6 addr; memset(&addr, 0, sizeof addr); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); addr.sin6_addr = in6addr_any; if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("Bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; } Commit Message: SECURITY FIX: Actually restrict the access to the printer to localhost Before, any machine in any network connected by any of the interfaces (as listed by "ifconfig") could access to an IPP-over-USB printer on the assigned port, allowing users on remote machines to print and to access the web configuration interface of a IPP-over-USB printer in contrary to conventional USB printers which are only accessible locally. CWE ID: CWE-264
struct tcp_sock_t *tcp_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("IPv4: callocing this failed"); goto error; } // Open [S]ocket [D]escriptor this->sd = -1; this->sd = socket(AF_INET, SOCK_STREAM, 0); if (this->sd < 0) { ERR("IPv4 socket open failed"); goto error; } // Configure socket params struct sockaddr_in addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(0x7F000001); // Bind to localhost if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("IPv4 bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } // Let kernel over-accept max number of connections if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("IPv4 listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; } struct tcp_sock_t *tcp6_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("IPv6: callocing this failed"); goto error; } this->sd = -1; this->sd = socket(AF_INET6, SOCK_STREAM, 0); if (this->sd < 0) { ERR("Ipv6 socket open failed"); goto error; } struct sockaddr_in6 addr; memset(&addr, 0, sizeof addr); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); addr.sin6_addr = in6addr_loopback; if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("IPv6 bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("IPv6 listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; }
166,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool adapter_enable_disable() { int error; CALL_AND_WAIT(error = bt_interface->enable(), adapter_state_changed); TASSERT(error == BT_STATUS_SUCCESS, "Error enabling Bluetooth: %d", error); TASSERT(adapter_get_state() == BT_STATE_ON, "Adapter did not turn on."); CALL_AND_WAIT(error = bt_interface->disable(), adapter_state_changed); TASSERT(error == BT_STATUS_SUCCESS, "Error disabling Bluetooth: %d", error); TASSERT(adapter_get_state() == BT_STATE_OFF, "Adapter did not turn off."); return true; } 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
bool adapter_enable_disable() { int error; CALL_AND_WAIT(error = bt_interface->enable(false), adapter_state_changed); TASSERT(error == BT_STATUS_SUCCESS, "Error enabling Bluetooth: %d", error); TASSERT(adapter_get_state() == BT_STATE_ON, "Adapter did not turn on."); CALL_AND_WAIT(error = bt_interface->disable(), adapter_state_changed); TASSERT(error == BT_STATUS_SUCCESS, "Error disabling Bluetooth: %d", error); TASSERT(adapter_get_state() == BT_STATE_OFF, "Adapter did not turn off."); return true; }
173,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void InputMethodChangedHandler( void* object, const chromeos::InputMethodDescriptor& current_input_method) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->ChangeCurrentInputMethod(current_input_method); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void InputMethodChangedHandler( // IBusController override. virtual void OnCurrentInputMethodChanged( const input_method::InputMethodDescriptor& current_input_method) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } ChangeCurrentInputMethod(current_input_method); }
170,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t ucma_process_join(struct ucma_file *file, struct rdma_ucm_join_mcast *cmd, int out_len) { struct rdma_ucm_create_id_resp resp; struct ucma_context *ctx; struct ucma_multicast *mc; struct sockaddr *addr; int ret; u8 join_state; if (out_len < sizeof(resp)) return -ENOSPC; addr = (struct sockaddr *) &cmd->addr; if (cmd->addr_size != rdma_addr_size(addr)) return -EINVAL; if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER) join_state = BIT(FULLMEMBER_JOIN); else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER) join_state = BIT(SENDONLY_FULLMEMBER_JOIN); else return -EINVAL; ctx = ucma_get_ctx_dev(file, cmd->id); if (IS_ERR(ctx)) return PTR_ERR(ctx); mutex_lock(&file->mut); mc = ucma_alloc_multicast(ctx); if (!mc) { ret = -ENOMEM; goto err1; } mc->join_state = join_state; mc->uid = cmd->uid; memcpy(&mc->addr, addr, cmd->addr_size); ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr, join_state, mc); if (ret) goto err2; resp.id = mc->id; if (copy_to_user(u64_to_user_ptr(cmd->response), &resp, sizeof(resp))) { ret = -EFAULT; goto err3; } mutex_unlock(&file->mut); ucma_put_ctx(ctx); return 0; err3: rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr); ucma_cleanup_mc_events(mc); err2: mutex_lock(&mut); idr_remove(&multicast_idr, mc->id); mutex_unlock(&mut); list_del(&mc->list); kfree(mc); err1: mutex_unlock(&file->mut); ucma_put_ctx(ctx); return ret; } Commit Message: infiniband: fix a possible use-after-free bug ucma_process_join() will free the new allocated "mc" struct, if there is any error after that, especially the copy_to_user(). But in parallel, ucma_leave_multicast() could find this "mc" through idr_find() before ucma_process_join() frees it, since it is already published. So "mc" could be used in ucma_leave_multicast() after it is been allocated and freed in ucma_process_join(), since we don't refcnt it. Fix this by separating "publish" from ID allocation, so that we can get an ID first and publish it later after copy_to_user(). Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support") Reported-by: Noam Rathaus <noamr@beyondsecurity.com> Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com> Signed-off-by: Jason Gunthorpe <jgg@mellanox.com> CWE ID: CWE-416
static ssize_t ucma_process_join(struct ucma_file *file, struct rdma_ucm_join_mcast *cmd, int out_len) { struct rdma_ucm_create_id_resp resp; struct ucma_context *ctx; struct ucma_multicast *mc; struct sockaddr *addr; int ret; u8 join_state; if (out_len < sizeof(resp)) return -ENOSPC; addr = (struct sockaddr *) &cmd->addr; if (cmd->addr_size != rdma_addr_size(addr)) return -EINVAL; if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER) join_state = BIT(FULLMEMBER_JOIN); else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER) join_state = BIT(SENDONLY_FULLMEMBER_JOIN); else return -EINVAL; ctx = ucma_get_ctx_dev(file, cmd->id); if (IS_ERR(ctx)) return PTR_ERR(ctx); mutex_lock(&file->mut); mc = ucma_alloc_multicast(ctx); if (!mc) { ret = -ENOMEM; goto err1; } mc->join_state = join_state; mc->uid = cmd->uid; memcpy(&mc->addr, addr, cmd->addr_size); ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr, join_state, mc); if (ret) goto err2; resp.id = mc->id; if (copy_to_user(u64_to_user_ptr(cmd->response), &resp, sizeof(resp))) { ret = -EFAULT; goto err3; } mutex_lock(&mut); idr_replace(&multicast_idr, mc, mc->id); mutex_unlock(&mut); mutex_unlock(&file->mut); ucma_put_ctx(ctx); return 0; err3: rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr); ucma_cleanup_mc_events(mc); err2: mutex_lock(&mut); idr_remove(&multicast_idr, mc->id); mutex_unlock(&mut); list_del(&mc->list); kfree(mc); err1: mutex_unlock(&file->mut); ucma_put_ctx(ctx); return ret; }
169,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContents::ImageDownloadCallback::Run, base::Owned(new ImageDownloadCallback(callback)), download_id, 400, url, std::vector<SkBitmap>(), std::vector<gfx::Size>())); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&DidDownloadImage, callback, download_id, url)); return download_id; } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { image_downloader::DownloadResultPtr result = image_downloader::DownloadResult::New(); result->http_status_code = 400; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContentsImpl::OnDidDownloadImage, weak_factory_.GetWeakPtr(), callback, download_id, url, base::Passed(&result))); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&WebContentsImpl::OnDidDownloadImage, weak_factory_.GetWeakPtr(), callback, download_id, url)); return download_id; }
172,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) { if (ComputeVisibleSelectionInDOMTree().IsNone()) return; SetSelection( SelectionInDOMTree::Builder( GetGranularityStrategy()->UpdateExtent(contents_point, frame_)) .SetIsHandleVisible(true) .Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetDoNotClearStrategy(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) { if (ComputeVisibleSelectionInDOMTree().IsNone()) return; SetSelection( SelectionInDOMTree::Builder( GetGranularityStrategy()->UpdateExtent(contents_point, frame_)) .Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetDoNotClearStrategy(true) .SetSetSelectionBy(SetSelectionBy::kUser) .SetShouldShowHandle(true) .Build()); }
171,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SaveTestFileSystem() { GDataRootDirectoryProto root; GDataDirectoryProto* root_dir = root.mutable_gdata_directory(); GDataEntryProto* file_base = root_dir->mutable_gdata_entry(); PlatformFileInfoProto* platform_info = file_base->mutable_file_info(); file_base->set_title("drive"); platform_info->set_is_directory(true); GDataFileProto* file = root_dir->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File1"); platform_info->set_is_directory(false); platform_info->set_size(1048576); GDataDirectoryProto* dir1 = root_dir->add_child_directories(); file_base = dir1->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("Dir1"); platform_info->set_is_directory(true); file = dir1->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File2"); platform_info->set_is_directory(false); platform_info->set_size(555); GDataDirectoryProto* dir2 = dir1->add_child_directories(); file_base = dir2->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("SubDir2"); platform_info->set_is_directory(true); file = dir2->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File3"); platform_info->set_is_directory(false); platform_info->set_size(12345); std::string serialized_proto; ASSERT_TRUE(root.SerializeToString(&serialized_proto)); ASSERT_TRUE(!serialized_proto.empty()); FilePath cache_dir_path = profile_->GetPath().Append( FILE_PATH_LITERAL("GCache/v1/meta/")); ASSERT_TRUE(file_util::CreateDirectory(cache_dir_path)); const int file_size = static_cast<int>(serialized_proto.length()); ASSERT_EQ(file_util::WriteFile(cache_dir_path.Append("file_system.pb"), serialized_proto.data(), file_size), file_size); } Commit Message: gdata: Define the resource ID for the root directory Per the spec, the resource ID for the root directory is defined as "folder:root". Add the resource ID to the root directory in our file system representation so we can look up the root directory by the resource ID. BUG=127697 TEST=add unit tests Review URL: https://chromiumcodereview.appspot.com/10332253 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SaveTestFileSystem() { GDataRootDirectoryProto root; GDataDirectoryProto* root_dir = root.mutable_gdata_directory(); GDataEntryProto* file_base = root_dir->mutable_gdata_entry(); PlatformFileInfoProto* platform_info = file_base->mutable_file_info(); file_base->set_title("drive"); file_base->set_resource_id(kGDataRootDirectoryResourceId); platform_info->set_is_directory(true); GDataFileProto* file = root_dir->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File1"); platform_info->set_is_directory(false); platform_info->set_size(1048576); GDataDirectoryProto* dir1 = root_dir->add_child_directories(); file_base = dir1->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("Dir1"); platform_info->set_is_directory(true); file = dir1->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File2"); platform_info->set_is_directory(false); platform_info->set_size(555); GDataDirectoryProto* dir2 = dir1->add_child_directories(); file_base = dir2->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("SubDir2"); platform_info->set_is_directory(true); file = dir2->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File3"); platform_info->set_is_directory(false); platform_info->set_size(12345); std::string serialized_proto; ASSERT_TRUE(root.SerializeToString(&serialized_proto)); ASSERT_TRUE(!serialized_proto.empty()); FilePath cache_dir_path = profile_->GetPath().Append( FILE_PATH_LITERAL("GCache/v1/meta/")); ASSERT_TRUE(file_util::CreateDirectory(cache_dir_path)); const int file_size = static_cast<int>(serialized_proto.length()); ASSERT_EQ(file_util::WriteFile(cache_dir_path.Append("file_system.pb"), serialized_proto.data(), file_size), file_size); }
170,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppListController::Init(Profile* initial_profile) { if (win8::IsSingleWindowMetroMode()) return; PrefService* prefs = g_browser_process->local_state(); if (prefs->HasPrefPath(prefs::kRestartWithAppList) && prefs->GetBoolean(prefs::kRestartWithAppList)) { prefs->SetBoolean(prefs::kRestartWithAppList, false); AppListController::GetInstance()-> ShowAppListDuringModeSwitch(initial_profile); } AppListController::GetInstance(); ScheduleWarmup(); MigrateAppLauncherEnabledPref(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList)) EnableAppList(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList)) DisableAppList(); } Commit Message: Upgrade old app host to new app launcher on startup This patch is a continuation of https://codereview.chromium.org/16805002/. BUG=248825 Review URL: https://chromiumcodereview.appspot.com/17022015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppListController::Init(Profile* initial_profile) { if (win8::IsSingleWindowMetroMode()) return; PrefService* prefs = g_browser_process->local_state(); if (prefs->HasPrefPath(prefs::kRestartWithAppList) && prefs->GetBoolean(prefs::kRestartWithAppList)) { prefs->SetBoolean(prefs::kRestartWithAppList, false); AppListController::GetInstance()-> ShowAppListDuringModeSwitch(initial_profile); } // Migrate from legacy app launcher if we are on a non-canary and non-chromium // build. #if defined(GOOGLE_CHROME_BUILD) if (!InstallUtil::IsChromeSxSProcess() && !chrome_launcher_support::GetAnyAppHostPath().empty()) { chrome_launcher_support::InstallationState state = chrome_launcher_support::GetAppLauncherInstallationState(); if (state == chrome_launcher_support::NOT_INSTALLED) { // If app_host.exe is found but can't be located in the registry, // skip the migration as this is likely a developer build. return; } else if (state == chrome_launcher_support::INSTALLED_AT_SYSTEM_LEVEL) { chrome_launcher_support::UninstallLegacyAppLauncher( chrome_launcher_support::SYSTEM_LEVEL_INSTALLATION); } else if (state == chrome_launcher_support::INSTALLED_AT_USER_LEVEL) { chrome_launcher_support::UninstallLegacyAppLauncher( chrome_launcher_support::USER_LEVEL_INSTALLATION); } EnableAppList(); } #endif AppListController::GetInstance(); ScheduleWarmup(); MigrateAppLauncherEnabledPref(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList)) EnableAppList(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList)) DisableAppList(); }
171,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; } Commit Message: HID: magicmouse: sanity check report size in raw_event() callback The report passed to us from transport driver could potentially be arbitrarily large, therefore we better sanity-check it so that magicmouse_emit_touch() gets only valid values of raw_id. Cc: stable@vger.kernel.org Reported-by: Steven Vittitoe <scvitti@google.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-119
static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; if (npoints > 15) { hid_warn(hdev, "invalid size value (%d) for TRACKPAD_REPORT_ID\n", size); return 0; } msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; if (npoints > 15) { hid_warn(hdev, "invalid size value (%d) for MOUSE_REPORT_ID\n", size); return 0; } msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; }
166,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int check_line_charstring(void) { char *p = line; while (isspace(*p)) p++; return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p')); } Commit Message: Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char. CWE ID: CWE-119
static int check_line_charstring(void) { char *p = line; while (isspace((unsigned char) *p)) p++; return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p')); }
166,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(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 locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(cppValue); }
171,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } Commit Message: ... CWE ID: CWE-125
MagickExport int LocaleLowercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); }
169,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; PixelPacket *q; register ssize_t i, x; size_t bits; ssize_t j, y; unsigned char code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), Min(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickFalse); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3); SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code])); if (colors.a[code] && image->matte == MagickFalse) /* Correct matte */ image->matte = MagickTrue; q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } SkipDXTMipmaps(image, dds_info, 8); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; PixelPacket *q; register ssize_t i, x; size_t bits; ssize_t j, y; unsigned char code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickFalse); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3); SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code])); if (colors.a[code] && image->matte == MagickFalse) /* Correct matte */ image->matte = MagickTrue; q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,8,exception)); }
168,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void start_auth_request(PgSocket *client, const char *username) { int res; PktBuf *buf; client->auth_user = client->db->auth_user; /* have to fetch user info from db */ client->pool = get_pool(client->db, client->db->auth_user); if (!find_server(client)) { client->wait_for_user_conn = true; return; } slog_noise(client, "Doing auth_conn query"); client->wait_for_user_conn = false; client->wait_for_user = true; if (!sbuf_pause(&client->sbuf)) { release_server(client->link); disconnect_client(client, true, "pause failed"); return; } client->link->ready = 0; res = 0; buf = pktbuf_dynamic(512); if (buf) { pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username); res = pktbuf_send_immediate(buf, client->link); pktbuf_free(buf); /* * Should do instead: * res = pktbuf_send_queued(buf, client->link); * but that needs better integration with SBuf. */ } if (!res) disconnect_server(client->link, false, "unable to send login query"); } Commit Message: Remove too early set of auth_user When query returns 0 rows (user not found), this user stays as login user... Should fix #69. CWE ID: CWE-287
static void start_auth_request(PgSocket *client, const char *username) { int res; PktBuf *buf; /* have to fetch user info from db */ client->pool = get_pool(client->db, client->db->auth_user); if (!find_server(client)) { client->wait_for_user_conn = true; return; } slog_noise(client, "Doing auth_conn query"); client->wait_for_user_conn = false; client->wait_for_user = true; if (!sbuf_pause(&client->sbuf)) { release_server(client->link); disconnect_client(client, true, "pause failed"); return; } client->link->ready = 0; res = 0; buf = pktbuf_dynamic(512); if (buf) { pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username); res = pktbuf_send_immediate(buf, client->link); pktbuf_free(buf); /* * Should do instead: * res = pktbuf_send_queued(buf, client->link); * but that needs better integration with SBuf. */ } if (!res) disconnect_server(client->link, false, "unable to send login query"); }
168,871
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LauncherView::SetAlignment(ShelfAlignment alignment) { if (alignment_ == alignment) return; alignment_ = alignment; UpdateFirstButtonPadding(); LayoutToIdealBounds(); tooltip_->SetArrowLocation(alignment_); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::SetAlignment(ShelfAlignment alignment) { if (alignment_ == alignment) return; alignment_ = alignment; UpdateFirstButtonPadding(); LayoutToIdealBounds(); tooltip_->SetArrowLocation(alignment_); if (overflow_bubble_.get()) overflow_bubble_->Hide(); }
170,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Editor::Transpose() { if (!CanEdit()) //// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in //// "EditorCommand.cpp" return; GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& range = ComputeRangeForTranspose(GetFrame()); if (range.IsNull()) return; const String& text = PlainText(range); if (text.length() != 2) return; const String& transposed = text.Right(1) + text.Left(1); if (DispatchBeforeInputInsertText( EventTargetNodeForDocument(GetFrame().GetDocument()), transposed, InputEvent::InputType::kInsertTranspose, new StaticRangeVector(1, StaticRange::Create(range))) != DispatchEventResult::kNotCanceled) return; if (frame_->GetDocument()->GetFrame() != frame_) return; GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& new_range = ComputeRangeForTranspose(GetFrame()); if (new_range.IsNull()) return; const String& new_text = PlainText(new_range); if (new_text.length() != 2) return; const String& new_transposed = new_text.Right(1) + new_text.Left(1); const SelectionInDOMTree& new_selection = SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build(); if (CreateVisibleSelection(new_selection) != GetFrame().Selection().ComputeVisibleSelectionInDOMTree()) GetFrame().Selection().SetSelection(new_selection); ReplaceSelectionWithText(new_transposed, false, false, InputEvent::InputType::kInsertTranspose); } Commit Message: Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Cr-Commit-Position: refs/heads/master@{#489518} CWE ID:
void Editor::Transpose() { //// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in //// "EditorCommand.cpp" void Transpose(LocalFrame& frame) { Editor& editor = frame.GetEditor(); if (!editor.CanEdit()) return; Document* const document = frame.GetDocument(); document->UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& range = ComputeRangeForTranspose(frame); if (range.IsNull()) return; const String& text = PlainText(range); if (text.length() != 2) return; const String& transposed = text.Right(1) + text.Left(1); if (DispatchBeforeInputInsertText( EventTargetNodeForDocument(document), transposed, InputEvent::InputType::kInsertTranspose, new StaticRangeVector(1, StaticRange::Create(range))) != DispatchEventResult::kNotCanceled) return; // 'beforeinput' event handler may destroy document-> if (frame.GetDocument() != document) return; document->UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& new_range = ComputeRangeForTranspose(frame); if (new_range.IsNull()) return; const String& new_text = PlainText(new_range); if (new_text.length() != 2) return; const String& new_transposed = new_text.Right(1) + new_text.Left(1); const SelectionInDOMTree& new_selection = SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build(); if (CreateVisibleSelection(new_selection) != frame.Selection().ComputeVisibleSelectionInDOMTree()) frame.Selection().SetSelection(new_selection); editor.ReplaceSelectionWithText(new_transposed, false, false, InputEvent::InputType::kInsertTranspose); }
172,011
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = mWidth * mHeight * 3 / 2; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); } Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec Bug: 27833616 Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0 CWE ID: CWE-20
void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { bool SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_U32 frameSize = mWidth * mHeight * 3 / 2; if (outHeader->nAllocLen - outHeader->nOffset < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); return false; } outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = frameSize; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return true; }
174,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_@_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { this->next->mod(this->next, that, pp, display); } 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_@_mod(PNG_CONST image_transform *this,
173,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PermissionsRemoveFunction::RunImpl() { scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, &error_); if (!permissions.get()) return false; const extensions::Extension* extension = GetExtension(); APIPermissionSet apis = permissions->apis(); for (APIPermissionSet::const_iterator i = apis.begin(); i != apis.end(); ++i) { if (!i->info()->supports_optional()) { error_ = ErrorUtils::FormatErrorMessage( kNotWhitelistedError, i->name()); return false; } } const PermissionSet* required = extension->required_permission_set(); scoped_refptr<PermissionSet> intersection( PermissionSet::CreateIntersection(permissions.get(), required)); if (!intersection->IsEmpty()) { error_ = kCantRemoveRequiredPermissionsError; results_ = Remove::Results::Create(false); return false; } PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get()); results_ = Remove::Results::Create(true); return true; } Commit Message: Check prefs before allowing extension file access in the permissions API. R=mpcomplete@chromium.org BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsRemoveFunction::RunImpl() { scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs(); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, prefs->AllowFileAccess(extension_->id()), &error_); if (!permissions.get()) return false; const extensions::Extension* extension = GetExtension(); APIPermissionSet apis = permissions->apis(); for (APIPermissionSet::const_iterator i = apis.begin(); i != apis.end(); ++i) { if (!i->info()->supports_optional()) { error_ = ErrorUtils::FormatErrorMessage( kNotWhitelistedError, i->name()); return false; } } const PermissionSet* required = extension->required_permission_set(); scoped_refptr<PermissionSet> intersection( PermissionSet::CreateIntersection(permissions.get(), required)); if (!intersection->IsEmpty()) { error_ = kCantRemoveRequiredPermissionsError; results_ = Remove::Results::Create(false); return false; } PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get()); results_ = Remove::Results::Create(true); return true; }
171,443
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL) { ALOGV("constructor"); const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != NULL) { mMediaRecorder = service->createMediaRecorder(opPackageName); } if (mMediaRecorder != NULL) { mCurrentState = MEDIA_RECORDER_IDLE; } doCleanUp(); } 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
MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL) { ALOGV("constructor"); const sp<IMediaPlayerService> service(getMediaPlayerService()); if (service != NULL) { mMediaRecorder = service->createMediaRecorder(opPackageName); } if (mMediaRecorder != NULL) { mCurrentState = MEDIA_RECORDER_IDLE; } doCleanUp(); }
173,540
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebPluginDelegateProxy::SendUpdateGeometry( bool bitmaps_changed) { PluginMsg_UpdateGeometry_Param param; param.window_rect = plugin_rect_; param.clip_rect = clip_rect_; param.windowless_buffer0 = TransportDIB::DefaultHandleValue(); param.windowless_buffer1 = TransportDIB::DefaultHandleValue(); param.windowless_buffer_index = back_buffer_index(); param.background_buffer = TransportDIB::DefaultHandleValue(); param.transparent = transparent_; #if defined(OS_POSIX) if (bitmaps_changed) #endif { if (transport_stores_[0].dib.get()) CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(), &param.windowless_buffer0); if (transport_stores_[1].dib.get()) CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(), &param.windowless_buffer1); if (background_store_.dib.get()) CopyTransportDIBHandleForMessage(background_store_.dib->handle(), &param.background_buffer); } IPC::Message* msg; #if defined(OS_WIN) if (UseSynchronousGeometryUpdates()) { msg = new PluginMsg_UpdateGeometrySync(instance_id_, param); } else // NOLINT #endif { msg = new PluginMsg_UpdateGeometry(instance_id_, param); msg->set_unblock(true); } Send(msg); } 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 WebPluginDelegateProxy::SendUpdateGeometry( bool bitmaps_changed) { PluginMsg_UpdateGeometry_Param param; param.window_rect = plugin_rect_; param.clip_rect = clip_rect_; param.windowless_buffer0 = TransportDIB::DefaultHandleValue(); param.windowless_buffer1 = TransportDIB::DefaultHandleValue(); param.windowless_buffer_index = back_buffer_index(); param.background_buffer = TransportDIB::DefaultHandleValue(); param.transparent = transparent_; #if defined(OS_POSIX) if (bitmaps_changed) #endif { if (transport_stores_[0].dib.get()) CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(), &param.windowless_buffer0, channel_host_->peer_pid()); if (transport_stores_[1].dib.get()) CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(), &param.windowless_buffer1, channel_host_->peer_pid()); if (background_store_.dib.get()) CopyTransportDIBHandleForMessage(background_store_.dib->handle(), &param.background_buffer, channel_host_->peer_pid()); } IPC::Message* msg; #if defined(OS_WIN) if (UseSynchronousGeometryUpdates()) { msg = new PluginMsg_UpdateGeometrySync(instance_id_, param); } else // NOLINT #endif { msg = new PluginMsg_UpdateGeometry(instance_id_, param); msg->set_unblock(true); } Send(msg); }
170,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fht16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht16x16_c(in, out, stride, tx_type); } 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
void fht16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void idct16x16_ref(const tran_low_t *in, uint8_t *dest, int stride, int /*tx_type*/) { vpx_idct16x16_256_add_c(in, dest, stride); } void fht16x16_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vp9_fht16x16_c(in, out, stride, tx_type); }
174,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_modify_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_modify_principal((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_modify_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_modify_principal((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: print_attr_string(netdissect_options *ndo, register const u_char *data, u_int length, u_short attr_code) { register u_int i; ND_TCHECK2(data[0],length); switch(attr_code) { case TUNNEL_PASS: if (length < 3) { ND_PRINT((ndo, "%s", tstr)); return; } if (*data && (*data <=0x1F) ) ND_PRINT((ndo, "Tag[%u] ", *data)); else ND_PRINT((ndo, "Tag[Unused] ")); data++; length--; ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data))); data+=2; length-=2; break; case TUNNEL_CLIENT_END: case TUNNEL_SERVER_END: case TUNNEL_PRIV_GROUP: case TUNNEL_ASSIGN_ID: case TUNNEL_CLIENT_AUTH: case TUNNEL_SERVER_AUTH: if (*data <= 0x1F) { if (length < 1) { ND_PRINT((ndo, "%s", tstr)); return; } if (*data) ND_PRINT((ndo, "Tag[%u] ", *data)); else ND_PRINT((ndo, "Tag[Unused] ")); data++; length--; } break; case EGRESS_VLAN_NAME: ND_PRINT((ndo, "%s (0x%02x) ", tok2str(rfc4675_tagged,"Unknown tag",*data), *data)); data++; length--; break; } for (i=0; *data && i < length ; i++, data++) ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data)); return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: CVE-2017-13032/RADIUS: Check whether a byte exists before testing its value. Reverse the test in a for loop to test the length before testing whether we have a null byte. This fixes a buffer over-read discovered by Bhargava Shastry. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Clean up other length tests while we're at it. CWE ID: CWE-125
print_attr_string(netdissect_options *ndo, register const u_char *data, u_int length, u_short attr_code) { register u_int i; ND_TCHECK2(data[0],length); switch(attr_code) { case TUNNEL_PASS: if (length < 3) goto trunc; if (*data && (*data <=0x1F) ) ND_PRINT((ndo, "Tag[%u] ", *data)); else ND_PRINT((ndo, "Tag[Unused] ")); data++; length--; ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data))); data+=2; length-=2; break; case TUNNEL_CLIENT_END: case TUNNEL_SERVER_END: case TUNNEL_PRIV_GROUP: case TUNNEL_ASSIGN_ID: case TUNNEL_CLIENT_AUTH: case TUNNEL_SERVER_AUTH: if (*data <= 0x1F) { if (length < 1) goto trunc; if (*data) ND_PRINT((ndo, "Tag[%u] ", *data)); else ND_PRINT((ndo, "Tag[Unused] ")); data++; length--; } break; case EGRESS_VLAN_NAME: if (length < 1) goto trunc; ND_PRINT((ndo, "%s (0x%02x) ", tok2str(rfc4675_tagged,"Unknown tag",*data), *data)); data++; length--; break; } for (i=0; i < length && *data; i++, data++) ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data)); return; trunc: ND_PRINT((ndo, "%s", tstr)); }
167,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int gs_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct gs_usb *dev; int rc = -ENOMEM; unsigned int icount, i; struct gs_host_config hconf = { .byte_order = 0x0000beef, }; struct gs_device_config dconf; /* send host config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_sndctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_HOST_FORMAT, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &hconf, sizeof(hconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't send data format (err=%d)\n", rc); return rc; } /* read device config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_rcvctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_DEVICE_CONFIG, USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &dconf, sizeof(dconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n", rc); return rc; } icount = dconf.icount + 1; dev_info(&intf->dev, "Configuring for %d interfaces\n", icount); if (icount > GS_MAX_INTF) { dev_err(&intf->dev, "Driver cannot handle more that %d CAN interfaces\n", GS_MAX_INTF); return -EINVAL; } dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; init_usb_anchor(&dev->rx_submitted); atomic_set(&dev->active_channels, 0); usb_set_intfdata(intf, dev); dev->udev = interface_to_usbdev(intf); for (i = 0; i < icount; i++) { dev->canch[i] = gs_make_candev(i, intf, &dconf); if (IS_ERR_OR_NULL(dev->canch[i])) { /* save error code to return later */ rc = PTR_ERR(dev->canch[i]); /* on failure destroy previously created candevs */ icount = i; for (i = 0; i < icount; i++) gs_destroy_candev(dev->canch[i]); usb_kill_anchored_urbs(&dev->rx_submitted); kfree(dev); return rc; } dev->canch[i]->parent = dev; } return 0; } Commit Message: can: gs_usb: Don't use stack memory for USB transfers Fixes: 05ca5270005c can: gs_usb: add ethtool set_phys_id callback to locate physical device The gs_usb driver is performing USB transfers using buffers allocated on the stack. This causes the driver to not function with vmapped stacks. Instead, allocate memory for the transfer buffers. Signed-off-by: Ethan Zonca <e@ethanzonca.com> Cc: linux-stable <stable@vger.kernel.org> # >= v4.8 Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de> CWE ID: CWE-119
static int gs_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct gs_usb *dev; int rc = -ENOMEM; unsigned int icount, i; struct gs_host_config *hconf; struct gs_device_config *dconf; hconf = kmalloc(sizeof(*hconf), GFP_KERNEL); if (!hconf) return -ENOMEM; hconf->byte_order = 0x0000beef; /* send host config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_sndctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_HOST_FORMAT, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, hconf, sizeof(*hconf), 1000); kfree(hconf); if (rc < 0) { dev_err(&intf->dev, "Couldn't send data format (err=%d)\n", rc); return rc; } dconf = kmalloc(sizeof(*dconf), GFP_KERNEL); if (!dconf) return -ENOMEM; /* read device config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_rcvctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_DEVICE_CONFIG, USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, dconf, sizeof(*dconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n", rc); kfree(dconf); return rc; } icount = dconf->icount + 1; dev_info(&intf->dev, "Configuring for %d interfaces\n", icount); if (icount > GS_MAX_INTF) { dev_err(&intf->dev, "Driver cannot handle more that %d CAN interfaces\n", GS_MAX_INTF); kfree(dconf); return -EINVAL; } dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) { kfree(dconf); return -ENOMEM; } init_usb_anchor(&dev->rx_submitted); atomic_set(&dev->active_channels, 0); usb_set_intfdata(intf, dev); dev->udev = interface_to_usbdev(intf); for (i = 0; i < icount; i++) { dev->canch[i] = gs_make_candev(i, intf, dconf); if (IS_ERR_OR_NULL(dev->canch[i])) { /* save error code to return later */ rc = PTR_ERR(dev->canch[i]); /* on failure destroy previously created candevs */ icount = i; for (i = 0; i < icount; i++) gs_destroy_candev(dev->canch[i]); usb_kill_anchored_urbs(&dev->rx_submitted); kfree(dconf); kfree(dev); return rc; } dev->canch[i]->parent = dev; } kfree(dconf); return 0; }
168,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptPromise Bluetooth::requestDevice(ScriptState* script_state, const RequestDeviceOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_MACOSX) && \ !defined(OS_WIN) context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); #endif CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } if (!service_) { frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest( &service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI))); } auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New(); ConvertRequestDeviceOptions(options, device_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); service_->RequestDevice( std::move(device_options), WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this), WrapPersistent(resolver))); return promise; } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <chrishtr@chromium.org> Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org> Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
ScriptPromise Bluetooth::requestDevice(ScriptState* script_state, const RequestDeviceOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_MACOSX) && \ !defined(OS_WIN) context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); #endif CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } EnsureServiceConnection(); auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New(); ConvertRequestDeviceOptions(options, device_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); service_->RequestDevice( std::move(device_options), WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this), WrapPersistent(resolver))); return promise; }
172,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: __xml_acl_post_process(xmlNode * xml) { xmlNode *cIter = __xml_first_child(xml); xml_private_t *p = xml->_private; if(is_set(p->flags, xpf_created)) { xmlAttr *xIter = NULL; /* Always allow new scaffolding, ie. node with no attributes or only an 'id' */ for (xIter = crm_first_attr(xml); xIter != NULL; xIter = xIter->next) { const char *prop_name = (const char *)xIter->name; if (strcmp(prop_name, XML_ATTR_ID) == 0) { /* Delay the acl check */ continue; } else if(__xml_acl_check(xml, NULL, xpf_acl_write)) { crm_trace("Creation of %s=%s is allowed", crm_element_name(xml), ID(xml)); break; } else { char *path = xml_get_path(xml); crm_trace("Cannot add new node %s at %s", crm_element_name(xml), path); if(xml != xmlDocGetRootElement(xml->doc)) { xmlUnlinkNode(xml); xmlFreeNode(xml); } free(path); return; } } } while (cIter != NULL) { xmlNode *child = cIter; cIter = __xml_next(cIter); /* In case it is free'd */ __xml_acl_post_process(child); } } Commit Message: Fix: acl: Do not delay evaluation of added nodes in some situations It is not appropriate when the node has no children as it is not a placeholder CWE ID: CWE-264
__xml_acl_post_process(xmlNode * xml) { xmlNode *cIter = __xml_first_child(xml); xml_private_t *p = xml->_private; if(is_set(p->flags, xpf_created)) { xmlAttr *xIter = NULL; char *path = xml_get_path(xml); /* Always allow new scaffolding, ie. node with no attributes or only an 'id' * Except in the ACLs section */ for (xIter = crm_first_attr(xml); xIter != NULL; xIter = xIter->next) { const char *prop_name = (const char *)xIter->name; if (strcmp(prop_name, XML_ATTR_ID) == 0 && strstr(path, "/"XML_CIB_TAG_ACLS"/") == NULL) { /* Delay the acl check */ continue; } else if(__xml_acl_check(xml, NULL, xpf_acl_write)) { crm_trace("Creation of %s=%s is allowed", crm_element_name(xml), ID(xml)); break; } else { crm_trace("Cannot add new node %s at %s", crm_element_name(xml), path); if(xml != xmlDocGetRootElement(xml->doc)) { xmlUnlinkNode(xml); xmlFreeNode(xml); } free(path); return; } } free(path); } while (cIter != NULL) { xmlNode *child = cIter; cIter = __xml_next(cIter); /* In case it is free'd */ __xml_acl_post_process(child); } }
166,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::Stop() { if (current_utterance_ && !current_utterance_->extension_id().empty()) { current_utterance_->profile()->GetExtensionEventRouter()-> DispatchEventToExtension( current_utterance_->extension_id(), events::kOnStop, "[]", current_utterance_->profile(), GURL()); } else { GetPlatformImpl()->clear_error(); GetPlatformImpl()->StopSpeaking(); } if (current_utterance_) current_utterance_->set_error(kSpeechInterruptedError); FinishCurrentUtterance(); ClearUtteranceQueue(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::Stop() { double volume = 1.0; if (options->HasKey(constants::kVolumeKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetDouble(constants::kVolumeKey, &volume)); if (volume < 0.0 || volume > 1.0) { error_ = constants::kErrorInvalidVolume; return false; } }
170,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread) { /* When sending a SMTP payload we must detect CRLF. sequences making sure they are sent as CRLF.. instead, as a . on the beginning of a line will be deleted by the server when not part of an EOB terminator and a genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of data by the server */ ssize_t i; ssize_t si; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *scratch = data->state.scratch; char *newscratch = NULL; char *oldscratch = NULL; size_t eob_sent; /* Do we need to allocate a scratch buffer? */ if(!scratch || data->set.crlf) { oldscratch = scratch; scratch = newscratch = malloc(2 * data->set.buffer_size); if(!newscratch) { failf(data, "Failed to alloc scratch buffer!"); return CURLE_OUT_OF_MEMORY; } } /* Have we already sent part of the EOB? */ eob_sent = smtp->eob; /* This loop can be improved by some kind of Boyer-Moore style of approach but that is saved for later... */ for(i = 0, si = 0; i < nread; i++) { if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) { smtp->eob++; /* Is the EOB potentially the terminating CRLF? */ if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob) smtp->trailing_crlf = TRUE; else smtp->trailing_crlf = FALSE; } else if(smtp->eob) { /* A previous substring matched so output that first */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; /* Then compare the first byte */ if(SMTP_EOB[0] == data->req.upload_fromhere[i]) smtp->eob = 1; else smtp->eob = 0; eob_sent = 0; /* Reset the trailing CRLF flag as there was more data */ smtp->trailing_crlf = FALSE; } /* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */ if(SMTP_EOB_FIND_LEN == smtp->eob) { /* Copy the replacement data to the target buffer */ memcpy(&scratch[si], &SMTP_EOB_REPL[eob_sent], SMTP_EOB_REPL_LEN - eob_sent); si += SMTP_EOB_REPL_LEN - eob_sent; smtp->eob = 0; eob_sent = 0; } else if(!smtp->eob) scratch[si++] = data->req.upload_fromhere[i]; } if(smtp->eob - eob_sent) { /* A substring matched before processing ended so output that now */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; } /* Only use the new buffer if we replaced something */ if(si != nread) { /* Upload from the new (replaced) buffer instead */ data->req.upload_fromhere = scratch; /* Save the buffer so it can be freed later */ data->state.scratch = scratch; /* Free the old scratch buffer */ free(oldscratch); /* Set the new amount too */ data->req.upload_present = si; } else free(newscratch); return CURLE_OK; } Commit Message: smtp: use the upload buffer size for scratch buffer malloc ... not the read buffer size, as that can be set smaller and thus cause a buffer overflow! CVE-2018-0500 Reported-by: Peter Wu Bug: https://curl.haxx.se/docs/adv_2018-70a2.html CWE ID: CWE-119
CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread) { /* When sending a SMTP payload we must detect CRLF. sequences making sure they are sent as CRLF.. instead, as a . on the beginning of a line will be deleted by the server when not part of an EOB terminator and a genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of data by the server */ ssize_t i; ssize_t si; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *scratch = data->state.scratch; char *newscratch = NULL; char *oldscratch = NULL; size_t eob_sent; /* Do we need to allocate a scratch buffer? */ if(!scratch || data->set.crlf) { oldscratch = scratch; scratch = newscratch = malloc(2 * UPLOAD_BUFSIZE); if(!newscratch) { failf(data, "Failed to alloc scratch buffer!"); return CURLE_OUT_OF_MEMORY; } } DEBUGASSERT(UPLOAD_BUFSIZE >= nread); /* Have we already sent part of the EOB? */ eob_sent = smtp->eob; /* This loop can be improved by some kind of Boyer-Moore style of approach but that is saved for later... */ for(i = 0, si = 0; i < nread; i++) { if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) { smtp->eob++; /* Is the EOB potentially the terminating CRLF? */ if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob) smtp->trailing_crlf = TRUE; else smtp->trailing_crlf = FALSE; } else if(smtp->eob) { /* A previous substring matched so output that first */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; /* Then compare the first byte */ if(SMTP_EOB[0] == data->req.upload_fromhere[i]) smtp->eob = 1; else smtp->eob = 0; eob_sent = 0; /* Reset the trailing CRLF flag as there was more data */ smtp->trailing_crlf = FALSE; } /* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */ if(SMTP_EOB_FIND_LEN == smtp->eob) { /* Copy the replacement data to the target buffer */ memcpy(&scratch[si], &SMTP_EOB_REPL[eob_sent], SMTP_EOB_REPL_LEN - eob_sent); si += SMTP_EOB_REPL_LEN - eob_sent; smtp->eob = 0; eob_sent = 0; } else if(!smtp->eob) scratch[si++] = data->req.upload_fromhere[i]; } if(smtp->eob - eob_sent) { /* A substring matched before processing ended so output that now */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; } /* Only use the new buffer if we replaced something */ if(si != nread) { /* Upload from the new (replaced) buffer instead */ data->req.upload_fromhere = scratch; /* Save the buffer so it can be freed later */ data->state.scratch = scratch; /* Free the old scratch buffer */ free(oldscratch); /* Set the new amount too */ data->req.upload_present = si; } else free(newscratch); return CURLE_OK; }
169,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ScreenOrientationDispatcherHost::OnUnlockRequest( RenderFrameHost* render_frame_host) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_.get()) return; provider_->UnlockOrientation(); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void ScreenOrientationDispatcherHost::OnUnlockRequest( RenderFrameHost* render_frame_host) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_) return; provider_->UnlockOrientation(); }
171,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask) { char *mask2, *mask_decoded, *mask_decoded2, *mask_decoded3, *mask_decoded4; char *mask_decoded5; const char *dir_separator; int length; time_t seconds; struct tm *date_tmp; mask2 = NULL; mask_decoded = NULL; mask_decoded2 = NULL; mask_decoded3 = NULL; mask_decoded4 = NULL; mask_decoded5 = NULL; dir_separator = weechat_info_get ("dir_separator", ""); if (!dir_separator) return NULL; /* * we first replace directory separator (commonly '/') by \01 because * buffer mask can contain this char, and will be replaced by replacement * char ('_' by default) */ mask2 = weechat_string_replace (mask, dir_separator, "\01"); if (!mask2) goto end; mask_decoded = weechat_buffer_string_replace_local_var (buffer, mask2); if (!mask_decoded) goto end; mask_decoded2 = weechat_string_replace (mask_decoded, dir_separator, weechat_config_string (logger_config_file_replacement_char)); if (!mask_decoded2) goto end; #ifdef __CYGWIN__ mask_decoded3 = weechat_string_replace (mask_decoded2, "\\", weechat_config_string (logger_config_file_replacement_char)); #else mask_decoded3 = strdup (mask_decoded2); #endif /* __CYGWIN__ */ if (!mask_decoded3) goto end; /* restore directory separator */ mask_decoded4 = weechat_string_replace (mask_decoded3, "\01", dir_separator); if (!mask_decoded4) goto end; /* replace date/time specifiers in mask */ length = strlen (mask_decoded4) + 256 + 1; mask_decoded5 = malloc (length); if (!mask_decoded5) goto end; seconds = time (NULL); date_tmp = localtime (&seconds); mask_decoded5[0] = '\0'; strftime (mask_decoded5, length - 1, mask_decoded4, date_tmp); /* convert to lower case? */ if (weechat_config_boolean (logger_config_file_name_lower_case)) weechat_string_tolower (mask_decoded5); if (weechat_logger_plugin->debug) { weechat_printf_date_tags (NULL, 0, "no_log", "%s: buffer = \"%s\", mask = \"%s\", " "decoded mask = \"%s\"", LOGGER_PLUGIN_NAME, weechat_buffer_get_string (buffer, "name"), mask, mask_decoded5); } end: if (mask2) free (mask2); if (mask_decoded) free (mask_decoded); if (mask_decoded2) free (mask_decoded2); if (mask_decoded3) free (mask_decoded3); if (mask_decoded4) free (mask_decoded4); return mask_decoded5; } Commit Message: logger: call strftime before replacing buffer local variables CWE ID: CWE-119
logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask) { char *mask2, *mask3, *mask4, *mask5, *mask6, *mask7; const char *dir_separator; int length; time_t seconds; struct tm *date_tmp; mask2 = NULL; mask3 = NULL; mask4 = NULL; mask5 = NULL; mask6 = NULL; mask7 = NULL; dir_separator = weechat_info_get ("dir_separator", ""); if (!dir_separator) return NULL; /* replace date/time specifiers in mask */ length = strlen (mask) + 256 + 1; mask2 = malloc (length); if (!mask2) goto end; seconds = time (NULL); date_tmp = localtime (&seconds); mask2[0] = '\0'; if (strftime (mask2, length - 1, mask, date_tmp) == 0) mask2[0] = '\0'; /* * we first replace directory separator (commonly '/') by \01 because * buffer mask can contain this char, and will be replaced by replacement * char ('_' by default) */ mask3 = weechat_string_replace (mask2, dir_separator, "\01"); if (!mask3) goto end; mask4 = weechat_buffer_string_replace_local_var (buffer, mask3); if (!mask4) goto end; mask5 = weechat_string_replace (mask4, dir_separator, weechat_config_string (logger_config_file_replacement_char)); if (!mask5) goto end; #ifdef __CYGWIN__ mask6 = weechat_string_replace (mask5, "\\", weechat_config_string (logger_config_file_replacement_char)); #else mask6 = strdup (mask5); #endif /* __CYGWIN__ */ if (!mask6) goto end; /* restore directory separator */ mask7 = weechat_string_replace (mask6, "\01", dir_separator); if (!mask7) goto end; /* convert to lower case? */ if (weechat_config_boolean (logger_config_file_name_lower_case)) weechat_string_tolower (mask7); if (weechat_logger_plugin->debug) { weechat_printf_date_tags (NULL, 0, "no_log", "%s: buffer = \"%s\", mask = \"%s\", " "decoded mask = \"%s\"", LOGGER_PLUGIN_NAME, weechat_buffer_get_string (buffer, "name"), mask, mask7); } end: if (mask2) free (mask2); if (mask3) free (mask3); if (mask4) free (mask4); if (mask5) free (mask5); if (mask6) free (mask6); return mask7; }
167,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TabStyle::TabColors GM2TabStyle::CalculateColors() const { const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider(); constexpr float kMinimumActiveContrastRatio = 6.05f; constexpr float kMinimumInactiveContrastRatio = 4.61f; constexpr float kMinimumHoveredContrastRatio = 5.02f; constexpr float kMinimumPressedContrastRatio = 4.41f; float expected_opacity = 0.0f; if (tab_->IsActive()) { expected_opacity = 1.0f; } else if (tab_->IsSelected()) { expected_opacity = kSelectedTabOpacity; } else if (tab_->mouse_hovered()) { expected_opacity = GetHoverOpacity(); } const SkColor bg_color = color_utils::AlphaBlend( tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE), tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE), expected_opacity); SkColor title_color = tab_->controller()->GetTabForegroundColor( expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color); title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color); const SkColor base_hovered_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER); const SkColor base_pressed_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED); const auto get_color_for_contrast_ratio = [](SkColor fg_color, SkColor bg_color, float contrast_ratio) { const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast( bg_color, fg_color, bg_color, contrast_ratio); return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha); }; const SkColor generated_icon_color = get_color_for_contrast_ratio( title_color, bg_color, tab_->IsActive() ? kMinimumActiveContrastRatio : kMinimumInactiveContrastRatio); const SkColor generated_hovered_color = get_color_for_contrast_ratio( base_hovered_color, bg_color, kMinimumHoveredContrastRatio); const SkColor generated_pressed_color = get_color_for_contrast_ratio( base_pressed_color, bg_color, kMinimumPressedContrastRatio); const SkColor generated_hovered_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_hovered_color); const SkColor generated_pressed_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_pressed_color); return {bg_color, title_color, generated_icon_color, generated_hovered_icon_color, generated_pressed_icon_color, generated_hovered_color, generated_pressed_color}; } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
TabStyle::TabColors GM2TabStyle::CalculateColors() const { const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider(); constexpr float kMinimumActiveContrastRatio = 6.05f; constexpr float kMinimumInactiveContrastRatio = 4.61f; constexpr float kMinimumHoveredContrastRatio = 5.02f; constexpr float kMinimumPressedContrastRatio = 4.41f; float expected_opacity = 0.0f; if (tab_->IsActive()) { expected_opacity = 1.0f; } else if (tab_->IsSelected()) { expected_opacity = kSelectedTabOpacity; } else if (tab_->mouse_hovered()) { expected_opacity = GetHoverOpacity(); } const SkColor bg_color = color_utils::AlphaBlend( GetTabBackgroundColor(TAB_ACTIVE), GetTabBackgroundColor(TAB_INACTIVE), expected_opacity); SkColor title_color = tab_->controller()->GetTabForegroundColor( expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color); title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color); const SkColor base_hovered_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER); const SkColor base_pressed_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED); const auto get_color_for_contrast_ratio = [](SkColor fg_color, SkColor bg_color, float contrast_ratio) { const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast( bg_color, fg_color, bg_color, contrast_ratio); return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha); }; const SkColor generated_icon_color = get_color_for_contrast_ratio( title_color, bg_color, tab_->IsActive() ? kMinimumActiveContrastRatio : kMinimumInactiveContrastRatio); const SkColor generated_hovered_color = get_color_for_contrast_ratio( base_hovered_color, bg_color, kMinimumHoveredContrastRatio); const SkColor generated_pressed_color = get_color_for_contrast_ratio( base_pressed_color, bg_color, kMinimumPressedContrastRatio); const SkColor generated_hovered_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_hovered_color); const SkColor generated_pressed_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_pressed_color); return {bg_color, title_color, generated_icon_color, generated_hovered_icon_color, generated_pressed_icon_color, generated_hovered_color, generated_pressed_color}; }
172,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data. The closest thing to a specification for the contents of the payload data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it is ever a complete ISAKMP message, so don't dissect types we don't have specific code for as a complete ISAKMP message. While we're at it, fix a comment, and clean up printing of V1 Nonce, V2 Authentication payloads, and v2 Notice payloads. This fixes an infinite loop 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-835
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; }
167,925
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::releaseEncoder() { if (!mStarted) { return OMX_ErrorNone; } PVCleanUpVideoEncoder(mHandle); free(mInputFrameData); mInputFrameData = NULL; delete mEncParams; mEncParams = NULL; delete mHandle; mHandle = NULL; mStarted = false; return OMX_ErrorNone; } Commit Message: codecs: handle onReset() for a few encoders Test: Run PoC binaries Bug: 34749392 Bug: 34705519 Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd CWE ID:
OMX_ERRORTYPE SoftMPEG4Encoder::releaseEncoder() { if (mEncParams) { delete mEncParams; mEncParams = NULL; } if (mHandle) { delete mHandle; mHandle = NULL; } return OMX_ErrorNone; }
174,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoundPool::doLoad(sp<Sample>& sample) { ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID()); sample->startLoad(); mDecodeThread->loadSample(sample->sampleID()); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
void SoundPool::doLoad(sp<Sample>& sample) int sampleID; { Mutex::Autolock lock(&mLock); sampleID = ++mNextSampleID; sp<Sample> sample = new Sample(sampleID, fd, offset, length); mSamples.add(sampleID, sample); sample->startLoad(); } // mDecodeThread->loadSample() must be called outside of mLock. // mDecodeThread->loadSample() may block on mDecodeThread message queue space; // the message queue emptying may block on SoundPool::findSample(). // // It theoretically possible that sample loads might decode out-of-order. mDecodeThread->loadSample(sampleID); return sampleID; }
173,960
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: test_standard(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, interlace_type, 0, 0, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; } } return 1; /* keep going */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
test_standard(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, test_standard(png_modifier* const pm, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info); if (fail(pm)) return 0; } } return 1; /* keep going */ }
173,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, struct xdr_buf *xdr, u32 xdr_off, size_t len, int dir) { struct page *page; dma_addr_t dma_addr; if (xdr_off < xdr->head[0].iov_len) { /* This offset is in the head */ xdr_off += (unsigned long)xdr->head[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->head[0].iov_base); } else { xdr_off -= xdr->head[0].iov_len; if (xdr_off < xdr->page_len) { /* This offset is in the page list */ xdr_off += xdr->page_base; page = xdr->pages[xdr_off >> PAGE_SHIFT]; xdr_off &= ~PAGE_MASK; } else { /* This offset is in the tail */ xdr_off -= xdr->page_len; xdr_off += (unsigned long) xdr->tail[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->tail[0].iov_base); } } dma_addr = ib_dma_map_page(xprt->sc_cm_id->device, page, xdr_off, min_t(size_t, PAGE_SIZE, len), dir); return dma_addr; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, /* The client provided a Write list in the Call message. Fill in * the segments in the first Write chunk in the Reply's transport * header with the number of bytes consumed in each segment. * Remaining chunks are returned unused. * * Assumptions: * - Client has provided only one Write chunk */ static void svc_rdma_xdr_encode_write_list(__be32 *rdma_resp, __be32 *wr_ch, unsigned int consumed) { unsigned int nsegs; __be32 *p, *q; /* RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; q = wr_ch; while (*q != xdr_zero) { nsegs = xdr_encode_write_chunk(p, q, consumed); q += 2 + nsegs * rpcrdma_segment_maxsz; p += 2 + nsegs * rpcrdma_segment_maxsz; consumed = 0; } /* Terminate Write list */ *p++ = xdr_zero; /* Reply chunk discriminator; may be replaced later */ *p = xdr_zero; } /* The client provided a Reply chunk in the Call message. Fill in * the segments in the Reply chunk in the Reply message with the * number of bytes consumed in each segment. * * Assumptions: * - Reply can always fit in the provided Reply chunk */ static void svc_rdma_xdr_encode_reply_chunk(__be32 *rdma_resp, __be32 *rp_ch, unsigned int consumed) { __be32 *p; /* Find the Reply chunk in the Reply's xprt header. * RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; /* Skip past Write list */ while (*p++ != xdr_zero) p += 1 + be32_to_cpup(p) * rpcrdma_segment_maxsz; xdr_encode_write_chunk(p, rp_ch, consumed); }
168,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } gdImageWebpCtx(im, out, -1); out->gd_free(out); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to security@libgd.org. CVE-2016-6912 CWE ID: CWE-415
BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, -1); out->gd_free(out); }
168,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CastCastView::CastCastView(CastConfigDelegate* cast_config_delegate) : cast_config_delegate_(cast_config_delegate) { set_background(views::Background::CreateSolidBackground(kBackgroundColor)); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal, 0, kTrayPopupPaddingBetweenItems)); icon_ = new FixedSizedImageView(0, kTrayPopupItemHeight); icon_->SetImage( bundle.GetImageNamed(IDR_AURA_UBER_TRAY_CAST_ENABLED).ToImageSkia()); AddChildView(icon_); label_container_ = new views::View; label_container_->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); title_ = new views::Label; title_->SetHorizontalAlignment(gfx::ALIGN_LEFT); title_->SetFontList(bundle.GetFontList(ui::ResourceBundle::BoldFont)); label_container_->AddChildView(title_); details_ = new views::Label; details_->SetHorizontalAlignment(gfx::ALIGN_LEFT); details_->SetMultiLine(false); details_->SetEnabledColor(kHeaderTextColorNormal); label_container_->AddChildView(details_); AddChildView(label_container_); base::string16 stop_button_text = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_ASH_STATUS_TRAY_CAST_STOP); stop_button_ = new TrayPopupLabelButton(this, stop_button_text); AddChildView(stop_button_); UpdateLabel(); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
CastCastView::CastCastView(CastConfigDelegate* cast_config_delegate) : cast_config_delegate_(cast_config_delegate) { set_background(views::Background::CreateSolidBackground(kBackgroundColor)); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal, 0, kTrayPopupPaddingBetweenItems)); icon_ = new FixedSizedImageView(0, kTrayPopupItemHeight); icon_->SetImage( bundle.GetImageNamed(IDR_AURA_UBER_TRAY_CAST_ENABLED).ToImageSkia()); AddChildView(icon_); label_container_ = new views::View; label_container_->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); title_ = new views::Label; title_->SetHorizontalAlignment(gfx::ALIGN_LEFT); title_->SetFontList(bundle.GetFontList(ui::ResourceBundle::BoldFont)); title_->SetText( bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_UNKNOWN_CAST_TYPE)); label_container_->AddChildView(title_); details_ = new views::Label; details_->SetHorizontalAlignment(gfx::ALIGN_LEFT); details_->SetMultiLine(false); details_->SetEnabledColor(kHeaderTextColorNormal); details_->SetText( bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_UNKNOWN_RECEIVER)); label_container_->AddChildView(details_); AddChildView(label_container_); base::string16 stop_button_text = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_ASH_STATUS_TRAY_CAST_STOP); stop_button_ = new TrayPopupLabelButton(this, stop_button_text); AddChildView(stop_button_); UpdateLabel(); }
171,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } }
166,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mark_trusted_task_done (GObject *source_object, GAsyncResult *res, gpointer user_data) { MarkTrustedJob *job = user_data; g_object_unref (job->file); if (job->done_callback) { job->done_callback (!job_aborted ((CommonJob *) job), job->done_callback_data); } finalize_common ((CommonJob *) job); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
mark_trusted_task_done (GObject *source_object, mark_desktop_file_executable_task_done (GObject *source_object, GAsyncResult *res, gpointer user_data) { MarkTrustedJob *job = user_data; g_object_unref (job->file); if (job->done_callback) { job->done_callback (!job_aborted ((CommonJob *) job), job->done_callback_data); } finalize_common ((CommonJob *) job); }
167,749
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; } Commit Message: CWE ID: CWE-189
JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmallocn(h, line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; }
164,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "PING")) return; reply(nickFromMask(prefix), "PING", param); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP PING request from %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") } } Commit Message: CWE ID: CWE-399
void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &reply) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { reply = param; emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP PING request from %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") } }
164,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; int sum = 0; int off_idx = -1; int off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } Commit Message: CWE ID: CWE-399
static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int32_t offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; uint64_t sum = 0; int off_idx = -1; int64_t off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); /* * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a * 512 byte sector size. We limit the PRDT in this implementation to * a reasonably large 2GiB, which can accommodate the maximum transfer * request for sector sizes up to 32K. */ if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %"PRId64"\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); if (sglist->size > INT32_MAX) { error_report("AHCI Physical Region Descriptor Table describes " "more than 2 GiB.\n"); qemu_sglist_destroy(sglist); r = -1; goto out; } }
164,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Cluster* Cluster::Create( Segment* pSegment, long idx, long long off) { assert(pSegment); assert(off >= 0); const long long element_start = pSegment->m_start + off; Cluster* const pCluster = new Cluster(pSegment, idx, element_start); assert(pCluster); return pCluster; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Cluster* Cluster::Create(
174,256