instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; data.render_process_id = render_process_id_; in_process_host_->AddInstance(instance, data); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; // It's important that we supply the render process ID ourselves since the // message may be coming from a compromised renderer. data.render_process_id = render_process_id_; // 'instance' is possibly invalid. The host must be careful not to trust it. in_process_host_->AddInstance(instance, data); }
172,311
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 ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); thread->AddObserver(phishing_classifier_.get()); thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); } Commit Message: Prevent navigation to chrome-devtools: and chrome-internal: schemas from http BUG=87815 Review URL: http://codereview.chromium.org/7275032 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91002 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); thread->AddObserver(phishing_classifier_.get()); thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } // chrome:, chrome-devtools:, and chrome-internal: pages should not be // accessible by normal content, and should also be unable to script // anything but themselves (to help limit the damage that a corrupt // page could cause). WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme); WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); }
170,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: my_object_dict_of_dicts (MyObject *obj, GHashTable *in, GHashTable **out, GError **error) { *out = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, (GDestroyNotify) g_hash_table_destroy); g_hash_table_foreach (in, hash_foreach_mangle_dict_of_strings, *out); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_dict_of_dicts (MyObject *obj, GHashTable *in,
165,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t *len, struct iovec **iovec, bool compat) { ssize_t ret; *nr_segs = *len; #ifdef CONFIG_COMPAT if (compat) ret = compat_rw_copy_check_uvector(rw, (struct compat_iovec __user *)buf, *nr_segs, UIO_FASTIOV, *iovec, iovec); else #endif ret = rw_copy_check_uvector(rw, (struct iovec __user *)buf, *nr_segs, UIO_FASTIOV, *iovec, iovec); if (ret < 0) return ret; /* len now reflect bytes instead of segs */ *len = ret; return 0; } Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw() the only non-trivial detail is that we do it before rw_verify_area(), so we'd better cap the length ourselves in aio_setup_single_rw() case (for vectored case rw_copy_check_uvector() will do that for us). Signed-off-by: Al Viro <[email protected]> CWE ID:
static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t *len, struct iovec **iovec, bool compat, struct iov_iter *iter) { ssize_t ret; *nr_segs = *len; #ifdef CONFIG_COMPAT if (compat) ret = compat_rw_copy_check_uvector(rw, (struct compat_iovec __user *)buf, *nr_segs, UIO_FASTIOV, *iovec, iovec); else #endif ret = rw_copy_check_uvector(rw, (struct iovec __user *)buf, *nr_segs, UIO_FASTIOV, *iovec, iovec); if (ret < 0) return ret; /* len now reflect bytes instead of segs */ *len = ret; iov_iter_init(iter, rw, *iovec, *nr_segs, *len); return 0; }
170,003
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 DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) { ScopedStateRestorer scoped_state_restorer(this); if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { return false; } gl_->GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size_); int max_sample_count = 0; anti_aliasing_mode_ = kNone; if (use_multisampling) { gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count); anti_aliasing_mode_ = kMSAAExplicitResolve; if (extensions_util_->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) { anti_aliasing_mode_ = kMSAAImplicitResolve; } else if (extensions_util_->SupportsExtension( "GL_CHROMIUM_screen_space_antialiasing")) { anti_aliasing_mode_ = kScreenSpaceAntialiasing; } } storage_texture_supported_ = (web_gl_version_ > kWebGL1 || extensions_util_->SupportsExtension("GL_EXT_texture_storage")) && anti_aliasing_mode_ == kScreenSpaceAntialiasing; sample_count_ = std::min(4, max_sample_count); state_restorer_->SetFramebufferBindingDirty(); gl_->GenFramebuffers(1, &fbo_); gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_); if (WantExplicitResolve()) { gl_->GenFramebuffers(1, &multisample_fbo_); gl_->BindFramebuffer(GL_FRAMEBUFFER, multisample_fbo_); gl_->GenRenderbuffers(1, &multisample_renderbuffer_); } if (!ResizeFramebufferInternal(size)) return false; if (depth_stencil_buffer_) { DCHECK(WantDepthOrStencil()); has_implicit_stencil_buffer_ = !want_stencil_; } if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { return false; } return true; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
bool DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) { ScopedStateRestorer scoped_state_restorer(this); if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { return false; } gl_->GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size_); int max_sample_count = 0; anti_aliasing_mode_ = kNone; if (use_multisampling) { gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count); anti_aliasing_mode_ = kMSAAExplicitResolve; if (extensions_util_->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) { anti_aliasing_mode_ = kMSAAImplicitResolve; } else if (extensions_util_->SupportsExtension( "GL_CHROMIUM_screen_space_antialiasing")) { anti_aliasing_mode_ = kScreenSpaceAntialiasing; } } storage_texture_supported_ = (webgl_version_ > kWebGL1 || extensions_util_->SupportsExtension("GL_EXT_texture_storage")) && anti_aliasing_mode_ == kScreenSpaceAntialiasing; sample_count_ = std::min(4, max_sample_count); state_restorer_->SetFramebufferBindingDirty(); gl_->GenFramebuffers(1, &fbo_); gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_); if (WantExplicitResolve()) { gl_->GenFramebuffers(1, &multisample_fbo_); gl_->BindFramebuffer(GL_FRAMEBUFFER, multisample_fbo_); gl_->GenRenderbuffers(1, &multisample_renderbuffer_); } if (!ResizeFramebufferInternal(size)) return false; if (depth_stencil_buffer_) { DCHECK(WantDepthOrStencil()); has_implicit_stencil_buffer_ = !want_stencil_; } if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { return false; } return true; }
172,293
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 RunMemCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { input_block[j] = rnd.Rand8() - rnd.Rand8(); input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255; } if (i == 0) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = 255; if (i == 1) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = -255; fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { EXPECT_EQ(output_block[j], output_ref_block[j]); EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j])) << "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE"; } } } 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 RunMemCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) { input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_; } if (i == 0) { for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = mask_; } else if (i == 1) { for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = -mask_; } fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { EXPECT_EQ(output_block[j], output_ref_block[j]); EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j])) << "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE"; } } }
174,526
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 DataReductionProxySettings::InitDataReductionProxySettings( PrefService* prefs, DataReductionProxyIOData* io_data, std::unique_ptr<DataReductionProxyService> data_reduction_proxy_service) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(prefs); DCHECK(io_data); DCHECK(io_data->config()); DCHECK(data_reduction_proxy_service); prefs_ = prefs; config_ = io_data->config(); data_reduction_proxy_service_ = std::move(data_reduction_proxy_service); data_reduction_proxy_service_->AddObserver(this); InitPrefMembers(); RecordDataReductionInit(); #if defined(OS_ANDROID) if (spdy_proxy_auth_enabled_.GetValue()) { data_reduction_proxy_service_->compression_stats() ->SetDataUsageReportingEnabled(true); } #endif // defined(OS_ANDROID) for (auto& observer : observers_) observer.OnSettingsInitialized(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void DataReductionProxySettings::InitDataReductionProxySettings( PrefService* prefs, DataReductionProxyIOData* io_data, std::unique_ptr<DataReductionProxyService> data_reduction_proxy_service) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(prefs); DCHECK(io_data); DCHECK(io_data->config()); DCHECK(data_reduction_proxy_service); prefs_ = prefs; config_ = io_data->config(); data_reduction_proxy_service_ = std::move(data_reduction_proxy_service); data_reduction_proxy_service_->AddObserver(this); RecordDataReductionInit(); registrar_.Init(prefs_); registrar_.Add( prefs::kDataSaverEnabled, base::BindRepeating(&DataReductionProxySettings::OnProxyEnabledPrefChange, base::Unretained(this))); #if defined(OS_ANDROID) if (IsDataSaverEnabledByUser(prefs_)) { data_reduction_proxy_service_->compression_stats() ->SetDataUsageReportingEnabled(true); } #endif // defined(OS_ANDROID) for (auto& observer : observers_) observer.OnSettingsInitialized(); }
172,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: asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { struct oabi_flock64 user; struct flock64 kernel; mm_segment_t fs = USER_DS; /* initialized to kill a warning */ unsigned long local_arg = arg; int ret; switch (cmd) { case F_OFD_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_GETLK64: case F_SETLK64: case F_SETLKW64: if (copy_from_user(&user, (struct oabi_flock64 __user *)arg, sizeof(user))) return -EFAULT; kernel.l_type = user.l_type; kernel.l_whence = user.l_whence; kernel.l_start = user.l_start; kernel.l_len = user.l_len; kernel.l_pid = user.l_pid; local_arg = (unsigned long)&kernel; fs = get_fs(); set_fs(KERNEL_DS); } ret = sys_fcntl64(fd, cmd, local_arg); switch (cmd) { case F_GETLK64: if (!ret) { user.l_type = kernel.l_type; user.l_whence = kernel.l_whence; user.l_start = kernel.l_start; user.l_len = kernel.l_len; user.l_pid = kernel.l_pid; if (copy_to_user((struct oabi_flock64 __user *)arg, &user, sizeof(user))) ret = -EFAULT; } case F_SETLK64: case F_SETLKW64: set_fs(fs); } return ret; } Commit Message: [PATCH] arm: fix handling of F_OFD_... in oabi_fcntl64() Cc: [email protected] # 3.15+ Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264
asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, static long do_locks(unsigned int fd, unsigned int cmd, unsigned long arg) { struct flock64 kernel; struct oabi_flock64 user; mm_segment_t fs; long ret; if (copy_from_user(&user, (struct oabi_flock64 __user *)arg, sizeof(user))) return -EFAULT; kernel.l_type = user.l_type; kernel.l_whence = user.l_whence; kernel.l_start = user.l_start; kernel.l_len = user.l_len; kernel.l_pid = user.l_pid; fs = get_fs(); set_fs(KERNEL_DS); ret = sys_fcntl64(fd, cmd, (unsigned long)&kernel); set_fs(fs); if (!ret && (cmd == F_GETLK64 || cmd == F_OFD_GETLK)) { user.l_type = kernel.l_type; user.l_whence = kernel.l_whence; user.l_start = kernel.l_start; user.l_len = kernel.l_len; user.l_pid = kernel.l_pid; if (copy_to_user((struct oabi_flock64 __user *)arg, &user, sizeof(user))) ret = -EFAULT; } return ret; } asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { switch (cmd) { case F_OFD_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_GETLK64: case F_SETLK64: case F_SETLKW64: return do_locks(fd, cmd, arg); default: return sys_fcntl64(fd, cmd, arg); } }
167,458
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: rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; }
169,830
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::FinishCurrentUtterance() { if (current_utterance_) { current_utterance_->FinishAndDestroy(); current_utterance_ = NULL; } } 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::FinishCurrentUtterance() { bool can_enqueue = false; if (options->HasKey(constants::kEnqueueKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetBoolean(constants::kEnqueueKey, &can_enqueue)); }
170,378
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 omx_video::empty_this_buffer_proxy(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { (void)hComp; OMX_U8 *pmem_data_buf = NULL; int push_cnt = 0; unsigned nBufIndex = 0; OMX_ERRORTYPE ret = OMX_ErrorNone; encoder_media_buffer_type *media_buffer = NULL; #ifdef _MSM8974_ int fd = 0; #endif DEBUG_PRINT_LOW("ETBProxy: buffer->pBuffer[%p]", buffer->pBuffer); if (buffer == NULL) { DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid buffer[%p]", buffer); return OMX_ErrorBadParameter; } if (meta_mode_enable && !mUsesColorConversion) { bool met_error = false; nBufIndex = buffer - meta_buffer_hdr; if (nBufIndex >= m_sInPortDef.nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid meta-bufIndex = %u", nBufIndex); return OMX_ErrorBadParameter; } media_buffer = (encoder_media_buffer_type *)meta_buffer_hdr[nBufIndex].pBuffer; if (media_buffer) { if (media_buffer->buffer_type != kMetadataBufferTypeCameraSource && media_buffer->buffer_type != kMetadataBufferTypeGrallocSource) { met_error = true; } else { if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) { if (media_buffer->meta_handle == NULL) met_error = true; else if ((media_buffer->meta_handle->numFds != 1 && media_buffer->meta_handle->numInts != 2)) met_error = true; } } } else met_error = true; if (met_error) { DEBUG_PRINT_ERROR("ERROR: Unkown source/metahandle in ETB call"); post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorBadParameter; } } else { nBufIndex = buffer - ((OMX_BUFFERHEADERTYPE *)m_inp_mem_ptr); if (nBufIndex >= m_sInPortDef.nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid bufIndex = %u", nBufIndex); return OMX_ErrorBadParameter; } } pending_input_buffers++; if (input_flush_progress == true) { post_event ((unsigned long)buffer,0, OMX_COMPONENT_GENERATE_EBD); DEBUG_PRINT_ERROR("ERROR: ETBProxy: Input flush in progress"); return OMX_ErrorNone; } #ifdef _MSM8974_ if (!meta_mode_enable) { fd = m_pInput_pmem[nBufIndex].fd; } #endif #ifdef _ANDROID_ICS_ if (meta_mode_enable && !mUseProxyColorFormat) { struct pmem Input_pmem_info; if (!media_buffer) { DEBUG_PRINT_ERROR("%s: invalid media_buffer",__FUNCTION__); return OMX_ErrorBadParameter; } if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) { Input_pmem_info.buffer = media_buffer; Input_pmem_info.fd = media_buffer->meta_handle->data[0]; #ifdef _MSM8974_ fd = Input_pmem_info.fd; #endif Input_pmem_info.offset = media_buffer->meta_handle->data[1]; Input_pmem_info.size = media_buffer->meta_handle->data[2]; DEBUG_PRINT_LOW("ETB (meta-Camera) fd = %d, offset = %d, size = %d", Input_pmem_info.fd, Input_pmem_info.offset, Input_pmem_info.size); } else { private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle; Input_pmem_info.buffer = media_buffer; Input_pmem_info.fd = handle->fd; #ifdef _MSM8974_ fd = Input_pmem_info.fd; #endif Input_pmem_info.offset = 0; Input_pmem_info.size = handle->size; DEBUG_PRINT_LOW("ETB (meta-gralloc) fd = %d, offset = %d, size = %d", Input_pmem_info.fd, Input_pmem_info.offset, Input_pmem_info.size); } if (dev_use_buf(&Input_pmem_info,PORT_INDEX_IN,0) != true) { DEBUG_PRINT_ERROR("ERROR: in dev_use_buf"); post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorBadParameter; } } else if (meta_mode_enable && !mUsesColorConversion) { if (media_buffer->buffer_type == kMetadataBufferTypeGrallocSource) { private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle; fd = handle->fd; DEBUG_PRINT_LOW("ETB (opaque-gralloc) fd = %d, size = %d", fd, handle->size); } else { DEBUG_PRINT_ERROR("ERROR: Invalid bufferType for buffer with Opaque" " color format"); post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorBadParameter; } } else if (input_use_buffer && !m_use_input_pmem) #else if (input_use_buffer && !m_use_input_pmem) #endif { DEBUG_PRINT_LOW("Heap UseBuffer case, so memcpy the data"); pmem_data_buf = (OMX_U8 *)m_pInput_pmem[nBufIndex].buffer; memcpy (pmem_data_buf, (buffer->pBuffer + buffer->nOffset), buffer->nFilledLen); DEBUG_PRINT_LOW("memcpy() done in ETBProxy for i/p Heap UseBuf"); } else if (mUseProxyColorFormat) { fd = m_pInput_pmem[nBufIndex].fd; DEBUG_PRINT_LOW("ETB (color-converted) fd = %d, size = %u", fd, (unsigned int)buffer->nFilledLen); } else if (m_sInPortDef.format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { if (!dev_color_align(buffer, m_sInPortDef.format.video.nFrameWidth, m_sInPortDef.format.video.nFrameHeight)) { DEBUG_PRINT_ERROR("Failed to adjust buffer color"); post_event((unsigned long)buffer, 0, OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorUndefined; } } #ifdef _MSM8974_ if (dev_empty_buf(buffer, pmem_data_buf,nBufIndex,fd) != true) #else if (dev_empty_buf(buffer, pmem_data_buf,0,0) != true) #endif { DEBUG_PRINT_ERROR("ERROR: ETBProxy: dev_empty_buf failed"); #ifdef _ANDROID_ICS_ omx_release_meta_buffer(buffer); #endif post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); /*Generate an async error and move to invalid state*/ pending_input_buffers--; if (hw_overload) { return OMX_ErrorInsufficientResources; } return OMX_ErrorBadParameter; } return ret; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27903498 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVenc problem #3) CRs-Fixed: 1010088 Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3 CWE ID:
OMX_ERRORTYPE omx_video::empty_this_buffer_proxy(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { (void)hComp; OMX_U8 *pmem_data_buf = NULL; int push_cnt = 0; unsigned nBufIndex = 0; OMX_ERRORTYPE ret = OMX_ErrorNone; encoder_media_buffer_type *media_buffer = NULL; #ifdef _MSM8974_ int fd = 0; #endif DEBUG_PRINT_LOW("ETBProxy: buffer->pBuffer[%p]", buffer->pBuffer); if (buffer == NULL) { DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid buffer[%p]", buffer); return OMX_ErrorBadParameter; } if (meta_mode_enable && !mUsesColorConversion) { bool met_error = false; nBufIndex = buffer - meta_buffer_hdr; if (nBufIndex >= m_sInPortDef.nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid meta-bufIndex = %u", nBufIndex); return OMX_ErrorBadParameter; } media_buffer = (encoder_media_buffer_type *)meta_buffer_hdr[nBufIndex].pBuffer; if (media_buffer) { if (media_buffer->buffer_type != kMetadataBufferTypeCameraSource && media_buffer->buffer_type != kMetadataBufferTypeGrallocSource) { met_error = true; } else { if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) { if (media_buffer->meta_handle == NULL) met_error = true; else if ((media_buffer->meta_handle->numFds != 1 && media_buffer->meta_handle->numInts != 2)) met_error = true; } } } else met_error = true; if (met_error) { DEBUG_PRINT_ERROR("ERROR: Unkown source/metahandle in ETB call"); post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorBadParameter; } } else { nBufIndex = buffer - ((OMX_BUFFERHEADERTYPE *)m_inp_mem_ptr); if (nBufIndex >= m_sInPortDef.nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid bufIndex = %u", nBufIndex); return OMX_ErrorBadParameter; } } pending_input_buffers++; if (input_flush_progress == true) { post_event ((unsigned long)buffer,0, OMX_COMPONENT_GENERATE_EBD); DEBUG_PRINT_ERROR("ERROR: ETBProxy: Input flush in progress"); return OMX_ErrorNone; } #ifdef _MSM8974_ if (!meta_mode_enable) { fd = m_pInput_pmem[nBufIndex].fd; } #endif #ifdef _ANDROID_ICS_ if (meta_mode_enable && !mUseProxyColorFormat) { struct pmem Input_pmem_info; if (!media_buffer) { DEBUG_PRINT_ERROR("%s: invalid media_buffer",__FUNCTION__); return OMX_ErrorBadParameter; } if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) { Input_pmem_info.buffer = media_buffer; Input_pmem_info.fd = media_buffer->meta_handle->data[0]; #ifdef _MSM8974_ fd = Input_pmem_info.fd; #endif Input_pmem_info.offset = media_buffer->meta_handle->data[1]; Input_pmem_info.size = media_buffer->meta_handle->data[2]; DEBUG_PRINT_LOW("ETB (meta-Camera) fd = %d, offset = %d, size = %d", Input_pmem_info.fd, Input_pmem_info.offset, Input_pmem_info.size); } else { private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle; Input_pmem_info.buffer = media_buffer; Input_pmem_info.fd = handle->fd; #ifdef _MSM8974_ fd = Input_pmem_info.fd; #endif Input_pmem_info.offset = 0; Input_pmem_info.size = handle->size; DEBUG_PRINT_LOW("ETB (meta-gralloc) fd = %d, offset = %d, size = %d", Input_pmem_info.fd, Input_pmem_info.offset, Input_pmem_info.size); } if (dev_use_buf(&Input_pmem_info,PORT_INDEX_IN,0) != true) { DEBUG_PRINT_ERROR("ERROR: in dev_use_buf"); post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorBadParameter; } } else if (meta_mode_enable && !mUsesColorConversion) { if (media_buffer->buffer_type == kMetadataBufferTypeGrallocSource) { private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle; fd = handle->fd; DEBUG_PRINT_LOW("ETB (opaque-gralloc) fd = %d, size = %d", fd, handle->size); } else { DEBUG_PRINT_ERROR("ERROR: Invalid bufferType for buffer with Opaque" " color format"); post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorBadParameter; } } else if (input_use_buffer && !m_use_input_pmem) #else if (input_use_buffer && !m_use_input_pmem) #endif { DEBUG_PRINT_LOW("Heap UseBuffer case, so memcpy the data"); auto_lock l(m_lock); pmem_data_buf = (OMX_U8 *)m_pInput_pmem[nBufIndex].buffer; if (pmem_data_buf) { memcpy (pmem_data_buf, (buffer->pBuffer + buffer->nOffset), buffer->nFilledLen); } DEBUG_PRINT_LOW("memcpy() done in ETBProxy for i/p Heap UseBuf"); } else if (mUseProxyColorFormat) { fd = m_pInput_pmem[nBufIndex].fd; DEBUG_PRINT_LOW("ETB (color-converted) fd = %d, size = %u", fd, (unsigned int)buffer->nFilledLen); } else if (m_sInPortDef.format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { if (!dev_color_align(buffer, m_sInPortDef.format.video.nFrameWidth, m_sInPortDef.format.video.nFrameHeight)) { DEBUG_PRINT_ERROR("Failed to adjust buffer color"); post_event((unsigned long)buffer, 0, OMX_COMPONENT_GENERATE_EBD); return OMX_ErrorUndefined; } } #ifdef _MSM8974_ if (dev_empty_buf(buffer, pmem_data_buf,nBufIndex,fd) != true) #else if (dev_empty_buf(buffer, pmem_data_buf,0,0) != true) #endif { DEBUG_PRINT_ERROR("ERROR: ETBProxy: dev_empty_buf failed"); #ifdef _ANDROID_ICS_ omx_release_meta_buffer(buffer); #endif post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD); /*Generate an async error and move to invalid state*/ pending_input_buffers--; if (hw_overload) { return OMX_ErrorInsufficientResources; } return OMX_ErrorBadParameter; } return ret; }
173,746
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: SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { struct smb_rqst rqst; int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct kvec iov[1]; struct kvec rsp_iov; unsigned int total_len; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0); if (rc) return rc; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; if (rc) { if (rc != -ENODATA) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, "Send error in read = %d\n", rc); trace_smb3_read_err(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length, rc); } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, 0); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc == -ENODATA ? 0 : rc; } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length); *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, "bad length %d for count %d\n", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } if (*buf) { memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; } Commit Message: cifs: Fix use-after-free in SMB2_read There is a KASAN use-after-free: BUG: KASAN: use-after-free in SMB2_read+0x1136/0x1190 Read of size 8 at addr ffff8880b4e45e50 by task ln/1009 Should not release the 'req' because it will use in the trace. Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging") Signed-off-by: ZhangXiaoxu <[email protected]> Signed-off-by: Steve French <[email protected]> CC: Stable <[email protected]> 4.18+ Reviewed-by: Pavel Shilovsky <[email protected]> CWE ID: CWE-416
SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { struct smb_rqst rqst; int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct kvec iov[1]; struct kvec rsp_iov; unsigned int total_len; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0); if (rc) return rc; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; if (rc) { if (rc != -ENODATA) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, "Send error in read = %d\n", rc); trace_smb3_read_err(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length, rc); } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, 0); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc == -ENODATA ? 0 : rc; } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length); cifs_small_buf_release(req); *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, "bad length %d for count %d\n", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } if (*buf) { memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; }
169,525
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: decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } Commit Message: CVE-2017-13043/BGP: fix decoding of MVPN route types 6 and 7 RFC 6514 Section 4.6 defines the structure for Shared Tree Join (6) and Source Tree Join (7) multicast VPN route types. decode_multicast_vpn() didn't implement the Source AS field of that structure properly, adjust the offsets to put it right. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; }
167,832
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 bochs_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVBochsState *s = bs->opaque; uint32_t i; struct bochs_header bochs; int ret; bs->read_only = 1; // no write support yet ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs)); if (ret < 0) { return ret; } if (strcmp(bochs.magic, HEADER_MAGIC) || strcmp(bochs.type, REDOLOG_TYPE) || strcmp(bochs.subtype, GROWING_TYPE) || ((le32_to_cpu(bochs.version) != HEADER_VERSION) && (le32_to_cpu(bochs.version) != HEADER_V1))) { error_setg(errp, "Image not in Bochs format"); return -EINVAL; } if (le32_to_cpu(bochs.version) == HEADER_V1) { bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512; } else { bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512; } s->catalog_size = le32_to_cpu(bochs.catalog); s->catalog_bitmap = g_malloc(s->catalog_size * 4); ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap, s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4); s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512; s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512; s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; fail: s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; extent_index = offset / s->extent_size; extent_offset = (offset % s->extent_size) / 512; if (s->catalog_bitmap[extent_index] == 0xffffffff) { return -1; /* not allocated */ } bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] * (s->extent_blocks + s->bitmap_blocks)); /* read in bitmap for current extent */ if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8), &bitmap_entry, 1) != 1) { return -1; } if (!((bitmap_entry >> (extent_offset % 8)) & 1)) { return -1; /* not allocated */ } return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset)); } Commit Message: CWE ID: CWE-190
static int bochs_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVBochsState *s = bs->opaque; uint32_t i; struct bochs_header bochs; int ret; bs->read_only = 1; // no write support yet ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs)); if (ret < 0) { return ret; } if (strcmp(bochs.magic, HEADER_MAGIC) || strcmp(bochs.type, REDOLOG_TYPE) || strcmp(bochs.subtype, GROWING_TYPE) || ((le32_to_cpu(bochs.version) != HEADER_VERSION) && (le32_to_cpu(bochs.version) != HEADER_V1))) { error_setg(errp, "Image not in Bochs format"); return -EINVAL; } if (le32_to_cpu(bochs.version) == HEADER_V1) { bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512; } else { bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512; } /* Limit to 1M entries to avoid unbounded allocation. This is what is * needed for the largest image that bximage can create (~8 TB). */ s->catalog_size = le32_to_cpu(bochs.catalog); if (s->catalog_size > 0x100000) { error_setg(errp, "Catalog size is too large"); return -EFBIG; } s->catalog_bitmap = g_malloc(s->catalog_size * 4); ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap, s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4); s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512; s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512; s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; fail: s->extent_size = le32_to_cpu(bochs.extent); if (s->catalog_size < bs->total_sectors / s->extent_size) { error_setg(errp, "Catalog size is too small for this disk size"); ret = -EINVAL; goto fail; } qemu_co_mutex_init(&s->lock); return 0; extent_index = offset / s->extent_size; extent_offset = (offset % s->extent_size) / 512; if (s->catalog_bitmap[extent_index] == 0xffffffff) { return -1; /* not allocated */ } bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] * (s->extent_blocks + s->bitmap_blocks)); /* read in bitmap for current extent */ if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8), &bitmap_entry, 1) != 1) { return -1; } if (!((bitmap_entry >> (extent_offset % 8)) & 1)) { return -1; /* not allocated */ } return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset)); }
165,404
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_scale_16_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_scale_16(pp); this->next->set(this->next, that, pp, pi); } 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_scale_16_set(PNG_CONST image_transform *this, image_transform_png_set_scale_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_scale_16(pp); # if PNG_LIBPNG_VER < 10700 /* libpng will limit the gamma table size: */ that->max_gamma_8 = PNG_MAX_GAMMA_8; # endif this->next->set(this->next, that, pp, pi); }
173,647
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 CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const int kMicrosoftPlatformId = 3; const int kUnicodeBmpEncodingId = 1; const int kUnicodeUcs4EncodingId = 10; if (kHeaderSize > cmap_size) { return false; } int numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } int bestTable = -1; for (int i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef PRINTF_DEBUG printf("best table = %d\n", bestTable); #endif if (bestTable < 0) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset + 2 > cmap_size) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef PRINTF_DEBUG for (int i = 0; i < coverageVec.size(); i += 2) { printf("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } #endif return success; } Commit Message: Reject fonts with invalid ranges in cmap A corrupt or malicious font may have a negative size in its cmap range, which in turn could lead to memory corruption. This patch detects the case and rejects the font, and also includes an assertion in the sparse bit set implementation if we missed any such case. External issue: https://code.google.com/p/android/issues/detail?id=192618 Bug: 26413177 Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2 CWE ID: CWE-20
bool CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const uint16_t kMicrosoftPlatformId = 3; const uint16_t kUnicodeBmpEncodingId = 1; const uint16_t kUnicodeUcs4EncodingId = 10; const uint32_t kNoTable = UINT32_MAX; if (kHeaderSize > cmap_size) { return false; } uint32_t numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } uint32_t bestTable = kNoTable; for (uint32_t i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef PRINTF_DEBUG printf("best table = %d\n", bestTable); #endif if (bestTable == kNoTable) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset > cmap_size - 2) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef PRINTF_DEBUG for (int i = 0; i < coverageVec.size(); i += 2) { printf("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } #endif return success; }
174,233
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 wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { smp_rmb(); return key->reject_error; } return key_validate(key); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); }
167,706
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 ExtensionApiTest::SetUpOnMainThread() { ExtensionBrowserTest::SetUpOnMainThread(); DCHECK(!test_config_.get()) << "Previous test did not clear config state."; test_config_.reset(new base::DictionaryValue()); test_config_->SetString(kTestDataDirectory, net::FilePathToFileURL(test_data_dir_).spec()); test_config_->SetBoolean(kBrowserSideNavigationEnabled, content::IsBrowserSideNavigationEnabled()); extensions::TestGetConfigFunction::set_test_config_state( test_config_.get()); } Commit Message: Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#528187} CWE ID: CWE-200
void ExtensionApiTest::SetUpOnMainThread() { ExtensionBrowserTest::SetUpOnMainThread(); DCHECK(!test_config_.get()) << "Previous test did not clear config state."; test_config_.reset(new base::DictionaryValue()); test_config_->SetString(kTestDataDirectory, net::FilePathToFileURL(test_data_dir_).spec()); test_config_->SetBoolean(kBrowserSideNavigationEnabled, content::IsBrowserSideNavigationEnabled()); if (embedded_test_server()->Started()) { // InitializeEmbeddedTestServer was called before |test_config_| was set. // Set the missing port key. test_config_->SetInteger(kEmbeddedTestServerPort, embedded_test_server()->port()); } extensions::TestGetConfigFunction::set_test_config_state( test_config_.get()); }
172,670
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: BrowserContext* SharedWorkerDevToolsAgentHost::GetBrowserContext() { RenderProcessHost* rph = GetProcess(); return rph ? rph->GetBrowserContext() : nullptr; } 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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
BrowserContext* SharedWorkerDevToolsAgentHost::GetBrowserContext() { if (!worker_host_) return nullptr; RenderProcessHost* rph = RenderProcessHost::FromID(worker_host_->process_id()); return rph ? rph->GetBrowserContext() : nullptr; }
172,788
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 BluetoothDeviceChooserController::PostErrorCallback( blink::mojom::WebBluetoothResult error) { if (!base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(error_callback_, error))) { LOG(WARNING) << "No TaskRunner."; } } 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 <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
void BluetoothDeviceChooserController::PostErrorCallback( WebBluetoothResult error) { if (!base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(error_callback_, error))) { LOG(WARNING) << "No TaskRunner."; } }
172,445
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 HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190
void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); frame_load_request.GetResourceRequest().SetHasUserGesture( Frame::HasTransientUserActivation(GetDocument().GetFrame())); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } }
173,032
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 dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; BN_CTX *ctx = NULL; STACK_OF(ASN1_TYPE) *ndsa = NULL; DSA *dsa = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ASN1_TYPE *t1, *t2; if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen))) goto decerr; if (sk_ASN1_TYPE_num(ndsa) != 2) goto decerr; /*- * Handle Two broken types: * SEQUENCE {parameters, priv_key} * SEQUENCE {pub_key, priv_key} */ t1 = sk_ASN1_TYPE_value(ndsa, 0); t2 = sk_ASN1_TYPE_value(ndsa, 1); if (t1->type == V_ASN1_SEQUENCE) { p8->broken = PKCS8_EMBEDDED_PARAM; pval = t1->value.ptr; } else if (ptype == V_ASN1_SEQUENCE) p8->broken = PKCS8_NS_DB; else goto decerr; if (t2->type != V_ASN1_INTEGER) goto decerr; privkey = t2->value.integer; } else { const unsigned char *q = p; if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER) { p8->broken = PKCS8_NEG_PRIVKEY; ASN1_STRING_clear_free(privkey); if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen))) goto decerr; } if (ptype != V_ASN1_SEQUENCE) goto decerr; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if (!(dsa->pub_key = BN_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!(ctx = BN_CTX_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } } Commit Message: CWE ID:
static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; BN_CTX *ctx = NULL; STACK_OF(ASN1_TYPE) *ndsa = NULL; DSA *dsa = NULL; int ret = 0; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ASN1_TYPE *t1, *t2; if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen))) goto decerr; if (sk_ASN1_TYPE_num(ndsa) != 2) goto decerr; /*- * Handle Two broken types: * SEQUENCE {parameters, priv_key} * SEQUENCE {pub_key, priv_key} */ t1 = sk_ASN1_TYPE_value(ndsa, 0); t2 = sk_ASN1_TYPE_value(ndsa, 1); if (t1->type == V_ASN1_SEQUENCE) { p8->broken = PKCS8_EMBEDDED_PARAM; pval = t1->value.ptr; } else if (ptype == V_ASN1_SEQUENCE) p8->broken = PKCS8_NS_DB; else goto decerr; if (t2->type != V_ASN1_INTEGER) goto decerr; privkey = t2->value.integer; } else { const unsigned char *q = p; if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER) { p8->broken = PKCS8_NEG_PRIVKEY; ASN1_STRING_clear_free(privkey); if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen))) goto decerr; } if (ptype != V_ASN1_SEQUENCE) goto decerr; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if (!(dsa->pub_key = BN_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!(ctx = BN_CTX_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } }
165,253
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: _gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; return session->internals.handshake_header_buffer.packet_length; } ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; } Commit Message: CWE ID: CWE-189
_gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; if (*recv_type != type) { gnutls_assert (); _gnutls_handshake_log ("HSK[%x]: Handshake type mismatch (under attack?)\n", session); return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET; } return session->internals.handshake_header_buffer.packet_length; } ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; }
165,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 RuntimeCustomBindings::GetExtensionViews( const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 2) return; if (!args[0]->IsInt32() || !args[1]->IsString()) return; int browser_window_id = args[0]->Int32Value(); std::string view_type_string = base::ToUpperASCII(*v8::String::Utf8Value(args[1])); ViewType view_type = VIEW_TYPE_INVALID; if (view_type_string == kViewTypeBackgroundPage) { view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; } else if (view_type_string == kViewTypeTabContents) { view_type = VIEW_TYPE_TAB_CONTENTS; } else if (view_type_string == kViewTypePopup) { view_type = VIEW_TYPE_EXTENSION_POPUP; } else if (view_type_string == kViewTypeExtensionDialog) { view_type = VIEW_TYPE_EXTENSION_DIALOG; } else if (view_type_string == kViewTypeAppWindow) { view_type = VIEW_TYPE_APP_WINDOW; } else if (view_type_string == kViewTypeLauncherPage) { view_type = VIEW_TYPE_LAUNCHER_PAGE; } else if (view_type_string == kViewTypePanel) { view_type = VIEW_TYPE_PANEL; } else if (view_type_string != kViewTypeAll) { return; } std::string extension_id = context()->GetExtensionID(); if (extension_id.empty()) return; std::vector<content::RenderFrame*> frames = ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id, view_type); v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate()); int v8_index = 0; for (content::RenderFrame* frame : frames) { if (frame->GetWebFrame()->top() != frame->GetWebFrame()) continue; v8::Local<v8::Context> context = frame->GetWebFrame()->mainWorldScriptContext(); if (!context.IsEmpty()) { v8::Local<v8::Value> window = context->Global(); DCHECK(!window.IsEmpty()); v8_views->Set(v8::Integer::New(args.GetIsolate(), v8_index++), window); } } args.GetReturnValue().Set(v8_views); } Commit Message: Create array of extension views without side effects BUG=608104 Review-Url: https://codereview.chromium.org/1935953002 Cr-Commit-Position: refs/heads/master@{#390961} CWE ID:
void RuntimeCustomBindings::GetExtensionViews( const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 2) return; if (!args[0]->IsInt32() || !args[1]->IsString()) return; int browser_window_id = args[0]->Int32Value(); std::string view_type_string = base::ToUpperASCII(*v8::String::Utf8Value(args[1])); ViewType view_type = VIEW_TYPE_INVALID; if (view_type_string == kViewTypeBackgroundPage) { view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; } else if (view_type_string == kViewTypeTabContents) { view_type = VIEW_TYPE_TAB_CONTENTS; } else if (view_type_string == kViewTypePopup) { view_type = VIEW_TYPE_EXTENSION_POPUP; } else if (view_type_string == kViewTypeExtensionDialog) { view_type = VIEW_TYPE_EXTENSION_DIALOG; } else if (view_type_string == kViewTypeAppWindow) { view_type = VIEW_TYPE_APP_WINDOW; } else if (view_type_string == kViewTypeLauncherPage) { view_type = VIEW_TYPE_LAUNCHER_PAGE; } else if (view_type_string == kViewTypePanel) { view_type = VIEW_TYPE_PANEL; } else if (view_type_string != kViewTypeAll) { return; } std::string extension_id = context()->GetExtensionID(); if (extension_id.empty()) return; std::vector<content::RenderFrame*> frames = ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id, view_type); v8::Local<v8::Context> v8_context = args.GetIsolate()->GetCurrentContext(); v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate()); int v8_index = 0; for (content::RenderFrame* frame : frames) { if (frame->GetWebFrame()->top() != frame->GetWebFrame()) continue; v8::Local<v8::Context> context = frame->GetWebFrame()->mainWorldScriptContext(); if (!context.IsEmpty()) { v8::Local<v8::Value> window = context->Global(); DCHECK(!window.IsEmpty()); v8::Maybe<bool> maybe = v8_views->CreateDataProperty(v8_context, v8_index++, window); DCHECK(maybe.IsJust() && maybe.FromJust()); } } args.GetReturnValue().Set(v8_views); }
172,260
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 rd_build_device_space(struct rd_dev *rd_dev) { u32 i = 0, j, page_offset = 0, sg_per_table, sg_tables, total_sg_needed; u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE / sizeof(struct scatterlist)); struct rd_dev_sg_table *sg_table; struct page *pg; struct scatterlist *sg; if (rd_dev->rd_page_count <= 0) { pr_err("Illegal page count: %u for Ramdisk device\n", rd_dev->rd_page_count); return -EINVAL; } /* Don't need backing pages for NULLIO */ if (rd_dev->rd_flags & RDF_NULLIO) return 0; total_sg_needed = rd_dev->rd_page_count; sg_tables = (total_sg_needed / max_sg_per_table) + 1; sg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL); if (!sg_table) { pr_err("Unable to allocate memory for Ramdisk" " scatterlist tables\n"); return -ENOMEM; } rd_dev->sg_table_array = sg_table; rd_dev->sg_table_count = sg_tables; while (total_sg_needed) { sg_per_table = (total_sg_needed > max_sg_per_table) ? max_sg_per_table : total_sg_needed; sg = kzalloc(sg_per_table * sizeof(struct scatterlist), GFP_KERNEL); if (!sg) { pr_err("Unable to allocate scatterlist array" " for struct rd_dev\n"); return -ENOMEM; } sg_init_table(sg, sg_per_table); sg_table[i].sg_table = sg; sg_table[i].rd_sg_count = sg_per_table; sg_table[i].page_start_offset = page_offset; sg_table[i++].page_end_offset = (page_offset + sg_per_table) - 1; for (j = 0; j < sg_per_table; j++) { pg = alloc_pages(GFP_KERNEL, 0); if (!pg) { pr_err("Unable to allocate scatterlist" " pages for struct rd_dev_sg_table\n"); return -ENOMEM; } sg_assign_page(&sg[j], pg); sg[j].length = PAGE_SIZE; } page_offset += sg_per_table; total_sg_needed -= sg_per_table; } pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u space of" " %u pages in %u tables\n", rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, rd_dev->rd_page_count, rd_dev->sg_table_count); return 0; } Commit Message: target/rd: Refactor rd_build_device_space + rd_release_device_space This patch refactors rd_build_device_space() + rd_release_device_space() into rd_allocate_sgl_table() + rd_release_device_space() so that they may be used seperatly for setup + release of protection information scatterlists. Also add explicit memset of pages within rd_allocate_sgl_table() based upon passed 'init_payload' value. v2 changes: - Drop unused sg_table from rd_release_device_space (Wei) Cc: Martin K. Petersen <[email protected]> Cc: Christoph Hellwig <[email protected]> Cc: Hannes Reinecke <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: Or Gerlitz <[email protected]> Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-264
static int rd_build_device_space(struct rd_dev *rd_dev) static int rd_allocate_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table, u32 total_sg_needed, unsigned char init_payload) { u32 i = 0, j, page_offset = 0, sg_per_table; u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE / sizeof(struct scatterlist)); struct page *pg; struct scatterlist *sg; unsigned char *p; while (total_sg_needed) { sg_per_table = (total_sg_needed > max_sg_per_table) ? max_sg_per_table : total_sg_needed; sg = kzalloc(sg_per_table * sizeof(struct scatterlist), GFP_KERNEL); if (!sg) { pr_err("Unable to allocate scatterlist array" " for struct rd_dev\n"); return -ENOMEM; } sg_init_table(sg, sg_per_table); sg_table[i].sg_table = sg; sg_table[i].rd_sg_count = sg_per_table; sg_table[i].page_start_offset = page_offset; sg_table[i++].page_end_offset = (page_offset + sg_per_table) - 1; for (j = 0; j < sg_per_table; j++) { pg = alloc_pages(GFP_KERNEL, 0); if (!pg) { pr_err("Unable to allocate scatterlist" " pages for struct rd_dev_sg_table\n"); return -ENOMEM; } sg_assign_page(&sg[j], pg); sg[j].length = PAGE_SIZE; p = kmap(pg); memset(p, init_payload, PAGE_SIZE); kunmap(pg); } page_offset += sg_per_table; total_sg_needed -= sg_per_table; } return 0; } static int rd_build_device_space(struct rd_dev *rd_dev) { struct rd_dev_sg_table *sg_table; u32 sg_tables, total_sg_needed; u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE / sizeof(struct scatterlist)); int rc; if (rd_dev->rd_page_count <= 0) { pr_err("Illegal page count: %u for Ramdisk device\n", rd_dev->rd_page_count); return -EINVAL; } /* Don't need backing pages for NULLIO */ if (rd_dev->rd_flags & RDF_NULLIO) return 0; total_sg_needed = rd_dev->rd_page_count; sg_tables = (total_sg_needed / max_sg_per_table) + 1; sg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL); if (!sg_table) { pr_err("Unable to allocate memory for Ramdisk" " scatterlist tables\n"); return -ENOMEM; } rd_dev->sg_table_array = sg_table; rd_dev->sg_table_count = sg_tables; rc = rd_allocate_sgl_table(rd_dev, sg_table, total_sg_needed, 0x00); if (rc) return rc; pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u space of" " %u pages in %u tables\n", rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, rd_dev->rd_page_count, rd_dev->sg_table_count); return 0; }
166,315
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 AwFeatureListCreator::SetUpFieldTrials() { auto* metrics_client = AwMetricsServiceClient::GetInstance(); DCHECK(!field_trial_list_); field_trial_list_ = std::make_unique<base::FieldTrialList>( metrics_client->CreateLowEntropyProvider()); std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed(); base::Time null_time; base::Time seed_date = seed ? base::Time::FromJavaTime(seed->date) : null_time; variations::UIStringOverrider ui_string_overrider; client_ = std::make_unique<AwVariationsServiceClient>(); auto seed_store = std::make_unique<variations::VariationsSeedStore>( local_state_.get(), /*initial_seed=*/std::move(seed), /*on_initial_seed_stored=*/base::DoNothing()); if (!seed_date.is_null()) seed_store->RecordLastFetchTime(seed_date); variations_field_trial_creator_ = std::make_unique<variations::VariationsFieldTrialCreator>( local_state_.get(), client_.get(), std::move(seed_store), ui_string_overrider); variations_field_trial_creator_->OverrideVariationsPlatform( variations::Study::PLATFORM_ANDROID_WEBVIEW); std::set<std::string> unforceable_field_trials; variations::SafeSeedManager ignored_safe_seed_manager(true, local_state_.get()); variations_field_trial_creator_->SetupFieldTrials( cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures, switches::kDisableFeatures, unforceable_field_trials, std::vector<std::string>(), content::GetSwitchDependentFeatureOverrides( *base::CommandLine::ForCurrentProcess()), /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(), aw_field_trials_.get(), &ignored_safe_seed_manager); } Commit Message: [AW] Add Variations.RestartsWithStaleSeed metric. This metric records the number of consecutive times the WebView browser process starts with a stale seed. It's written when a fresh seed is loaded after previously loading a stale seed. Test: Manually verified with logging that the metric was written. Bug: 1010625 Change-Id: Iadedb45af08d59ecd6662472670f848e8e99a8d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1851126 Commit-Queue: Robbie McElrath <[email protected]> Reviewed-by: Nate Fischer <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Reviewed-by: Changwan Ryu <[email protected]> Cr-Commit-Position: refs/heads/master@{#709417} CWE ID: CWE-20
void AwFeatureListCreator::SetUpFieldTrials() { auto* metrics_client = AwMetricsServiceClient::GetInstance(); DCHECK(!field_trial_list_); field_trial_list_ = std::make_unique<base::FieldTrialList>( metrics_client->CreateLowEntropyProvider()); std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed(); base::Time null_time; base::Time seed_date = seed ? base::Time::FromJavaTime(seed->date) : null_time; variations::UIStringOverrider ui_string_overrider; client_ = std::make_unique<AwVariationsServiceClient>(); auto seed_store = std::make_unique<variations::VariationsSeedStore>( local_state_.get(), /*initial_seed=*/std::move(seed), /*on_initial_seed_stored=*/base::DoNothing()); if (!seed_date.is_null()) seed_store->RecordLastFetchTime(seed_date); variations_field_trial_creator_ = std::make_unique<variations::VariationsFieldTrialCreator>( local_state_.get(), client_.get(), std::move(seed_store), ui_string_overrider); variations_field_trial_creator_->OverrideVariationsPlatform( variations::Study::PLATFORM_ANDROID_WEBVIEW); std::set<std::string> unforceable_field_trials; variations::SafeSeedManager ignored_safe_seed_manager(true, local_state_.get()); variations_field_trial_creator_->SetupFieldTrials( cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures, switches::kDisableFeatures, unforceable_field_trials, std::vector<std::string>(), content::GetSwitchDependentFeatureOverrides( *base::CommandLine::ForCurrentProcess()), /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(), aw_field_trials_.get(), &ignored_safe_seed_manager); CountOrRecordRestartsWithStaleSeed(local_state_.get(), IsSeedFresh()); }
172,360
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 packet_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied, err; struct sockaddr_ll *sll; int vnet_hdr_len = 0; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE)) goto out; #if 0 /* What error should we return now? EUNATTACH? */ if (pkt_sk(sk)->ifindex < 0) return -ENODEV; #endif if (flags & MSG_ERRQUEUE) { err = packet_recv_error(sk, msg, len); goto out; } /* * Call the generic datagram receiver. This handles all sorts * of horrible races and re-entrancy so we can forget about it * in the protocol layers. * * Now it will return ENETDOWN, if device have just gone down, * but then it will block. */ skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); /* * An error occurred so return it. Because skb_recv_datagram() * handles the blocking we don't see and worry about blocking * retries. */ if (skb == NULL) goto out; if (pkt_sk(sk)->has_vnet_hdr) { struct virtio_net_hdr vnet_hdr = { 0 }; err = -EINVAL; vnet_hdr_len = sizeof(vnet_hdr); if (len < vnet_hdr_len) goto out_free; len -= vnet_hdr_len; if (skb_is_gso(skb)) { struct skb_shared_info *sinfo = skb_shinfo(skb); /* This is a hint as to how much should be linear. */ vnet_hdr.hdr_len = skb_headlen(skb); vnet_hdr.gso_size = sinfo->gso_size; if (sinfo->gso_type & SKB_GSO_TCPV4) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; else if (sinfo->gso_type & SKB_GSO_TCPV6) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; else if (sinfo->gso_type & SKB_GSO_UDP) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP; else if (sinfo->gso_type & SKB_GSO_FCOE) goto out_free; else BUG(); if (sinfo->gso_type & SKB_GSO_TCP_ECN) vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN; } else vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE; if (skb->ip_summed == CHECKSUM_PARTIAL) { vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; vnet_hdr.csum_start = skb_checksum_start_offset(skb); vnet_hdr.csum_offset = skb->csum_offset; } /* else everything is zero */ err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr, vnet_hdr_len); if (err < 0) goto out_free; } /* * If the address length field is there to be filled in, we fill * it in now. */ sll = &PACKET_SKB_CB(skb)->sa.ll; if (sock->type == SOCK_PACKET) msg->msg_namelen = sizeof(struct sockaddr_pkt); else msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr); /* * You lose any data beyond the buffer you gave. If it worries a * user program they can ask the device for its MTU anyway. */ copied = skb->len; if (copied > len) { copied = len; msg->msg_flags |= MSG_TRUNC; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_ts_and_drops(msg, sk, skb); if (msg->msg_name) memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, msg->msg_namelen); if (pkt_sk(sk)->auxdata) { struct tpacket_auxdata aux; aux.tp_status = TP_STATUS_USER; if (skb->ip_summed == CHECKSUM_PARTIAL) aux.tp_status |= TP_STATUS_CSUMNOTREADY; aux.tp_len = PACKET_SKB_CB(skb)->origlen; aux.tp_snaplen = skb->len; aux.tp_mac = 0; aux.tp_net = skb_network_offset(skb); if (vlan_tx_tag_present(skb)) { aux.tp_vlan_tci = vlan_tx_tag_get(skb); aux.tp_status |= TP_STATUS_VLAN_VALID; } else { aux.tp_vlan_tci = 0; } put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux); } /* * Free or return the buffer as appropriate. Again this * hides all the races and re-entrancy issues from us. */ err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied); out_free: skb_free_datagram(sk, skb); out: return err; } Commit Message: af_packet: prevent information leak In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace) added a small information leak. Add padding field and make sure its zeroed before copy to user. Signed-off-by: Eric Dumazet <[email protected]> CC: Patrick McHardy <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static int packet_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied, err; struct sockaddr_ll *sll; int vnet_hdr_len = 0; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE)) goto out; #if 0 /* What error should we return now? EUNATTACH? */ if (pkt_sk(sk)->ifindex < 0) return -ENODEV; #endif if (flags & MSG_ERRQUEUE) { err = packet_recv_error(sk, msg, len); goto out; } /* * Call the generic datagram receiver. This handles all sorts * of horrible races and re-entrancy so we can forget about it * in the protocol layers. * * Now it will return ENETDOWN, if device have just gone down, * but then it will block. */ skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); /* * An error occurred so return it. Because skb_recv_datagram() * handles the blocking we don't see and worry about blocking * retries. */ if (skb == NULL) goto out; if (pkt_sk(sk)->has_vnet_hdr) { struct virtio_net_hdr vnet_hdr = { 0 }; err = -EINVAL; vnet_hdr_len = sizeof(vnet_hdr); if (len < vnet_hdr_len) goto out_free; len -= vnet_hdr_len; if (skb_is_gso(skb)) { struct skb_shared_info *sinfo = skb_shinfo(skb); /* This is a hint as to how much should be linear. */ vnet_hdr.hdr_len = skb_headlen(skb); vnet_hdr.gso_size = sinfo->gso_size; if (sinfo->gso_type & SKB_GSO_TCPV4) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; else if (sinfo->gso_type & SKB_GSO_TCPV6) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; else if (sinfo->gso_type & SKB_GSO_UDP) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP; else if (sinfo->gso_type & SKB_GSO_FCOE) goto out_free; else BUG(); if (sinfo->gso_type & SKB_GSO_TCP_ECN) vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN; } else vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE; if (skb->ip_summed == CHECKSUM_PARTIAL) { vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; vnet_hdr.csum_start = skb_checksum_start_offset(skb); vnet_hdr.csum_offset = skb->csum_offset; } /* else everything is zero */ err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr, vnet_hdr_len); if (err < 0) goto out_free; } /* * If the address length field is there to be filled in, we fill * it in now. */ sll = &PACKET_SKB_CB(skb)->sa.ll; if (sock->type == SOCK_PACKET) msg->msg_namelen = sizeof(struct sockaddr_pkt); else msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr); /* * You lose any data beyond the buffer you gave. If it worries a * user program they can ask the device for its MTU anyway. */ copied = skb->len; if (copied > len) { copied = len; msg->msg_flags |= MSG_TRUNC; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_ts_and_drops(msg, sk, skb); if (msg->msg_name) memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, msg->msg_namelen); if (pkt_sk(sk)->auxdata) { struct tpacket_auxdata aux; aux.tp_status = TP_STATUS_USER; if (skb->ip_summed == CHECKSUM_PARTIAL) aux.tp_status |= TP_STATUS_CSUMNOTREADY; aux.tp_len = PACKET_SKB_CB(skb)->origlen; aux.tp_snaplen = skb->len; aux.tp_mac = 0; aux.tp_net = skb_network_offset(skb); if (vlan_tx_tag_present(skb)) { aux.tp_vlan_tci = vlan_tx_tag_get(skb); aux.tp_status |= TP_STATUS_VLAN_VALID; } else { aux.tp_vlan_tci = 0; } aux.tp_padding = 0; put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux); } /* * Free or return the buffer as appropriate. Again this * hides all the races and re-entrancy issues from us. */ err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied); out_free: skb_free_datagram(sk, skb); out: return err; }
165,847
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: PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */ { const char *p, *q; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); p = val; while (p < endptr) { zval **tmp; q = p; while (*q != PS_DELIMITER) { if (++q >= endptr) goto break_outer_loop; } if (p[0] == PS_UNDEF_MARKER) { p++; has_value = 0; } else { has_value = 1; } namelen = q - p; name = estrndup(p, namelen); q++; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { goto skip; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { var_push_dtor_no_addref(&var_hash, &current); efree(name); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); skip: efree(name); p = q; } break_outer_loop: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */ Commit Message: Fix bug #72681 - consume data even if we're not storing them CWE ID: CWE-74
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */ { const char *p, *q; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; int skip = 0; PHP_VAR_UNSERIALIZE_INIT(var_hash); p = val; while (p < endptr) { zval **tmp; q = p; skip = 0; while (*q != PS_DELIMITER) { if (++q >= endptr) goto break_outer_loop; } if (p[0] == PS_UNDEF_MARKER) { p++; has_value = 0; } else { has_value = 1; } namelen = q - p; name = estrndup(p, namelen); q++; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { skip = 1; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { if (!skip) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } } else { var_push_dtor_no_addref(&var_hash, &current); efree(name); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } if (!skip) { PS_ADD_VARL(name, namelen); } skip: efree(name); p = q; } break_outer_loop: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */
166,959
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; } Commit Message: base64: Rework base64decode to handle split encoded data correctly CWE ID: CWE-125
unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; int wv, w1, w2, w3, w4; int tmpval[4]; int tmpcnt = 0; do { while (ptr < buf+len && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n' || *ptr == '\r')) { ptr++; } if (*ptr == '\0' || ptr >= buf+len) { break; } if ((wv = base64_table[(int)(unsigned char)*ptr++]) == -1) { continue; } tmpval[tmpcnt++] = wv; if (tmpcnt == 4) { tmpcnt = 0; w1 = tmpval[0]; w2 = tmpval[1]; w3 = tmpval[2]; w4 = tmpval[3]; if (w2 >= 0) { outbuf[p++] = (unsigned char)(((w1 << 2) + (w2 >> 4)) & 0xFF); } if (w3 >= 0) { outbuf[p++] = (unsigned char)(((w2 << 4) + (w3 >> 2)) & 0xFF); } if (w4 >= 0) { outbuf[p++] = (unsigned char)(((w3 << 6) + w4) & 0xFF); } } } while (1); outbuf[p] = 0; *size = p; return outbuf; }
168,416
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { const tuple<int, int, SubpelVarianceFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; subpel_variance_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); sec_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_ + width_ + height_ + 1]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(sec_ != NULL); ASSERT_TRUE(ref_ != NULL); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { const tuple<int, int, MseFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; mse_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(ref_ != NULL); }
174,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: static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for "KWAJ" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { off_t pos = sys->tell(fh); char *fn = (char *) sys->alloc(sys, (size_t) 13); /* allocate memory for maximum length filename */ if (! fn) return MSPACK_ERR_NOMEMORY; hdr->filename = fn; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ; for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 9) ? i+1 : 9; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 4) ? i+1 : 4; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } *fn = '\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; } Commit Message: kwaj_read_headers(): fix handling of non-terminated strings CWE ID: CWE-787
static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for "KWAJ" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { int len; /* allocate memory for maximum length filename */ char *fn = (char *) sys->alloc(sys, (size_t) 13); if (!(hdr->filename = fn)) return MSPACK_ERR_NOMEMORY; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { /* read and copy up to 9 bytes of a null terminated string */ if ((len = sys->read(fh, &buf[0], 9)) < 2) return MSPACK_ERR_READ; for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break; /* if string was 9 bytes with no null terminator, reject it */ if (i == 9 && buf[8] != '\0') return MSPACK_ERR_DATAFORMAT; /* seek to byte after string ended in file */ if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; fn--; /* remove the null terminator */ } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; /* read and copy up to 4 bytes of a null terminated string */ if ((len = sys->read(fh, &buf[0], 4)) < 2) return MSPACK_ERR_READ; for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break; /* if string was 4 bytes with no null terminator, reject it */ if (i == 4 && buf[3] != '\0') return MSPACK_ERR_DATAFORMAT; /* seek to byte after string ended in file */ if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; fn--; /* remove the null terminator */ } *fn = '\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; }
169,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) { const DictionaryValue* dict = GetExtensionPref(extension_id); std::string path; if (!dict->GetString(kPrefPath, &path)) return FilePath(); return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path))); } Commit Message: Coverity: Add a missing NULL check. BUG=none TEST=none CID=16813 Review URL: http://codereview.chromium.org/7216034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) { const DictionaryValue* dict = GetExtensionPref(extension_id); if (!dict) return FilePath(); std::string path; if (!dict->GetString(kPrefPath, &path)) return FilePath(); return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path))); }
170,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void impeg2d_dec_user_data(dec_state_t *ps_dec) { UWORD32 u4_start_code; stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while(u4_start_code == USER_DATA_START_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) { impeg2d_bit_stream_flush(ps_stream,8); } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
void impeg2d_dec_user_data(dec_state_t *ps_dec) { UWORD32 u4_start_code; stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while(u4_start_code == USER_DATA_START_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); while((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { impeg2d_bit_stream_flush(ps_stream,8); } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } }
173,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long ec_device_ioctl_xcmd(struct cros_ec_dev *ec, void __user *arg) { long ret; struct cros_ec_command u_cmd; struct cros_ec_command *s_cmd; if (copy_from_user(&u_cmd, arg, sizeof(u_cmd))) return -EFAULT; if ((u_cmd.outsize > EC_MAX_MSG_BYTES) || (u_cmd.insize > EC_MAX_MSG_BYTES)) return -EINVAL; s_cmd = kmalloc(sizeof(*s_cmd) + max(u_cmd.outsize, u_cmd.insize), GFP_KERNEL); if (!s_cmd) return -ENOMEM; if (copy_from_user(s_cmd, arg, sizeof(*s_cmd) + u_cmd.outsize)) { ret = -EFAULT; goto exit; } s_cmd->command += ec->cmd_offset; ret = cros_ec_cmd_xfer(ec->ec_dev, s_cmd); /* Only copy data to userland if data was received. */ if (ret < 0) goto exit; if (copy_to_user(arg, s_cmd, sizeof(*s_cmd) + u_cmd.insize)) ret = -EFAULT; exit: kfree(s_cmd); return ret; } Commit Message: platform/chrome: cros_ec_dev - double fetch bug in ioctl We verify "u_cmd.outsize" and "u_cmd.insize" but we need to make sure that those values have not changed between the two copy_from_user() calls. Otherwise it could lead to a buffer overflow. Additionally, cros_ec_cmd_xfer() can set s_cmd->insize to a lower value. We should use the new smaller value so we don't copy too much data to the user. Reported-by: Pengfei Wang <[email protected]> Fixes: a841178445bb ('mfd: cros_ec: Use a zero-length array for command data') Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Kees Cook <[email protected]> Tested-by: Gwendal Grignou <[email protected]> Cc: <[email protected]> # v4.2+ Signed-off-by: Olof Johansson <[email protected]> CWE ID: CWE-362
static long ec_device_ioctl_xcmd(struct cros_ec_dev *ec, void __user *arg) { long ret; struct cros_ec_command u_cmd; struct cros_ec_command *s_cmd; if (copy_from_user(&u_cmd, arg, sizeof(u_cmd))) return -EFAULT; if ((u_cmd.outsize > EC_MAX_MSG_BYTES) || (u_cmd.insize > EC_MAX_MSG_BYTES)) return -EINVAL; s_cmd = kmalloc(sizeof(*s_cmd) + max(u_cmd.outsize, u_cmd.insize), GFP_KERNEL); if (!s_cmd) return -ENOMEM; if (copy_from_user(s_cmd, arg, sizeof(*s_cmd) + u_cmd.outsize)) { ret = -EFAULT; goto exit; } if (u_cmd.outsize != s_cmd->outsize || u_cmd.insize != s_cmd->insize) { ret = -EINVAL; goto exit; } s_cmd->command += ec->cmd_offset; ret = cros_ec_cmd_xfer(ec->ec_dev, s_cmd); /* Only copy data to userland if data was received. */ if (ret < 0) goto exit; if (copy_to_user(arg, s_cmd, sizeof(*s_cmd) + s_cmd->insize)) ret = -EFAULT; exit: kfree(s_cmd); return ret; }
167,017
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: vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc( size ); if( object ) { g_signal_connect( object, "postclose", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); } Commit Message: zero memory on malloc to prevent write of uninit memory under some error conditions thanks Balint CWE ID: CWE-200
vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc0( size ); if( object ) { g_signal_connect( object, "postclose", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); }
169,739
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: dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[21]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59
dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[22]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen_safe(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); }
168,997
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: secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); /* m1 = c ^ (d mod (p-1)) mod p */ mpi_sub_ui ( h, P, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m1, C, h, P ); /* m2 = c ^ (d mod (q-1)) mod q */ mpi_sub_ui ( h, Q, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m2, C, h, Q ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } } Commit Message: CWE ID: CWE-310
secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t D_blind = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t r; unsigned int r_nbits; r_nbits = mpi_get_nbits (P) / 4; if (r_nbits < 96) r_nbits = 96; r = mpi_alloc_secure ( (r_nbits + BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB ); /* d_blind = (d mod (p-1)) + (p-1) * r */ /* m1 = c ^ d_blind mod p */ _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, P, 1 ); mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); mpi_add ( D_blind, D_blind, h ); mpi_powm ( m1, C, D_blind, P ); /* d_blind = (d mod (q-1)) + (q-1) * r */ /* m2 = c ^ d_blind mod q */ _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, Q, 1 ); mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); mpi_add ( D_blind, D_blind, h ); mpi_powm ( m2, C, D_blind, Q ); mpi_free ( r ); mpi_free ( D_blind ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } }
165,456
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: internalEntityProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { ENTITY *entity; const char *textStart, *textEnd; const char *next; enum XML_Error result; OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities; if (! openEntity) return XML_ERROR_UNEXPECTED_STATE; entity = openEntity->entity; textStart = ((char *)entity->textPtr) + entity->processed; textEnd = (char *)(entity->textPtr + entity->textLen); /* Set a safe default value in case 'next' does not get set */ next = textStart; #ifdef XML_DTD if (entity->is_param) { int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, next, &next, XML_FALSE); } else #endif /* XML_DTD */ result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding, textStart, textEnd, &next, XML_FALSE); if (result != XML_ERROR_NONE) return result; else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { entity->processed = (int)(next - (char *)entity->textPtr); return result; } else { entity->open = XML_FALSE; parser->m_openInternalEntities = openEntity->next; /* put openEntity back in list of free instances */ openEntity->next = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity; } #ifdef XML_DTD if (entity->is_param) { int tok; parser->m_processor = prologProcessor; tok = XmlPrologTok(parser->m_encoding, s, end, &next); return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } else #endif /* XML_DTD */ { parser->m_processor = contentProcessor; /* see externalEntityContentProcessor vs contentProcessor */ return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
internalEntityProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { ENTITY *entity; const char *textStart, *textEnd; const char *next; enum XML_Error result; OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities; if (! openEntity) return XML_ERROR_UNEXPECTED_STATE; entity = openEntity->entity; textStart = ((char *)entity->textPtr) + entity->processed; textEnd = (char *)(entity->textPtr + entity->textLen); /* Set a safe default value in case 'next' does not get set */ next = textStart; #ifdef XML_DTD if (entity->is_param) { int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, next, &next, XML_FALSE, XML_TRUE); } else #endif /* XML_DTD */ result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding, textStart, textEnd, &next, XML_FALSE); if (result != XML_ERROR_NONE) return result; else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { entity->processed = (int)(next - (char *)entity->textPtr); return result; } else { entity->open = XML_FALSE; parser->m_openInternalEntities = openEntity->next; /* put openEntity back in list of free instances */ openEntity->next = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity; } #ifdef XML_DTD if (entity->is_param) { int tok; parser->m_processor = prologProcessor; tok = XmlPrologTok(parser->m_encoding, s, end, &next); return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); } else #endif /* XML_DTD */ { parser->m_processor = contentProcessor; /* see externalEntityContentProcessor vs contentProcessor */ return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } }
169,531
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 jp2_box_dump(jp2_box_t *box, FILE *out) { jp2_boxinfo_t *boxinfo; boxinfo = jp2_boxinfolookup(box->type); assert(boxinfo); fprintf(out, "JP2 box: "); fprintf(out, "type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"', boxinfo->name, '"', box->type, box->len); if (box->ops->dumpdata) { (*box->ops->dumpdata)(box, out); } } Commit Message: Fixed another problem with incorrect cleanup of JP2 box data upon error. CWE ID: CWE-476
void jp2_box_dump(jp2_box_t *box, FILE *out) { jp2_boxinfo_t *boxinfo; boxinfo = jp2_boxinfolookup(box->type); assert(boxinfo); fprintf(out, "JP2 box: "); fprintf(out, "type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"', boxinfo->name, '"', box->type, box->len); if (box->ops->dumpdata) { (*box->ops->dumpdata)(box, out); } }
168,472
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 __exit pcd_exit(void) { struct pcd_unit *cd; int unit; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { if (cd->present) { del_gendisk(cd->disk); pi_release(cd->pi); unregister_cdrom(&cd->info); } blk_cleanup_queue(cd->disk->queue); blk_mq_free_tag_set(&cd->tag_set); put_disk(cd->disk); } unregister_blkdev(major, name); pi_unregister_driver(par_drv); } Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak Syzkaller report this: pcd: pcd version 1.07, major 46, nice 0 pcd0: Autoprobe failed pcd: No CD-ROM drive found kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pcd_init+0x95c/0x1000 [pcd] Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2 RSP: 0018:ffff8881e84df880 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935 RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8 R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000 R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003 FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1508000 ? 0xffffffffc1508000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace d873691c3cd69f56 ]--- If alloc_disk fails in pcd_init_units, cd->disk will be NULL, however in pcd_detect and pcd_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <[email protected]> Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-476
static void __exit pcd_exit(void) { struct pcd_unit *cd; int unit; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { if (!cd->disk) continue; if (cd->present) { del_gendisk(cd->disk); pi_release(cd->pi); unregister_cdrom(&cd->info); } blk_cleanup_queue(cd->disk->queue); blk_mq_free_tag_set(&cd->tag_set); put_disk(cd->disk); } unregister_blkdev(major, name); pi_unregister_driver(par_drv); }
169,518
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: xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate) { int end_in_lf = 0; int remain = 0; if (ctxt == NULL) return(XML_ERR_INTERNAL_ERROR); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (ctxt->instate == XML_PARSER_START) xmlDetectSAX2(ctxt); if ((size > 0) && (chunk != NULL) && (!terminate) && (chunk[size - 1] == '\r')) { end_in_lf = 1; size--; } xmldecl_done: if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) { int base = ctxt->input->base - ctxt->input->buf->buffer->content; int cur = ctxt->input->cur - ctxt->input->base; int res; /* * Specific handling if we autodetected an encoding, we should not * push more than the first line ... which depend on the encoding * And only push the rest once the final encoding was detected */ if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) { unsigned int len = 45; if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF-16")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF16"))) len = 90; else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS-4")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS4"))) len = 180; if (ctxt->input->buf->rawconsumed < len) len -= ctxt->input->buf->rawconsumed; /* * Change size for reading the initial declaration only * if size is greater than len. Otherwise, memmove in xmlBufferAdd * will blindly copy extra bytes from memory. */ if (size > len) { remain = size - len; size = len; } else { remain = 0; } } res =xmlParserInputBufferPush(ctxt->input->buf, size, chunk); if (res < 0) { ctxt->errNo = XML_PARSER_EOF; ctxt->disableSAX = 1; return (XML_PARSER_EOF); } ctxt->input->base = ctxt->input->buf->buffer->content + base; ctxt->input->cur = ctxt->input->base + cur; ctxt->input->end = &ctxt->input->buf->buffer->content[ctxt->input->buf->buffer->use]; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } else if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->input != NULL) && ctxt->input->buf != NULL) { xmlParserInputBufferPtr in = ctxt->input->buf; if ((in->encoder != NULL) && (in->buffer != NULL) && (in->raw != NULL)) { int nbchars; nbchars = xmlCharEncInFunc(in->encoder, in->buffer, in->raw); if (nbchars < 0) { /* TODO 2.6.0 */ xmlGenericError(xmlGenericErrorContext, "xmlParseChunk: encoder error\n"); return(XML_ERR_INVALID_ENCODING); } } } } if (remain != 0) xmlParseTryOrFinish(ctxt, 0); else xmlParseTryOrFinish(ctxt, terminate); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (remain != 0) { chunk += size; size = remain; remain = 0; goto xmldecl_done; } if ((end_in_lf == 1) && (ctxt->input != NULL) && (ctxt->input->buf != NULL)) { xmlParserInputBufferPush(ctxt->input->buf, 1, "\r"); } if (terminate) { /* * Check for termination */ int avail = 0; if (ctxt->input != NULL) { if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); } if ((ctxt->instate != XML_PARSER_EOF) && (ctxt->instate != XML_PARSER_EPILOG)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if ((ctxt->instate == XML_PARSER_EPILOG) && (avail > 0)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); } ctxt->instate = XML_PARSER_EOF; } return((xmlParserErrors) ctxt->errNo); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate) { int end_in_lf = 0; int remain = 0; if (ctxt == NULL) return(XML_ERR_INTERNAL_ERROR); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (ctxt->instate == XML_PARSER_EOF) return(-1); if (ctxt->instate == XML_PARSER_START) xmlDetectSAX2(ctxt); if ((size > 0) && (chunk != NULL) && (!terminate) && (chunk[size - 1] == '\r')) { end_in_lf = 1; size--; } xmldecl_done: if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) { int base = ctxt->input->base - ctxt->input->buf->buffer->content; int cur = ctxt->input->cur - ctxt->input->base; int res; /* * Specific handling if we autodetected an encoding, we should not * push more than the first line ... which depend on the encoding * And only push the rest once the final encoding was detected */ if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) { unsigned int len = 45; if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF-16")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF16"))) len = 90; else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS-4")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS4"))) len = 180; if (ctxt->input->buf->rawconsumed < len) len -= ctxt->input->buf->rawconsumed; /* * Change size for reading the initial declaration only * if size is greater than len. Otherwise, memmove in xmlBufferAdd * will blindly copy extra bytes from memory. */ if (size > len) { remain = size - len; size = len; } else { remain = 0; } } res =xmlParserInputBufferPush(ctxt->input->buf, size, chunk); if (res < 0) { ctxt->errNo = XML_PARSER_EOF; ctxt->disableSAX = 1; return (XML_PARSER_EOF); } ctxt->input->base = ctxt->input->buf->buffer->content + base; ctxt->input->cur = ctxt->input->base + cur; ctxt->input->end = &ctxt->input->buf->buffer->content[ctxt->input->buf->buffer->use]; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } else if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->input != NULL) && ctxt->input->buf != NULL) { xmlParserInputBufferPtr in = ctxt->input->buf; if ((in->encoder != NULL) && (in->buffer != NULL) && (in->raw != NULL)) { int nbchars; nbchars = xmlCharEncInFunc(in->encoder, in->buffer, in->raw); if (nbchars < 0) { /* TODO 2.6.0 */ xmlGenericError(xmlGenericErrorContext, "xmlParseChunk: encoder error\n"); return(XML_ERR_INVALID_ENCODING); } } } } if (remain != 0) xmlParseTryOrFinish(ctxt, 0); else xmlParseTryOrFinish(ctxt, terminate); if (ctxt->instate == XML_PARSER_EOF) return(ctxt->errNo); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (remain != 0) { chunk += size; size = remain; remain = 0; goto xmldecl_done; } if ((end_in_lf == 1) && (ctxt->input != NULL) && (ctxt->input->buf != NULL)) { xmlParserInputBufferPush(ctxt->input->buf, 1, "\r"); } if (terminate) { /* * Check for termination */ int avail = 0; if (ctxt->input != NULL) { if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); } if ((ctxt->instate != XML_PARSER_EOF) && (ctxt->instate != XML_PARSER_EPILOG)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if ((ctxt->instate == XML_PARSER_EPILOG) && (avail > 0)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); } ctxt->instate = XML_PARSER_EOF; } return((xmlParserErrors) ctxt->errNo); }
171,277
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 map_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int cap_setid, struct uid_gid_map *map, struct uid_gid_map *parent_map) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct uid_gid_map new_map; unsigned idx; struct uid_gid_extent extent; char *kbuf = NULL, *pos, *next_line; ssize_t ret; /* Only allow < page size writes at the beginning of the file */ if ((*ppos != 0) || (count >= PAGE_SIZE)) return -EINVAL; /* Slurp in the user data */ kbuf = memdup_user_nul(buf, count); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); /* * The userns_state_mutex serializes all writes to any given map. * * Any map is only ever written once. * * An id map fits within 1 cache line on most architectures. * * On read nothing needs to be done unless you are on an * architecture with a crazy cache coherency model like alpha. * * There is a one time data dependency between reading the * count of the extents and the values of the extents. The * desired behavior is to see the values of the extents that * were written before the count of the extents. * * To achieve this smp_wmb() is used on guarantee the write * order and smp_rmb() is guaranteed that we don't have crazy * architectures returning stale data. */ mutex_lock(&userns_state_mutex); memset(&new_map, 0, sizeof(struct uid_gid_map)); ret = -EPERM; /* Only allow one successful write to the map */ if (map->nr_extents != 0) goto out; /* * Adjusting namespace settings requires capabilities on the target. */ if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN)) goto out; /* Parse the user data */ ret = -EINVAL; pos = kbuf; for (; pos; pos = next_line) { /* Find the end of line and ensure I don't look past it */ next_line = strchr(pos, '\n'); if (next_line) { *next_line = '\0'; next_line++; if (*next_line == '\0') next_line = NULL; } pos = skip_spaces(pos); extent.first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent.lower_first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent.count = simple_strtoul(pos, &pos, 10); if (*pos && !isspace(*pos)) goto out; /* Verify there is not trailing junk on the line */ pos = skip_spaces(pos); if (*pos != '\0') goto out; /* Verify we have been given valid starting values */ if ((extent.first == (u32) -1) || (extent.lower_first == (u32) -1)) goto out; /* Verify count is not zero and does not cause the * extent to wrap */ if ((extent.first + extent.count) <= extent.first) goto out; if ((extent.lower_first + extent.count) <= extent.lower_first) goto out; /* Do the ranges in extent overlap any previous extents? */ if (mappings_overlap(&new_map, &extent)) goto out; if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS && (next_line != NULL)) goto out; ret = insert_extent(&new_map, &extent); if (ret < 0) goto out; ret = -EINVAL; } /* Be very certaint the new map actually exists */ if (new_map.nr_extents == 0) goto out; ret = -EPERM; /* Validate the user is allowed to use user id's mapped to. */ if (!new_idmap_permitted(file, ns, cap_setid, &new_map)) goto out; ret = sort_idmaps(&new_map); if (ret < 0) goto out; ret = -EPERM; /* Map the lower ids from the parent user namespace to the * kernel global id space. */ for (idx = 0; idx < new_map.nr_extents; idx++) { struct uid_gid_extent *e; u32 lower_first; if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) e = &new_map.extent[idx]; else e = &new_map.forward[idx]; lower_first = map_id_range_down(parent_map, e->lower_first, e->count); /* Fail if we can not map the specified extent to * the kernel global id space. */ if (lower_first == (u32) -1) goto out; e->lower_first = lower_first; } /* Install the map */ if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) { memcpy(map->extent, new_map.extent, new_map.nr_extents * sizeof(new_map.extent[0])); } else { map->forward = new_map.forward; map->reverse = new_map.reverse; } smp_wmb(); map->nr_extents = new_map.nr_extents; *ppos = count; ret = count; out: if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) { kfree(new_map.forward); kfree(new_map.reverse); map->forward = NULL; map->reverse = NULL; map->nr_extents = 0; } mutex_unlock(&userns_state_mutex); kfree(kbuf); return ret; } Commit Message: userns: also map extents in the reverse map to kernel IDs The current logic first clones the extent array and sorts both copies, then maps the lower IDs of the forward mapping into the lower namespace, but doesn't map the lower IDs of the reverse mapping. This means that code in a nested user namespace with >5 extents will see incorrect IDs. It also breaks some access checks, like inode_owner_or_capable() and privileged_wrt_inode_uidgid(), so a process can incorrectly appear to be capable relative to an inode. To fix it, we have to make sure that the "lower_first" members of extents in both arrays are translated; and we have to make sure that the reverse map is sorted *after* the translation (since otherwise the translation can break the sorting). This is CVE-2018-18955. Fixes: 6397fac4915a ("userns: bump idmap limits to 340") Cc: [email protected] Signed-off-by: Jann Horn <[email protected]> Tested-by: Eric W. Biederman <[email protected]> Reviewed-by: Eric W. Biederman <[email protected]> Signed-off-by: Eric W. Biederman <[email protected]> CWE ID: CWE-20
static ssize_t map_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int cap_setid, struct uid_gid_map *map, struct uid_gid_map *parent_map) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct uid_gid_map new_map; unsigned idx; struct uid_gid_extent extent; char *kbuf = NULL, *pos, *next_line; ssize_t ret; /* Only allow < page size writes at the beginning of the file */ if ((*ppos != 0) || (count >= PAGE_SIZE)) return -EINVAL; /* Slurp in the user data */ kbuf = memdup_user_nul(buf, count); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); /* * The userns_state_mutex serializes all writes to any given map. * * Any map is only ever written once. * * An id map fits within 1 cache line on most architectures. * * On read nothing needs to be done unless you are on an * architecture with a crazy cache coherency model like alpha. * * There is a one time data dependency between reading the * count of the extents and the values of the extents. The * desired behavior is to see the values of the extents that * were written before the count of the extents. * * To achieve this smp_wmb() is used on guarantee the write * order and smp_rmb() is guaranteed that we don't have crazy * architectures returning stale data. */ mutex_lock(&userns_state_mutex); memset(&new_map, 0, sizeof(struct uid_gid_map)); ret = -EPERM; /* Only allow one successful write to the map */ if (map->nr_extents != 0) goto out; /* * Adjusting namespace settings requires capabilities on the target. */ if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN)) goto out; /* Parse the user data */ ret = -EINVAL; pos = kbuf; for (; pos; pos = next_line) { /* Find the end of line and ensure I don't look past it */ next_line = strchr(pos, '\n'); if (next_line) { *next_line = '\0'; next_line++; if (*next_line == '\0') next_line = NULL; } pos = skip_spaces(pos); extent.first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent.lower_first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent.count = simple_strtoul(pos, &pos, 10); if (*pos && !isspace(*pos)) goto out; /* Verify there is not trailing junk on the line */ pos = skip_spaces(pos); if (*pos != '\0') goto out; /* Verify we have been given valid starting values */ if ((extent.first == (u32) -1) || (extent.lower_first == (u32) -1)) goto out; /* Verify count is not zero and does not cause the * extent to wrap */ if ((extent.first + extent.count) <= extent.first) goto out; if ((extent.lower_first + extent.count) <= extent.lower_first) goto out; /* Do the ranges in extent overlap any previous extents? */ if (mappings_overlap(&new_map, &extent)) goto out; if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS && (next_line != NULL)) goto out; ret = insert_extent(&new_map, &extent); if (ret < 0) goto out; ret = -EINVAL; } /* Be very certaint the new map actually exists */ if (new_map.nr_extents == 0) goto out; ret = -EPERM; /* Validate the user is allowed to use user id's mapped to. */ if (!new_idmap_permitted(file, ns, cap_setid, &new_map)) goto out; ret = -EPERM; /* Map the lower ids from the parent user namespace to the * kernel global id space. */ for (idx = 0; idx < new_map.nr_extents; idx++) { struct uid_gid_extent *e; u32 lower_first; if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) e = &new_map.extent[idx]; else e = &new_map.forward[idx]; lower_first = map_id_range_down(parent_map, e->lower_first, e->count); /* Fail if we can not map the specified extent to * the kernel global id space. */ if (lower_first == (u32) -1) goto out; e->lower_first = lower_first; } /* * If we want to use binary search for lookup, this clones the extent * array and sorts both copies. */ ret = sort_idmaps(&new_map); if (ret < 0) goto out; /* Install the map */ if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) { memcpy(map->extent, new_map.extent, new_map.nr_extents * sizeof(new_map.extent[0])); } else { map->forward = new_map.forward; map->reverse = new_map.reverse; } smp_wmb(); map->nr_extents = new_map.nr_extents; *ppos = count; ret = count; out: if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) { kfree(new_map.forward); kfree(new_map.reverse); map->forward = NULL; map->reverse = NULL; map->nr_extents = 0; } mutex_unlock(&userns_state_mutex); kfree(kbuf); return ret; }
168,998
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 aura::Window* OpenTestWindow(aura::Window* parent, bool modal) { DCHECK(!modal || (modal && parent)); views::Widget* widget = views::Widget::CreateWindowWithParent(new TestWindow(modal), parent); widget->Show(); return widget->GetNativeView(); } Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs. BUG=130420 TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient Review URL: https://chromiumcodereview.appspot.com/10514012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
static aura::Window* OpenTestWindow(aura::Window* parent, bool modal) { views::Widget* widget = views::Widget::CreateWindowWithParent(new TestWindow(modal), parent); widget->Show(); return widget->GetNativeView(); }
170,802
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 LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, CallbackWrapper* callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); }
171,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { if (requested_pos < 0) return 0; Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); Cluster* const pCluster = Cluster::Create( this, -1, requested_pos); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == 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
const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { // INVARIANT: //[ii, i) < pTP->m_pos //[i, j) ? //[j, jj) > pTP->m_pos Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); // const long long pos_ = pCluster->m_pos; // assert(pos_); // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); // assert(Cluster::HasBlockEntries(this, tp.m_pos)); Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); //-1); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; }
174,280
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 PHP_RINIT_FUNCTION(libxml) { if (_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); } return SUCCESS; } Commit Message: CWE ID:
static PHP_RINIT_FUNCTION(libxml) { if (_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); /* Enable the entity loader by default. This ensure that * other threads/requests that might have disable the loader * do not affect the current request. */ LIBXML(entity_loader_disabled) = 0; } return SUCCESS; }
165,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg) { char fnam[PROCLEN]; FILE *f; bool answer = false; char *line = NULL; size_t len = 0; int ret; ret = snprintf(fnam, PROCLEN, "/proc/%d/cgroup", pid); if (ret < 0 || ret >= PROCLEN) return false; if (!(f = fopen(fnam, "r"))) return false; while (getline(&line, &len, f) != -1) { char *c1, *c2, *linecmp; if (!line[0]) continue; c1 = strchr(line, ':'); if (!c1) goto out; c1++; c2 = strchr(c1, ':'); if (!c2) goto out; *c2 = '\0'; if (strcmp(c1, contrl) != 0) continue; c2++; stripnewline(c2); prune_init_slice(c2); /* * callers pass in '/' for root cgroup, otherwise they pass * in a cgroup without leading '/' */ linecmp = *cg == '/' ? c2 : c2+1; if (strncmp(linecmp, cg, strlen(linecmp)) != 0) { if (nextcg) *nextcg = get_next_cgroup_dir(linecmp, cg); goto out; } answer = true; goto out; } out: fclose(f); free(line); return answer; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg) { bool answer = false; char *c2 = get_pid_cgroup(pid, contrl); char *linecmp; if (!c2) return false; prune_init_slice(c2); /* * callers pass in '/' for root cgroup, otherwise they pass * in a cgroup without leading '/' */ linecmp = *cg == '/' ? c2 : c2+1; if (strncmp(linecmp, cg, strlen(linecmp)) != 0) { if (nextcg) { *nextcg = get_next_cgroup_dir(linecmp, cg); } goto out; } answer = true; out: free(c2); return answer; } /* * If caller is in /a/b/c, he may see that /a exists, but not /b or /a/c. */ static bool caller_may_see_dir(pid_t pid, const char *contrl, const char *cg) { bool answer = false; char *c2, *task_cg; size_t target_len, task_len; if (strcmp(cg, "/") == 0) return true; c2 = get_pid_cgroup(pid, contrl); if (!c2) return false; task_cg = c2 + 1; target_len = strlen(cg); task_len = strlen(task_cg); if (strcmp(cg, task_cg) == 0) { answer = true; goto out; } if (target_len < task_len) { /* looking up a parent dir */ if (strncmp(task_cg, cg, target_len) == 0 && task_cg[target_len] == '/') answer = true; goto out; } if (target_len > task_len) { /* looking up a child dir */ if (strncmp(task_cg, cg, task_len) == 0 && cg[task_len] == '/') answer = true; goto out; } out: free(c2); return answer; }
166,703
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: beep_print(netdissect_options *ndo, const u_char *bp, u_int length) { if (l_strnstart("MSG", 4, (const char *)bp, length)) /* A REQuest */ ND_PRINT((ndo, " BEEP MSG")); else if (l_strnstart("RPY ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP RPY")); else if (l_strnstart("ERR ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ERR")); else if (l_strnstart("ANS ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ANS")); else if (l_strnstart("NUL ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP NUL")); else if (l_strnstart("SEQ ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP SEQ")); else if (l_strnstart("END", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP END")); else ND_PRINT((ndo, " BEEP (payload or undecoded)")); } Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
beep_print(netdissect_options *ndo, const u_char *bp, u_int length) { if (l_strnstart(ndo, "MSG", 4, (const char *)bp, length)) /* A REQuest */ ND_PRINT((ndo, " BEEP MSG")); else if (l_strnstart(ndo, "RPY ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP RPY")); else if (l_strnstart(ndo, "ERR ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ERR")); else if (l_strnstart(ndo, "ANS ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ANS")); else if (l_strnstart(ndo, "NUL ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP NUL")); else if (l_strnstart(ndo, "SEQ ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP SEQ")); else if (l_strnstart(ndo, "END", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP END")); else ND_PRINT((ndo, " BEEP (payload or undecoded)")); }
167,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 VRDisplay::ConnectVSyncProvider() { DVLOG(1) << __FUNCTION__ << ": IsPresentationFocused()=" << IsPresentationFocused() << " vr_v_sync_provider_.is_bound()=" << vr_v_sync_provider_.is_bound(); if (!IsPresentationFocused() || vr_v_sync_provider_.is_bound()) return; display_->GetVRVSyncProvider(mojo::MakeRequest(&vr_v_sync_provider_)); vr_v_sync_provider_.set_connection_error_handler(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSyncConnectionError, WrapWeakPersistent(this)))); if (pending_raf_ && !display_blurred_) { pending_vsync_ = true; vr_v_sync_provider_->GetVSync(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSync, WrapWeakPersistent(this)))); } } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID:
void VRDisplay::ConnectVSyncProvider() { DVLOG(1) << __FUNCTION__ << ": IsPresentationFocused()=" << IsPresentationFocused() << " vr_v_sync_provider_.is_bound()=" << vr_v_sync_provider_.is_bound(); if (!IsPresentationFocused() || vr_v_sync_provider_.is_bound()) return; display_->GetVRVSyncProvider(mojo::MakeRequest(&vr_v_sync_provider_)); vr_v_sync_provider_.set_connection_error_handler(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSyncConnectionError, WrapWeakPersistent(this)))); if (pending_vrdisplay_raf_ && !display_blurred_) { pending_vsync_ = true; vr_v_sync_provider_->GetVSync(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSync, WrapWeakPersistent(this)))); } }
171,992
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 UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents); TabAttachedImpl(new_contents->web_contents()); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents->web_contents()); TabAttachedImpl(new_contents->web_contents()); }
171,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: void UpdateContentLengthPrefs( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, bool via_data_reduction_proxy, PrefService* prefs) { int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength); int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength); total_received += received_content_length; total_original += original_content_length; prefs->SetInt64(prefs::kHttpReceivedContentLength, total_received); prefs->SetInt64(prefs::kHttpOriginalContentLength, total_original); #if defined(OS_ANDROID) || defined(OS_IOS) UpdateContentLengthPrefsForDataReductionProxy( received_content_length, original_content_length, with_data_reduction_proxy_enabled, via_data_reduction_proxy, base::Time::Now(), prefs); #endif // defined(OS_ANDROID) || defined(OS_IOS) } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void UpdateContentLengthPrefs( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, DataReductionRequestType data_reduction_type, PrefService* prefs) { int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength); int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength); total_received += received_content_length; total_original += original_content_length; prefs->SetInt64(prefs::kHttpReceivedContentLength, total_received); prefs->SetInt64(prefs::kHttpOriginalContentLength, total_original); #if defined(OS_ANDROID) || defined(OS_IOS) UpdateContentLengthPrefsForDataReductionProxy( received_content_length, original_content_length, with_data_reduction_proxy_enabled, data_reduction_type, base::Time::Now(), prefs); #endif // defined(OS_ANDROID) || defined(OS_IOS) }
171,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) { if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; while (bytes) { int copy = min(bytes, iov->iov_len - base); bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) { if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; /* * The !iov->iov_len check ensures we skip over unlikely * zero-length segments. */ while (bytes || !iov->iov_len) { int copy = min(bytes, iov->iov_len - base); bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } }
167,617
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: KeyedService* LogoServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); DCHECK(!profile->IsOffTheRecord()); #if defined(OS_ANDROID) bool use_gray_background = !GetIsChromeHomeEnabled(); #else bool use_gray_background = false; #endif return new LogoService(profile->GetPath().Append(kCachedLogoDirectory), TemplateURLServiceFactory::GetForProfile(profile), base::MakeUnique<suggestions::ImageDecoderImpl>(), profile->GetRequestContext(), use_gray_background); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
KeyedService* LogoServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); DCHECK(!profile->IsOffTheRecord()); #if defined(OS_ANDROID) bool use_gray_background = !GetIsChromeHomeEnabled(); #else bool use_gray_background = false; #endif return new LogoServiceImpl(profile->GetPath().Append(kCachedLogoDirectory), TemplateURLServiceFactory::GetForProfile(profile), base::MakeUnique<suggestions::ImageDecoderImpl>(), profile->GetRequestContext(), use_gray_background); }
171,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction( v8::Handle<v8::String> name) { if (name->Equals(v8::String::New("GetExtensionAPIDefinition"))) { return v8::FunctionTemplate::New(GetExtensionAPIDefinition); } else if (name->Equals(v8::String::New("GetExtensionViews"))) { return v8::FunctionTemplate::New(GetExtensionViews, v8::External::New(this)); } else if (name->Equals(v8::String::New("GetNextRequestId"))) { return v8::FunctionTemplate::New(GetNextRequestId); } else if (name->Equals(v8::String::New("OpenChannelToTab"))) { return v8::FunctionTemplate::New(OpenChannelToTab); } else if (name->Equals(v8::String::New("GetNextContextMenuId"))) { return v8::FunctionTemplate::New(GetNextContextMenuId); } else if (name->Equals(v8::String::New("GetCurrentPageActions"))) { return v8::FunctionTemplate::New(GetCurrentPageActions, v8::External::New(this)); } else if (name->Equals(v8::String::New("StartRequest"))) { return v8::FunctionTemplate::New(StartRequest, v8::External::New(this)); } else if (name->Equals(v8::String::New("GetRenderViewId"))) { return v8::FunctionTemplate::New(GetRenderViewId); } else if (name->Equals(v8::String::New("SetIconCommon"))) { return v8::FunctionTemplate::New(SetIconCommon, v8::External::New(this)); } else if (name->Equals(v8::String::New("IsExtensionProcess"))) { return v8::FunctionTemplate::New(IsExtensionProcess, v8::External::New(this)); } else if (name->Equals(v8::String::New("IsIncognitoProcess"))) { return v8::FunctionTemplate::New(IsIncognitoProcess); } else if (name->Equals(v8::String::New("GetUniqueSubEventName"))) { return v8::FunctionTemplate::New(GetUniqueSubEventName); } else if (name->Equals(v8::String::New("GetLocalFileSystem"))) { return v8::FunctionTemplate::New(GetLocalFileSystem); } else if (name->Equals(v8::String::New("DecodeJPEG"))) { return v8::FunctionTemplate::New(DecodeJPEG, v8::External::New(this)); } return ExtensionBase::GetNativeFunction(name); } 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
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction( v8::Handle<v8::String> name) { if (name->Equals(v8::String::New("GetExtensionAPIDefinition"))) { return v8::FunctionTemplate::New(GetExtensionAPIDefinition); } else if (name->Equals(v8::String::New("GetExtensionViews"))) { return v8::FunctionTemplate::New(GetExtensionViews, v8::External::New(this)); } else if (name->Equals(v8::String::New("GetNextRequestId"))) { return v8::FunctionTemplate::New(GetNextRequestId); } else if (name->Equals(v8::String::New("OpenChannelToTab"))) { return v8::FunctionTemplate::New(OpenChannelToTab); } else if (name->Equals(v8::String::New("GetNextContextMenuId"))) { return v8::FunctionTemplate::New(GetNextContextMenuId); } else if (name->Equals(v8::String::New("GetNextTtsEventId"))) { return v8::FunctionTemplate::New(GetNextTtsEventId); } else if (name->Equals(v8::String::New("GetCurrentPageActions"))) { return v8::FunctionTemplate::New(GetCurrentPageActions, v8::External::New(this)); } else if (name->Equals(v8::String::New("StartRequest"))) { return v8::FunctionTemplate::New(StartRequest, v8::External::New(this)); } else if (name->Equals(v8::String::New("GetRenderViewId"))) { return v8::FunctionTemplate::New(GetRenderViewId); } else if (name->Equals(v8::String::New("SetIconCommon"))) { return v8::FunctionTemplate::New(SetIconCommon, v8::External::New(this)); } else if (name->Equals(v8::String::New("IsExtensionProcess"))) { return v8::FunctionTemplate::New(IsExtensionProcess, v8::External::New(this)); } else if (name->Equals(v8::String::New("IsIncognitoProcess"))) { return v8::FunctionTemplate::New(IsIncognitoProcess); } else if (name->Equals(v8::String::New("GetUniqueSubEventName"))) { return v8::FunctionTemplate::New(GetUniqueSubEventName); } else if (name->Equals(v8::String::New("GetLocalFileSystem"))) { return v8::FunctionTemplate::New(GetLocalFileSystem); } else if (name->Equals(v8::String::New("DecodeJPEG"))) { return v8::FunctionTemplate::New(DecodeJPEG, v8::External::New(this)); } return ExtensionBase::GetNativeFunction(name); }
170,404
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 **XListExtensions( register Display *dpy, int *nextensions) /* RETURN */ { xListExtensionsReply rep; char **list = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetEmptyReq (ListExtensions, req); if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nExtensions) { list = Xmalloc (rep.nExtensions * sizeof (char *)); if (rep.length > 0 && rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc (rlen + 1); /* +1 to leave room for last null-terminator */ } if ((!list) || (!ch)) { Xfree(list); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *ch; for (i = 0; i < rep.nExtensions; i++) { if (ch + length < chend) { list[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ if (ch <= chend) { length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else { list[i] = NULL; } } else list[i] = NULL; } } } else Commit Message: CWE ID: CWE-682
char **XListExtensions( register Display *dpy, int *nextensions) /* RETURN */ { xListExtensionsReply rep; char **list = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetEmptyReq (ListExtensions, req); if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nExtensions) { list = Xmalloc (rep.nExtensions * sizeof (char *)); if (rep.length > 0 && rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc (rlen + 1); /* +1 to leave room for last null-terminator */ } if ((!list) || (!ch)) { Xfree(list); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + rlen; length = *ch; for (i = 0; i < rep.nExtensions; i++) { if (ch + length < chend) { list[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else list[i] = NULL; } } } else
164,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: int module_load( YR_SCAN_CONTEXT* context, YR_OBJECT* module_object, void* module_data, size_t module_data_size) { set_integer(1, module_object, "constants.one"); set_integer(2, module_object, "constants.two"); set_string("foo", module_object, "constants.foo"); set_string("", module_object, "constants.empty"); set_integer(1, module_object, "struct_array[1].i"); set_integer(0, module_object, "integer_array[%i]", 0); set_integer(1, module_object, "integer_array[%i]", 1); set_integer(2, module_object, "integer_array[%i]", 2); set_string("foo", module_object, "string_array[%i]", 0); set_string("bar", module_object, "string_array[%i]", 1); set_string("baz", module_object, "string_array[%i]", 2); set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3); set_string("foo", module_object, "string_dict[%s]", "foo"); set_string("bar", module_object, "string_dict[\"bar\"]"); set_string("foo", module_object, "struct_dict[%s].s", "foo"); set_integer(1, module_object, "struct_dict[%s].i", "foo"); return ERROR_SUCCESS; } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119
int module_load( YR_SCAN_CONTEXT* context, YR_OBJECT* module_object, void* module_data, size_t module_data_size) { set_integer(1, module_object, "constants.one"); set_integer(2, module_object, "constants.two"); set_string("foo", module_object, "constants.foo"); set_string("", module_object, "constants.empty"); set_integer(1, module_object, "struct_array[1].i"); set_integer(0, module_object, "integer_array[%i]", 0); set_integer(1, module_object, "integer_array[%i]", 1); set_integer(2, module_object, "integer_array[%i]", 2); set_integer(256, module_object, "integer_array[%i]", 256); set_string("foo", module_object, "string_array[%i]", 0); set_string("bar", module_object, "string_array[%i]", 1); set_string("baz", module_object, "string_array[%i]", 2); set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3); set_string("foo", module_object, "string_dict[%s]", "foo"); set_string("bar", module_object, "string_dict[\"bar\"]"); set_string("foo", module_object, "struct_dict[%s].s", "foo"); set_integer(1, module_object, "struct_dict[%s].i", "foo"); return ERROR_SUCCESS; }
168,044
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: HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, const GlyphData* emphasisData, HashSet<const SimpleFontData*>* fallbackFonts, FloatRect* bounds) : Shaper(font, run, emphasisData, fallbackFonts, bounds) , m_normalizedBufferLength(0) , m_wordSpacingAdjustment(font->fontDescription().wordSpacing()) , m_letterSpacing(font->fontDescription().letterSpacing()) , m_expansionOpportunityCount(0) , m_fromIndex(0) , m_toIndex(m_run.length()) { m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]); normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength); setExpansion(m_run.expansion()); setFontFeatures(); } Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape. [email protected] BUG=476647 Review URL: https://codereview.chromium.org/1108663003 git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, const GlyphData* emphasisData, HashSet<const SimpleFontData*>* fallbackFonts, FloatRect* bounds) : Shaper(font, run, emphasisData, fallbackFonts, bounds) , m_normalizedBufferLength(0) , m_wordSpacingAdjustment(font->fontDescription().wordSpacing()) , m_letterSpacing(font->fontDescription().letterSpacing()) , m_expansionOpportunityCount(0) , m_fromIndex(0) , m_toIndex(m_run.length()) , m_totalWidth(0) { m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]); normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength); setExpansion(m_run.expansion()); setFontFeatures(); }
172,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: static int __jfs_set_acl(tid_t tid, struct inode *inode, int type, struct posix_acl *acl) { char *ea_name; int rc; int size = 0; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: ea_name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { rc = posix_acl_equiv_mode(acl, &inode->i_mode); if (rc < 0) return rc; inode->i_ctime = CURRENT_TIME; mark_inode_dirty(inode); if (rc == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: ea_name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; rc = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (rc < 0) goto out; } rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0); out: kfree(value); if (!rc) set_cached_acl(inode, type, acl); return rc; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
static int __jfs_set_acl(tid_t tid, struct inode *inode, int type, struct posix_acl *acl) { char *ea_name; int rc; int size = 0; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: ea_name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { rc = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (rc) return rc; inode->i_ctime = CURRENT_TIME; mark_inode_dirty(inode); } break; case ACL_TYPE_DEFAULT: ea_name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; rc = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (rc < 0) goto out; } rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0); out: kfree(value); if (!rc) set_cached_acl(inode, type, acl); return rc; }
166,975
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 cg_rmdir(const char *path) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *cgdir = NULL, *controller; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { ret = -EINVAL; goto out; } fprintf(stderr, "rmdir: verifying access to %s:%s (req path %s)\n", controller, cgdir, path); if (!fc_may_access(fc, controller, cgdir, NULL, O_WRONLY)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { ret = -EACCES; goto out; } if (!cgfs_remove(controller, cgroup)) { ret = -EINVAL; goto out; } ret = 0; out: free(cgdir); return ret; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static int cg_rmdir(const char *path) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *cgdir = NULL, *controller, *next = NULL; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { ret = -EINVAL; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, &next)) { if (!fpath || strcmp(next, fpath) == 0) ret = -EBUSY; else ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, cgdir, NULL, O_WRONLY)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { ret = -EACCES; goto out; } if (!cgfs_remove(controller, cgroup)) { ret = -EINVAL; goto out; } ret = 0; out: free(cgdir); free(next); return ret; }
166,708
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: XOpenDevice( register Display *dpy, register XID id) { register long rlen; /* raw length */ xOpenDeviceReq *req; xOpenDeviceReply rep; XDevice *dev; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(OpenDevice, req); req->reqType = info->codes->major_opcode; req->ReqType = X_OpenDevice; req->deviceid = id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (XDevice *) NULL; return (XDevice *) NULL; } rlen = rep.length << 2; dev = (XDevice *) Xmalloc(sizeof(XDevice) + rep.num_classes * sizeof(XInputClassInfo)); if (dev) { int dlen; /* data length */ _XEatData(dpy, (unsigned long)rlen - dlen); } else _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (dev); } Commit Message: CWE ID: CWE-284
XOpenDevice( register Display *dpy, register XID id) { register long rlen; /* raw length */ xOpenDeviceReq *req; xOpenDeviceReply rep; XDevice *dev; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(OpenDevice, req); req->reqType = info->codes->major_opcode; req->ReqType = X_OpenDevice; req->deviceid = id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (XDevice *) NULL; return (XDevice *) NULL; } if (rep.length < INT_MAX >> 2 && (rep.length << 2) >= rep.num_classes * sizeof(xInputClassInfo)) { rlen = rep.length << 2; dev = (XDevice *) Xmalloc(sizeof(XDevice) + rep.num_classes * sizeof(XInputClassInfo)); } else { rlen = 0; dev = NULL; } if (dev) { int dlen; /* data length */ _XEatData(dpy, (unsigned long)rlen - dlen); } else _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (dev); }
164,921
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: write_header( FT_Error error_code ) { FT_Face face; const char* basename; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) PanicZ( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); sprintf( status.header_buffer, "at %g points, angle = %d", status.ptsize/64.0, status.angle ); grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); } Commit Message: CWE ID: CWE-119
write_header( FT_Error error_code ) { FT_Face face; const char* basename; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) PanicZ( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%.50s %.50s (file `%.100s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')", basename ); break; default: sprintf( status.header_buffer, "File `%.100s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); sprintf( status.header_buffer, "at %g points, angle = %d", status.ptsize/64.0, status.angle ); grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); }
165,000
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 dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev) { struct nlattr *cee, *app; struct dcb_app_type *itr; const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops; int dcbx, i, err = -EMSGSIZE; u8 value; if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name)) goto nla_put_failure; cee = nla_nest_start(skb, DCB_ATTR_CEE); if (!cee) goto nla_put_failure; /* local pg */ if (ops->getpgtccfgtx && ops->getpgbwgcfgtx) { err = dcbnl_cee_pg_fill(skb, netdev, 1); if (err) goto nla_put_failure; } if (ops->getpgtccfgrx && ops->getpgbwgcfgrx) { err = dcbnl_cee_pg_fill(skb, netdev, 0); if (err) goto nla_put_failure; } /* local pfc */ if (ops->getpfccfg) { struct nlattr *pfc_nest = nla_nest_start(skb, DCB_ATTR_CEE_PFC); if (!pfc_nest) goto nla_put_failure; for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) { ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value); if (nla_put_u8(skb, i, value)) goto nla_put_failure; } nla_nest_end(skb, pfc_nest); } /* local app */ spin_lock(&dcb_lock); app = nla_nest_start(skb, DCB_ATTR_CEE_APP_TABLE); if (!app) goto dcb_unlock; list_for_each_entry(itr, &dcb_app_list, list) { if (itr->ifindex == netdev->ifindex) { struct nlattr *app_nest = nla_nest_start(skb, DCB_ATTR_APP); if (!app_nest) goto dcb_unlock; err = nla_put_u8(skb, DCB_APP_ATTR_IDTYPE, itr->app.selector); if (err) goto dcb_unlock; err = nla_put_u16(skb, DCB_APP_ATTR_ID, itr->app.protocol); if (err) goto dcb_unlock; err = nla_put_u8(skb, DCB_APP_ATTR_PRIORITY, itr->app.priority); if (err) goto dcb_unlock; nla_nest_end(skb, app_nest); } } nla_nest_end(skb, app); if (netdev->dcbnl_ops->getdcbx) dcbx = netdev->dcbnl_ops->getdcbx(netdev); else dcbx = -EOPNOTSUPP; spin_unlock(&dcb_lock); /* features flags */ if (ops->getfeatcfg) { struct nlattr *feat = nla_nest_start(skb, DCB_ATTR_CEE_FEAT); if (!feat) goto nla_put_failure; for (i = DCB_FEATCFG_ATTR_ALL + 1; i <= DCB_FEATCFG_ATTR_MAX; i++) if (!ops->getfeatcfg(netdev, i, &value) && nla_put_u8(skb, i, value)) goto nla_put_failure; nla_nest_end(skb, feat); } /* peer info if available */ if (ops->cee_peer_getpg) { struct cee_pg pg; err = ops->cee_peer_getpg(netdev, &pg); if (!err && nla_put(skb, DCB_ATTR_CEE_PEER_PG, sizeof(pg), &pg)) goto nla_put_failure; } if (ops->cee_peer_getpfc) { struct cee_pfc pfc; err = ops->cee_peer_getpfc(netdev, &pfc); if (!err && nla_put(skb, DCB_ATTR_CEE_PEER_PFC, sizeof(pfc), &pfc)) goto nla_put_failure; } if (ops->peer_getappinfo && ops->peer_getapptable) { err = dcbnl_build_peer_app(netdev, skb, DCB_ATTR_CEE_PEER_APP_TABLE, DCB_ATTR_CEE_PEER_APP_INFO, DCB_ATTR_CEE_PEER_APP); if (err) goto nla_put_failure; } nla_nest_end(skb, cee); /* DCBX state */ if (dcbx >= 0) { err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx); if (err) goto nla_put_failure; } return 0; dcb_unlock: spin_unlock(&dcb_lock); nla_put_failure: return err; } Commit Message: dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev) { struct nlattr *cee, *app; struct dcb_app_type *itr; const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops; int dcbx, i, err = -EMSGSIZE; u8 value; if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name)) goto nla_put_failure; cee = nla_nest_start(skb, DCB_ATTR_CEE); if (!cee) goto nla_put_failure; /* local pg */ if (ops->getpgtccfgtx && ops->getpgbwgcfgtx) { err = dcbnl_cee_pg_fill(skb, netdev, 1); if (err) goto nla_put_failure; } if (ops->getpgtccfgrx && ops->getpgbwgcfgrx) { err = dcbnl_cee_pg_fill(skb, netdev, 0); if (err) goto nla_put_failure; } /* local pfc */ if (ops->getpfccfg) { struct nlattr *pfc_nest = nla_nest_start(skb, DCB_ATTR_CEE_PFC); if (!pfc_nest) goto nla_put_failure; for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) { ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value); if (nla_put_u8(skb, i, value)) goto nla_put_failure; } nla_nest_end(skb, pfc_nest); } /* local app */ spin_lock(&dcb_lock); app = nla_nest_start(skb, DCB_ATTR_CEE_APP_TABLE); if (!app) goto dcb_unlock; list_for_each_entry(itr, &dcb_app_list, list) { if (itr->ifindex == netdev->ifindex) { struct nlattr *app_nest = nla_nest_start(skb, DCB_ATTR_APP); if (!app_nest) goto dcb_unlock; err = nla_put_u8(skb, DCB_APP_ATTR_IDTYPE, itr->app.selector); if (err) goto dcb_unlock; err = nla_put_u16(skb, DCB_APP_ATTR_ID, itr->app.protocol); if (err) goto dcb_unlock; err = nla_put_u8(skb, DCB_APP_ATTR_PRIORITY, itr->app.priority); if (err) goto dcb_unlock; nla_nest_end(skb, app_nest); } } nla_nest_end(skb, app); if (netdev->dcbnl_ops->getdcbx) dcbx = netdev->dcbnl_ops->getdcbx(netdev); else dcbx = -EOPNOTSUPP; spin_unlock(&dcb_lock); /* features flags */ if (ops->getfeatcfg) { struct nlattr *feat = nla_nest_start(skb, DCB_ATTR_CEE_FEAT); if (!feat) goto nla_put_failure; for (i = DCB_FEATCFG_ATTR_ALL + 1; i <= DCB_FEATCFG_ATTR_MAX; i++) if (!ops->getfeatcfg(netdev, i, &value) && nla_put_u8(skb, i, value)) goto nla_put_failure; nla_nest_end(skb, feat); } /* peer info if available */ if (ops->cee_peer_getpg) { struct cee_pg pg; memset(&pg, 0, sizeof(pg)); err = ops->cee_peer_getpg(netdev, &pg); if (!err && nla_put(skb, DCB_ATTR_CEE_PEER_PG, sizeof(pg), &pg)) goto nla_put_failure; } if (ops->cee_peer_getpfc) { struct cee_pfc pfc; memset(&pfc, 0, sizeof(pfc)); err = ops->cee_peer_getpfc(netdev, &pfc); if (!err && nla_put(skb, DCB_ATTR_CEE_PEER_PFC, sizeof(pfc), &pfc)) goto nla_put_failure; } if (ops->peer_getappinfo && ops->peer_getapptable) { err = dcbnl_build_peer_app(netdev, skb, DCB_ATTR_CEE_PEER_APP_TABLE, DCB_ATTR_CEE_PEER_APP_INFO, DCB_ATTR_CEE_PEER_APP); if (err) goto nla_put_failure; } nla_nest_end(skb, cee); /* DCBX state */ if (dcbx >= 0) { err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx); if (err) goto nla_put_failure; } return 0; dcb_unlock: spin_unlock(&dcb_lock); nla_put_failure: return err; }
166,057
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 nw_cache_free(nw_cache *cache, void *obj) { if (cache->free < cache->free_total) { cache->free_arr[cache->free++] = obj; } else { uint32_t new_free_total = cache->free_total * 2; void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *)); if (new_arr) { cache->free_total = new_free_total; cache->free_arr = new_arr; cache->free_arr[cache->free++] = obj; } else { free(obj); } } } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
void nw_cache_free(nw_cache *cache, void *obj) { if (cache->free < cache->free_total) { cache->free_arr[cache->free++] = obj; } else if (cache->free_total < NW_CACHE_MAX_SIZE) { uint32_t new_free_total = cache->free_total * 2; void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *)); if (new_arr) { cache->free_total = new_free_total; cache->free_arr = new_arr; cache->free_arr[cache->free++] = obj; } else { free(obj); } } else { free(obj); } }
169,016
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 DrawingBuffer::FinishPrepareTextureMailboxGpu( viz::TextureMailbox* out_mailbox, std::unique_ptr<cc::SingleReleaseCallback>* out_release_callback) { DCHECK(state_restorer_); if (web_gl_version_ > kWebGL1) { state_restorer_->SetPixelUnpackBufferBindingDirty(); gl_->BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } RefPtr<ColorBuffer> color_buffer_for_mailbox; if (preserve_drawing_buffer_ == kDiscard) { color_buffer_for_mailbox = back_color_buffer_; back_color_buffer_ = CreateOrRecycleColorBuffer(); AttachColorBufferToReadFramebuffer(); if (discard_framebuffer_supported_) { const GLenum kAttachments[3] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT}; state_restorer_->SetFramebufferBindingDirty(); gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_); gl_->DiscardFramebufferEXT(GL_FRAMEBUFFER, 3, kAttachments); } } else { color_buffer_for_mailbox = CreateOrRecycleColorBuffer(); gl_->CopySubTextureCHROMIUM(back_color_buffer_->texture_id, 0, color_buffer_for_mailbox->parameters.target, color_buffer_for_mailbox->texture_id, 0, 0, 0, 0, 0, size_.Width(), size_.Height(), GL_FALSE, GL_FALSE, GL_FALSE); } { gl_->ProduceTextureDirectCHROMIUM( color_buffer_for_mailbox->texture_id, color_buffer_for_mailbox->parameters.target, color_buffer_for_mailbox->mailbox.name); const GLuint64 fence_sync = gl_->InsertFenceSyncCHROMIUM(); #if defined(OS_MACOSX) gl_->DescheduleUntilFinishedCHROMIUM(); #endif gl_->Flush(); gl_->GenSyncTokenCHROMIUM( fence_sync, color_buffer_for_mailbox->produce_sync_token.GetData()); } { bool is_overlay_candidate = color_buffer_for_mailbox->image_id != 0; bool secure_output_only = false; *out_mailbox = viz::TextureMailbox( color_buffer_for_mailbox->mailbox, color_buffer_for_mailbox->produce_sync_token, color_buffer_for_mailbox->parameters.target, gfx::Size(size_), is_overlay_candidate, secure_output_only); out_mailbox->set_color_space(color_space_); auto func = WTF::Bind(&DrawingBuffer::MailboxReleasedGpu, RefPtr<DrawingBuffer>(this), color_buffer_for_mailbox); *out_release_callback = cc::SingleReleaseCallback::Create( ConvertToBaseCallback(std::move(func))); } front_color_buffer_ = color_buffer_for_mailbox; contents_changed_ = false; SetBufferClearNeeded(true); return true; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
bool DrawingBuffer::FinishPrepareTextureMailboxGpu( viz::TextureMailbox* out_mailbox, std::unique_ptr<cc::SingleReleaseCallback>* out_release_callback) { DCHECK(state_restorer_); if (webgl_version_ > kWebGL1) { state_restorer_->SetPixelUnpackBufferBindingDirty(); gl_->BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } RefPtr<ColorBuffer> color_buffer_for_mailbox; if (preserve_drawing_buffer_ == kDiscard) { color_buffer_for_mailbox = back_color_buffer_; back_color_buffer_ = CreateOrRecycleColorBuffer(); AttachColorBufferToReadFramebuffer(); if (discard_framebuffer_supported_) { const GLenum kAttachments[3] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT}; state_restorer_->SetFramebufferBindingDirty(); gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_); gl_->DiscardFramebufferEXT(GL_FRAMEBUFFER, 3, kAttachments); } } else { color_buffer_for_mailbox = CreateOrRecycleColorBuffer(); gl_->CopySubTextureCHROMIUM(back_color_buffer_->texture_id, 0, color_buffer_for_mailbox->parameters.target, color_buffer_for_mailbox->texture_id, 0, 0, 0, 0, 0, size_.Width(), size_.Height(), GL_FALSE, GL_FALSE, GL_FALSE); } { gl_->ProduceTextureDirectCHROMIUM( color_buffer_for_mailbox->texture_id, color_buffer_for_mailbox->parameters.target, color_buffer_for_mailbox->mailbox.name); const GLuint64 fence_sync = gl_->InsertFenceSyncCHROMIUM(); #if defined(OS_MACOSX) gl_->DescheduleUntilFinishedCHROMIUM(); #endif gl_->Flush(); gl_->GenSyncTokenCHROMIUM( fence_sync, color_buffer_for_mailbox->produce_sync_token.GetData()); } { bool is_overlay_candidate = color_buffer_for_mailbox->image_id != 0; bool secure_output_only = false; *out_mailbox = viz::TextureMailbox( color_buffer_for_mailbox->mailbox, color_buffer_for_mailbox->produce_sync_token, color_buffer_for_mailbox->parameters.target, gfx::Size(size_), is_overlay_candidate, secure_output_only); out_mailbox->set_color_space(color_space_); auto func = WTF::Bind(&DrawingBuffer::MailboxReleasedGpu, RefPtr<DrawingBuffer>(this), color_buffer_for_mailbox); *out_release_callback = cc::SingleReleaseCallback::Create( ConvertToBaseCallback(std::move(func))); } front_color_buffer_ = color_buffer_for_mailbox; contents_changed_ = false; SetBufferClearNeeded(true); return true; }
172,292
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 simple_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int error; if (type == ACL_TYPE_ACCESS) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return 0; if (error == 0) acl = NULL; } inode->i_ctime = current_time(inode); set_cached_acl(inode, type, acl); return 0; } Commit Message: tmpfs: clear S_ISGID when setting posix ACLs This change was missed the tmpfs modification in In CVE-2016-7097 commit 073931017b49 ("posix_acl: Clear SGID bit when setting file permissions") It can test by xfstest generic/375, which failed to clear setgid bit in the following test case on tmpfs: touch $testfile chown 100:100 $testfile chmod 2755 $testfile _runas -u 100 -g 101 -- setfacl -m u::rwx,g::rwx,o::rwx $testfile Signed-off-by: Gu Zheng <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID:
int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int error; if (type == ACL_TYPE_ACCESS) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; } inode->i_ctime = current_time(inode); set_cached_acl(inode, type, acl); return 0; }
168,386
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 SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); } Commit Message: CWE ID: CWE-399
static void SRP_user_pwd_free(SRP_user_pwd *user_pwd) void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); }
165,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void opl3_panning(int dev, int voice, int value) { devc->voc[voice].panning = value; } Commit Message: sound/oss/opl3: validate voice and channel indexes User-controllable indexes for voice and channel values may cause reading and writing beyond the bounds of their respective arrays, leading to potentially exploitable memory corruption. Validate these indexes. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-119
static void opl3_panning(int dev, int voice, int value) { if (voice < 0 || voice >= devc->nr_voice) return; devc->voc[voice].panning = value; }
165,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (str_len > INT_MAX) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } } Commit Message: Fix bug #72674 - check both curl_escape and curl_unescape CWE ID: CWE-119
PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ZEND_SIZE_T_INT_OVFL(str_len)) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } }
166,947
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 PPB_URLLoader_Impl::RunCallback(int32_t result) { if (!pending_callback_.get()) { CHECK(main_document_loader_); return; } TrackedCallback::ClearAndRun(&pending_callback_, result); } Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called. BUG=137778 Review URL: https://chromiumcodereview.appspot.com/10797037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void PPB_URLLoader_Impl::RunCallback(int32_t result) { if (!pending_callback_.get()) { CHECK(main_document_loader_); return; } // If |user_buffer_| was set as part of registering the callback, ensure // it got cleared since the callback is now free to delete it. DCHECK(!user_buffer_); TrackedCallback::ClearAndRun(&pending_callback_, result); }
170,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: rend_service_intro_established(origin_circuit_t *circuit, const uint8_t *request, size_t request_len) { rend_service_t *service; rend_intro_point_t *intro; char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; (void) request; (void) request_len; tor_assert(circuit->rend_data); /* XXX: This is version 2 specific (only supported one for now). */ const char *rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL); if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) { log_warn(LD_PROTOCOL, "received INTRO_ESTABLISHED cell on non-intro circuit."); goto err; } service = rend_service_get_by_pk_digest(rend_pk_digest); if (!service) { log_warn(LD_REND, "Unknown service on introduction circuit %u.", (unsigned)circuit->base_.n_circ_id); goto err; } /* We've just successfully established a intro circuit to one of our * introduction point, account for it. */ intro = find_intro_point(circuit); if (intro == NULL) { log_warn(LD_REND, "Introduction circuit established without a rend_intro_point_t " "object for service %s on circuit %u", safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id); goto err; } intro->circuit_established = 1; /* We might not have every introduction point ready but at this point we * know that the descriptor needs to be uploaded. */ service->desc_is_dirty = time(NULL); circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO); base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1, rend_pk_digest, REND_SERVICE_ID_LEN); log_info(LD_REND, "Received INTRO_ESTABLISHED cell on circuit %u for service %s", (unsigned)circuit->base_.n_circ_id, serviceid); /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully * used the circ */ pathbias_mark_use_success(circuit); return 0; err: circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL); return -1; } Commit Message: Fix log-uninitialized-stack bug in rend_service_intro_established. Fixes bug 23490; bugfix on 0.2.7.2-alpha. TROVE-2017-008 CVE-2017-0380 CWE ID: CWE-532
rend_service_intro_established(origin_circuit_t *circuit, const uint8_t *request, size_t request_len) { rend_service_t *service; rend_intro_point_t *intro; char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; (void) request; (void) request_len; tor_assert(circuit->rend_data); /* XXX: This is version 2 specific (only supported one for now). */ const char *rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL); if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) { log_warn(LD_PROTOCOL, "received INTRO_ESTABLISHED cell on non-intro circuit."); goto err; } service = rend_service_get_by_pk_digest(rend_pk_digest); if (!service) { log_warn(LD_REND, "Unknown service on introduction circuit %u.", (unsigned)circuit->base_.n_circ_id); goto err; } base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1, rend_pk_digest, REND_SERVICE_ID_LEN); /* We've just successfully established a intro circuit to one of our * introduction point, account for it. */ intro = find_intro_point(circuit); if (intro == NULL) { log_warn(LD_REND, "Introduction circuit established without a rend_intro_point_t " "object for service %s on circuit %u", safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id); goto err; } intro->circuit_established = 1; /* We might not have every introduction point ready but at this point we * know that the descriptor needs to be uploaded. */ service->desc_is_dirty = time(NULL); circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO); log_info(LD_REND, "Received INTRO_ESTABLISHED cell on circuit %u for service %s", (unsigned)circuit->base_.n_circ_id, serviceid); /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully * used the circ */ pathbias_mark_use_success(circuit); return 0; err: circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL); return -1; }
168,449
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 ClipboardMessageFilter::OnReadImageReply( SkBitmap bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector<unsigned char> png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast<const unsigned char*>(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector<gfx::PNGCodec::Comment>(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void ClipboardMessageFilter::OnReadImageReply( const SkBitmap& bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector<unsigned char> png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast<const unsigned char*>(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector<gfx::PNGCodec::Comment>(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); }
170,311
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 ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); } Commit Message: CWE ID:
static void ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); ncq_tfs->used = 0; }
165,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void XMLHttpRequest::abortError() { genericError(); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent)); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::abortError() void XMLHttpRequest::handleDidCancel() { m_exceptionCode = AbortError; handleDidFailGeneric(); if (!m_async) { m_state = DONE; return; } changeState(DONE); dispatchEventAndLoadEnd(eventNames().abortEvent); }
171,164
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 long EBMLHeader::Parse( IMkvReader* pReader, long long& pos) { assert(pReader); long long total, available; long status = pReader->Length(&total, &available); if (status < 0) //error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) //error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; //don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; //5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; //try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) //error return result; if (result == 0x0A45DFA3) //EBML Header ID { pos += len; //consume ID break; } ++pos; //throw away just the 0x1A byte, and try again } long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return result; if (result > 0) //need more data return result; assert(len > 0); assert(len <= 8); if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; //try again later result = ReadUInt(pReader, pos, len); if (result < 0) //error return result; pos += len; //consume size field if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader( pReader, pos, end, id, size); if (status < 0) //error return status; if (size == 0) //weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) //version { m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) //read version { m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) //max id length { m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) //max size length { m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) //doctype { if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) //error return status; } else if (id == 0x0287) //doctype version { m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) //doctype read version { m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } assert(pos == end); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long EBMLHeader::Parse( if (status < 0) // error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) // error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; // don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; // 5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; // try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; if (result == 0x0A45DFA3) { // EBML Header ID pos += len; // consume ID break; } ++pos; // throw away just the 0x1A byte, and try again } // pos designates start of size field // get length of size field long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return result; if (result > 0) // need more data return result; assert(len > 0); assert(len <= 8); if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; // try again later // get the EBML header size result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; pos += len; // consume size field // pos now designates start of payload if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader(pReader, pos, end, id, size); if (status < 0) // error return status; if (size == 0) // weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) { // version m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) { // read version m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) { // max id length m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) { // max size length m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) { // doctype if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) // error return status; } else if (id == 0x0287) { // doctype version m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) { // doctype read version m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } assert(pos == end); return 0; } Segment::Segment(IMkvReader* pReader, long long elem_start, // long long elem_size, long long start, long long size) : m_pReader(pReader), m_element_start(elem_start), // m_element_size(elem_size), m_start(start), m_size(size), m_pos(start), m_pUnknownSize(0), m_pSeekHead(NULL), m_pInfo(NULL), m_pTracks(NULL), m_pCues(NULL), m_pChapters(NULL), m_clusters(NULL), m_clusterCount(0), m_clusterPreloadCount(0), m_clusterSize(0) {} Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; assert(p); delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pSeekHead; } long long Segment::CreateInstance(IMkvReader* pReader, long long pos, Segment*& pSegment) { assert(pReader); assert(pos >= 0); pSegment = NULL; long long total, available; const long status = pReader->Length(&total, &available); if (status < 0) // error return status; if (available < 0) return -1; if ((total >= 0) && (available > total)) return -1; // I would assume that in practice this loop would execute // exactly once, but we allow for other elements (e.g. Void) // to immediately follow the EBML header. This is fine for // the source filter case (since the entire file is available), // but in the splitter case over a network we should probably // just give up early. We could for example decide only to // execute this loop a maximum of, say, 10 times. // TODO: // There is an implied "give up early" by only parsing up // to the available limit. We do do that, but only if the // total file size is unknown. We could decide to always // use what's available as our limit (irrespective of whether // we happen to know the total file length). This would have // as its sense "parse this much of the file before giving up", // which a slightly different sense from "try to parse up to // 10 EMBL elements before giving up". for (;;) { if ((total >= 0) && (pos >= total)) return E_FILE_FORMAT_INVALID; // Read ID long len; long long result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return id; pos += len; // consume ID // Read Size result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element // Pos now points to start of payload // Handle "unknown size" for live streaming of webm files. const long long unknown_size = (1LL << (7 * len)) - 1; if (id == 0x08538067) { // Segment ID if (size == unknown_size) size = -1; else if (total < 0) size = -1; else if ((pos + size) > total) size = -1; pSegment = new (std::nothrow) Segment(pReader, idpos, // elem_size pos, size); if (pSegment == 0) return -1; // generic error return 0; // success } if (size == unknown_size) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + size) > total)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; pos += size; // consume payload } }
174,405
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 jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (1 << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (1 << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } Commit Message: Fixed numerous integer overflow problems in the code for packet iterators in the JPC decoder. CWE ID: CWE-125
static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; }
169,442
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 HeapObjectHeader::Finalize(Address object, size_t object_size) { HeapAllocHooks::FreeHookIfEnabled(object); const GCInfo* gc_info = ThreadHeap::GcInfo(GcInfoIndex()); if (gc_info->HasFinalizer()) gc_info->finalize_(object); ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void HeapObjectHeader::Finalize(Address object, size_t object_size) { HeapAllocHooks::FreeHookIfEnabled(object); const GCInfo* gc_info = GCInfoTable::Get().GCInfoFromIndex(GcInfoIndex()); if (gc_info->HasFinalizer()) gc_info->finalize_(object); ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size); }
173,139
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: krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 *minor_status; gss_ctx_id_t *context_handle; gss_buffer_t interprocess_token; { krb5_context context = NULL; krb5_error_code kret; OM_uint32 retval; size_t bufsize, blen; krb5_gss_ctx_id_t ctx; krb5_octet *obuffer, *obp; /* Assume a tragic failure */ obuffer = (krb5_octet *) NULL; retval = GSS_S_FAILURE; *minor_status = 0; ctx = (krb5_gss_ctx_id_t) *context_handle; context = ctx->k5_context; kret = krb5_gss_ser_init(context); if (kret) goto error_out; /* Determine size needed for externalization of context */ bufsize = 0; if ((kret = kg_ctx_size(context, (krb5_pointer) ctx, &bufsize))) goto error_out; /* Allocate the buffer */ if ((obuffer = gssalloc_malloc(bufsize)) == NULL) { kret = ENOMEM; goto error_out; } obp = obuffer; blen = bufsize; /* Externalize the context */ if ((kret = kg_ctx_externalize(context, (krb5_pointer) ctx, &obp, &blen))) goto error_out; /* Success! Return the buffer */ interprocess_token->length = bufsize - blen; interprocess_token->value = obuffer; *minor_status = 0; retval = GSS_S_COMPLETE; /* Now, clean up the context state */ (void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL); *context_handle = GSS_C_NO_CONTEXT; return (GSS_S_COMPLETE); error_out: if (retval != GSS_S_COMPLETE) if (kret != 0 && context != 0) save_error_info((OM_uint32)kret, context); if (obuffer && bufsize) { memset(obuffer, 0, bufsize); xfree(obuffer); } if (*minor_status == 0) *minor_status = (OM_uint32) kret; return(retval); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 *minor_status; gss_ctx_id_t *context_handle; gss_buffer_t interprocess_token; { krb5_context context = NULL; krb5_error_code kret; OM_uint32 retval; size_t bufsize, blen; krb5_gss_ctx_id_t ctx; krb5_octet *obuffer, *obp; /* Assume a tragic failure */ obuffer = (krb5_octet *) NULL; retval = GSS_S_FAILURE; *minor_status = 0; ctx = (krb5_gss_ctx_id_t) *context_handle; if (ctx->terminated) { *minor_status = KG_CTX_INCOMPLETE; return (GSS_S_NO_CONTEXT); } context = ctx->k5_context; kret = krb5_gss_ser_init(context); if (kret) goto error_out; /* Determine size needed for externalization of context */ bufsize = 0; if ((kret = kg_ctx_size(context, (krb5_pointer) ctx, &bufsize))) goto error_out; /* Allocate the buffer */ if ((obuffer = gssalloc_malloc(bufsize)) == NULL) { kret = ENOMEM; goto error_out; } obp = obuffer; blen = bufsize; /* Externalize the context */ if ((kret = kg_ctx_externalize(context, (krb5_pointer) ctx, &obp, &blen))) goto error_out; /* Success! Return the buffer */ interprocess_token->length = bufsize - blen; interprocess_token->value = obuffer; *minor_status = 0; retval = GSS_S_COMPLETE; /* Now, clean up the context state */ (void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL); *context_handle = GSS_C_NO_CONTEXT; return (GSS_S_COMPLETE); error_out: if (retval != GSS_S_COMPLETE) if (kret != 0 && context != 0) save_error_info((OM_uint32)kret, context); if (obuffer && bufsize) { memset(obuffer, 0, bufsize); xfree(obuffer); } if (*minor_status == 0) *minor_status = (OM_uint32) kret; return(retval); }
166,814
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: __u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr, __be16 sport, __be16 dport) { __u32 seq; __u32 hash[12]; struct keydata *keyptr = get_keyptr(); /* The procedure is the same as for IPv4, but addresses are longer. * Thus we must use twothirdsMD4Transform. */ memcpy(hash, saddr, 16); hash[4] = ((__force u16)sport << 16) + (__force u16)dport; memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7); seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK; seq += keyptr->count; seq += ktime_to_ns(ktime_get_real()); return seq; } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
__u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,
165,769
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 DevToolsSession::AddHandler( std::unique_ptr<protocol::DevToolsDomainHandler> handler) { handler->Wire(dispatcher_.get()); handler->SetRenderer(process_, host_); handlers_[handler->name()] = std::move(handler); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DevToolsSession::AddHandler( std::unique_ptr<protocol::DevToolsDomainHandler> handler) { handler->Wire(dispatcher_.get()); handler->SetRenderer(process_host_id_, host_); handlers_[handler->name()] = std::move(handler); }
172,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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: TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tmpResult; TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; while( resultKey->t.size < bytes ) { i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j++] = (TPM2B_DIGEST *)0; rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult ); if( rval != TPM_RC_SUCCESS ) { return( rval ); } bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { return TSS2_SYS_RC_BAD_VALUE; } } resultKey->t.size = bytes; return TPM_RC_SUCCESS; } Commit Message: kdfa: use openssl for hmac not tpm While not reachable in the current code base tools, a potential security bug lurked in tpm_kdfa(). If using that routine for an hmac authorization, the hmac was calculated using the tpm. A user of an object wishing to authenticate via hmac, would expect that the password is never sent to the tpm. However, since the hmac calculation relies on password, and is performed by the tpm, the password ends up being sent in plain text to the tpm. The fix is to use openssl to generate the hmac on the host. Fixes: CVE-2017-7524 Signed-off-by: William Roberts <[email protected]> CWE ID: CWE-522
TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM_RC tpm_kdfa(TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval = TPM_RC_SUCCESS; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; const EVP_MD *md = tpm_algorithm_to_openssl_digest(hashAlg); if (!md) { LOG_ERR("Algorithm not supported for hmac: %x", hashAlg); return TPM_RC_HASH; } HMAC_CTX ctx; HMAC_CTX_init(&ctx); int rc = HMAC_Init_ex(&ctx, key->buffer, key->size, md, NULL); if (!rc) { LOG_ERR("HMAC Init failed: %s", ERR_error_string(rc, NULL)); return TPM_RC_MEMORY; } // TODO Why is this a loop? It appears to only execute once. while( resultKey->t.size < bytes ) { TPM2B_DIGEST tmpResult; i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j] = (TPM2B_DIGEST *)0; int c; for(c=0; c < j; c++) { TPM2B_DIGEST *digest = bufferList[c]; int rc = HMAC_Update(&ctx, digest->b.buffer, digest->b.size); if (!rc) { LOG_ERR("HMAC Update failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } } unsigned size = sizeof(tmpResult.t.buffer); int rc = HMAC_Final(&ctx, tmpResult.t.buffer, &size); if (!rc) { LOG_ERR("HMAC Final failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } tmpResult.t.size = size; bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { rval = TSS2_SYS_RC_BAD_VALUE; goto err; } } resultKey->t.size = bytes; err: HMAC_CTX_cleanup(&ctx); return rval; }
168,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 ProcessMSLScript(const ImageInfo *image_info, Image **image,ExceptionInfo *exception) { char message[MagickPathExtent]; Image *msl_image; int status; ssize_t n; MSLInfo msl_info; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(image != (Image **) NULL); msl_image=AcquireImage(image_info,exception); status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", msl_image->filename); msl_image=DestroyImageList(msl_image); return(MagickFalse); } msl_image->columns=1; msl_image->rows=1; /* Parse MSL file. */ (void) ResetMagickMemory(&msl_info,0,sizeof(msl_info)); msl_info.exception=exception; msl_info.image_info=(ImageInfo **) AcquireMagickMemory( sizeof(*msl_info.image_info)); msl_info.draw_info=(DrawInfo **) AcquireMagickMemory( sizeof(*msl_info.draw_info)); /* top of the stack is the MSL file itself */ msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image)); msl_info.attributes=(Image **) AcquireMagickMemory( sizeof(*msl_info.attributes)); msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory( sizeof(*msl_info.group_info)); if ((msl_info.image_info == (ImageInfo **) NULL) || (msl_info.image == (Image **) NULL) || (msl_info.attributes == (Image **) NULL) || (msl_info.group_info == (MSLGroupInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"UnableToInterpretMSLImage"); *msl_info.image_info=CloneImageInfo(image_info); *msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); *msl_info.attributes=AcquireImage(image_info,exception); msl_info.group_info[0].numImages=0; /* the first slot is used to point to the MSL file image */ *msl_info.image=msl_image; if (*image != (Image *) NULL) MSLPushImage(&msl_info,*image); (void) xmlSubstituteEntitiesDefault(1); (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=MSLInternalSubset; sax_modules.isStandalone=MSLIsStandalone; sax_modules.hasInternalSubset=MSLHasInternalSubset; sax_modules.hasExternalSubset=MSLHasExternalSubset; sax_modules.resolveEntity=MSLResolveEntity; sax_modules.getEntity=MSLGetEntity; sax_modules.entityDecl=MSLEntityDeclaration; sax_modules.notationDecl=MSLNotationDeclaration; sax_modules.attributeDecl=MSLAttributeDeclaration; sax_modules.elementDecl=MSLElementDeclaration; sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration; sax_modules.setDocumentLocator=MSLSetDocumentLocator; sax_modules.startDocument=MSLStartDocument; sax_modules.endDocument=MSLEndDocument; sax_modules.startElement=MSLStartElement; sax_modules.endElement=MSLEndElement; sax_modules.reference=MSLReference; sax_modules.characters=MSLCharacters; sax_modules.ignorableWhitespace=MSLIgnorableWhitespace; sax_modules.processingInstruction=MSLProcessingInstructions; sax_modules.comment=MSLComment; sax_modules.warning=MSLWarning; sax_modules.error=MSLError; sax_modules.fatalError=MSLError; sax_modules.getParameterEntity=MSLGetParameterEntity; sax_modules.cdataBlock=MSLCDataBlock; sax_modules.externalSubset=MSLExternalSubset; sax_handler=(&sax_modules); msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0, msl_image->filename); while (ReadBlobString(msl_image,message) != (char *) NULL) { n=(ssize_t) strlen(message); if (n == 0) continue; status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse); if (status != 0) break; (void) xmlParseChunk(msl_info.parser," ",1,MagickFalse); if (msl_info.exception->severity >= ErrorException) break; } if (msl_info.exception->severity == UndefinedException) (void) xmlParseChunk(msl_info.parser," ",1,MagickTrue); xmlFreeParserCtxt(msl_info.parser); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (*image == (Image *) NULL) *image=(*msl_info.image); if (msl_info.exception->severity != UndefinedException) return(MagickFalse); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/636 CWE ID: CWE-772
static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info, Image **image,ExceptionInfo *exception) { char message[MagickPathExtent]; Image *msl_image; int status; ssize_t n; MSLInfo msl_info; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(image != (Image **) NULL); msl_image=AcquireImage(image_info,exception); status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", msl_image->filename); msl_image=DestroyImageList(msl_image); return(MagickFalse); } msl_image->columns=1; msl_image->rows=1; /* Parse MSL file. */ (void) ResetMagickMemory(&msl_info,0,sizeof(msl_info)); msl_info.exception=exception; msl_info.image_info=(ImageInfo **) AcquireMagickMemory( sizeof(*msl_info.image_info)); msl_info.draw_info=(DrawInfo **) AcquireMagickMemory( sizeof(*msl_info.draw_info)); /* top of the stack is the MSL file itself */ msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image)); msl_info.attributes=(Image **) AcquireMagickMemory( sizeof(*msl_info.attributes)); msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory( sizeof(*msl_info.group_info)); if ((msl_info.image_info == (ImageInfo **) NULL) || (msl_info.image == (Image **) NULL) || (msl_info.attributes == (Image **) NULL) || (msl_info.group_info == (MSLGroupInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"UnableToInterpretMSLImage"); *msl_info.image_info=CloneImageInfo(image_info); *msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); *msl_info.attributes=AcquireImage(image_info,exception); msl_info.group_info[0].numImages=0; /* the first slot is used to point to the MSL file image */ *msl_info.image=msl_image; if (*image != (Image *) NULL) MSLPushImage(&msl_info,*image); (void) xmlSubstituteEntitiesDefault(1); (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=MSLInternalSubset; sax_modules.isStandalone=MSLIsStandalone; sax_modules.hasInternalSubset=MSLHasInternalSubset; sax_modules.hasExternalSubset=MSLHasExternalSubset; sax_modules.resolveEntity=MSLResolveEntity; sax_modules.getEntity=MSLGetEntity; sax_modules.entityDecl=MSLEntityDeclaration; sax_modules.notationDecl=MSLNotationDeclaration; sax_modules.attributeDecl=MSLAttributeDeclaration; sax_modules.elementDecl=MSLElementDeclaration; sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration; sax_modules.setDocumentLocator=MSLSetDocumentLocator; sax_modules.startDocument=MSLStartDocument; sax_modules.endDocument=MSLEndDocument; sax_modules.startElement=MSLStartElement; sax_modules.endElement=MSLEndElement; sax_modules.reference=MSLReference; sax_modules.characters=MSLCharacters; sax_modules.ignorableWhitespace=MSLIgnorableWhitespace; sax_modules.processingInstruction=MSLProcessingInstructions; sax_modules.comment=MSLComment; sax_modules.warning=MSLWarning; sax_modules.error=MSLError; sax_modules.fatalError=MSLError; sax_modules.getParameterEntity=MSLGetParameterEntity; sax_modules.cdataBlock=MSLCDataBlock; sax_modules.externalSubset=MSLExternalSubset; sax_handler=(&sax_modules); msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0, msl_image->filename); while (ReadBlobString(msl_image,message) != (char *) NULL) { n=(ssize_t) strlen(message); if (n == 0) continue; status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse); if (status != 0) break; (void) xmlParseChunk(msl_info.parser," ",1,MagickFalse); if (msl_info.exception->severity >= ErrorException) break; } if (msl_info.exception->severity == UndefinedException) (void) xmlParseChunk(msl_info.parser," ",1,MagickTrue); /* Free resources. */ xmlFreeParserCtxt(msl_info.parser); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (*image == (Image *) NULL) *image=(*msl_info.image); *msl_info.image_info=DestroyImageInfo(*msl_info.image_info); msl_info.image_info=(ImageInfo **) RelinquishMagickMemory( msl_info.image_info); *msl_info.draw_info=DestroyDrawInfo(*msl_info.draw_info); msl_info.draw_info=(DrawInfo **) RelinquishMagickMemory(msl_info.draw_info); msl_info.image=(Image **) RelinquishMagickMemory(msl_info.image); *msl_info.attributes=DestroyImage(*msl_info.attributes); msl_info.attributes=(Image **) RelinquishMagickMemory(msl_info.attributes); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (msl_info.exception->severity != UndefinedException) return(MagickFalse); return(MagickTrue); }
167,985
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 nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size) { ssize_t ret; uint8_t *buffer = g_malloc(MIN(65536, size)); while (size > 0) { size_t count = MIN(65536, size); ret = nbd_negotiate_read(ioc, buffer, count); if (ret < 0) { g_free(buffer); return ret; } size -= count; } g_free(buffer); return 0; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
165,453
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 InitOnIOThread(const std::string& mime_type) { PluginServiceImpl* plugin_service = PluginServiceImpl::GetInstance(); std::vector<WebPluginInfo> plugins; plugin_service->GetPluginInfoArray( GURL(), mime_type, false, &plugins, NULL); base::FilePath plugin_path; if (!plugins.empty()) // May be empty for some tests. plugin_path = plugins[0].path; DCHECK_CURRENTLY_ON(BrowserThread::IO); remove_start_time_ = base::Time::Now(); is_removing_ = true; AddRef(); PepperPluginInfo* pepper_info = plugin_service->GetRegisteredPpapiPluginInfo(plugin_path); if (pepper_info) { plugin_name_ = pepper_info->name; plugin_service->OpenChannelToPpapiBroker(0, plugin_path, this); } else { plugin_service->OpenChannelToNpapiPlugin( 0, 0, GURL(), GURL(), mime_type, this); } } Commit Message: Do not attempt to open a channel to a plugin in Plugin Data Remover if there are no plugins available. BUG=485886 Review URL: https://codereview.chromium.org/1144353003 Cr-Commit-Position: refs/heads/master@{#331168} CWE ID:
void InitOnIOThread(const std::string& mime_type) { PluginServiceImpl* plugin_service = PluginServiceImpl::GetInstance(); std::vector<WebPluginInfo> plugins; plugin_service->GetPluginInfoArray( GURL(), mime_type, false, &plugins, NULL); if (plugins.empty()) { // May be empty for some tests and on the CrOS login OOBE screen. event_->Signal(); return; } base::FilePath plugin_path = plugins[0].path; DCHECK_CURRENTLY_ON(BrowserThread::IO); remove_start_time_ = base::Time::Now(); is_removing_ = true; AddRef(); PepperPluginInfo* pepper_info = plugin_service->GetRegisteredPpapiPluginInfo(plugin_path); if (pepper_info) { plugin_name_ = pepper_info->name; plugin_service->OpenChannelToPpapiBroker(0, plugin_path, this); } else { plugin_service->OpenChannelToNpapiPlugin( 0, 0, GURL(), GURL(), mime_type, this); } }
171,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: void GpuProcessHost::OnChannelEstablished( const IPC::ChannelHandle& channel_handle) { DCHECK(gpu_process_); EstablishChannelCallback callback = channel_requests_.front(); channel_requests_.pop(); if (!channel_handle.name.empty() && !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) { Send(new GpuMsg_CloseChannel(channel_handle)); EstablishChannelError(callback, IPC::ChannelHandle(), base::kNullProcessHandle, content::GPUInfo()); RouteOnUIThread(GpuHostMsg_OnLogMessage( logging::LOG_WARNING, "WARNING", "Hardware acceleration is unavailable.")); return; } callback.Run(channel_handle, gpu_process_, GpuDataManagerImpl::GetInstance()->GetGPUInfo()); } 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 GpuProcessHost::OnChannelEstablished( const IPC::ChannelHandle& channel_handle) { EstablishChannelCallback callback = channel_requests_.front(); channel_requests_.pop(); if (!channel_handle.name.empty() && !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) { Send(new GpuMsg_CloseChannel(channel_handle)); EstablishChannelError(callback, IPC::ChannelHandle(), base::kNullProcessHandle, content::GPUInfo()); RouteOnUIThread(GpuHostMsg_OnLogMessage( logging::LOG_WARNING, "WARNING", "Hardware acceleration is unavailable.")); return; } callback.Run(channel_handle, GpuDataManagerImpl::GetInstance()->GetGPUInfo()); }
170,922
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 ServiceWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); state_ = WORKER_TERMINATED; agent_ptr_.reset(); for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(nullptr, nullptr); } 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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void ServiceWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); state_ = WORKER_TERMINATED; agent_ptr_.reset(); for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(-1, nullptr); }
172,784
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 FFmpegVideoDecodeEngine::Initialize( MessageLoop* message_loop, VideoDecodeEngine::EventHandler* event_handler, VideoDecodeContext* context, const VideoDecoderConfig& config) { static const int kDecodeThreads = 2; static const int kMaxDecodeThreads = 16; codec_context_ = avcodec_alloc_context(); codec_context_->pix_fmt = PIX_FMT_YUV420P; codec_context_->codec_type = AVMEDIA_TYPE_VIDEO; codec_context_->codec_id = VideoCodecToCodecID(config.codec()); codec_context_->coded_width = config.width(); codec_context_->coded_height = config.height(); frame_rate_numerator_ = config.frame_rate_numerator(); frame_rate_denominator_ = config.frame_rate_denominator(); if (config.extra_data() != NULL) { codec_context_->extradata_size = config.extra_data_size(); codec_context_->extradata = reinterpret_cast<uint8_t*>(av_malloc(config.extra_data_size())); memcpy(codec_context_->extradata, config.extra_data(), config.extra_data_size()); } codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK; codec_context_->error_recognition = FF_ER_CAREFUL; AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ? 1 : kDecodeThreads; const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads)); if ((!threads.empty() && !base::StringToInt(threads, &decode_threads)) || decode_threads < 0 || decode_threads > kMaxDecodeThreads) { decode_threads = kDecodeThreads; } av_frame_.reset(avcodec_alloc_frame()); VideoCodecInfo info; info.success = false; info.provides_buffers = true; info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY; info.stream_info.surface_format = GetSurfaceFormat(); info.stream_info.surface_width = config.surface_width(); info.stream_info.surface_height = config.surface_height(); bool buffer_allocated = true; frame_queue_available_.clear(); for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) { scoped_refptr<VideoFrame> video_frame; VideoFrame::CreateFrame(VideoFrame::YV12, config.width(), config.height(), kNoTimestamp, kNoTimestamp, &video_frame); if (!video_frame.get()) { buffer_allocated = false; break; } frame_queue_available_.push_back(video_frame); } if (codec && avcodec_thread_init(codec_context_, decode_threads) >= 0 && avcodec_open(codec_context_, codec) >= 0 && av_frame_.get() && buffer_allocated) { info.success = true; } event_handler_ = event_handler; event_handler_->OnInitializeComplete(info); } Commit Message: Don't forget the ffmpeg input buffer padding when allocating a codec's extradata buffer. BUG=82438 Review URL: http://codereview.chromium.org/7137002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88354 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void FFmpegVideoDecodeEngine::Initialize( MessageLoop* message_loop, VideoDecodeEngine::EventHandler* event_handler, VideoDecodeContext* context, const VideoDecoderConfig& config) { static const int kDecodeThreads = 2; static const int kMaxDecodeThreads = 16; codec_context_ = avcodec_alloc_context(); codec_context_->pix_fmt = PIX_FMT_YUV420P; codec_context_->codec_type = AVMEDIA_TYPE_VIDEO; codec_context_->codec_id = VideoCodecToCodecID(config.codec()); codec_context_->coded_width = config.width(); codec_context_->coded_height = config.height(); frame_rate_numerator_ = config.frame_rate_numerator(); frame_rate_denominator_ = config.frame_rate_denominator(); if (config.extra_data() != NULL) { codec_context_->extradata_size = config.extra_data_size(); codec_context_->extradata = reinterpret_cast<uint8_t*>( av_malloc(config.extra_data_size() + FF_INPUT_BUFFER_PADDING_SIZE)); memcpy(codec_context_->extradata, config.extra_data(), config.extra_data_size()); memset(codec_context_->extradata + config.extra_data_size(), '\0', FF_INPUT_BUFFER_PADDING_SIZE); } codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK; codec_context_->error_recognition = FF_ER_CAREFUL; AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ? 1 : kDecodeThreads; const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads)); if ((!threads.empty() && !base::StringToInt(threads, &decode_threads)) || decode_threads < 0 || decode_threads > kMaxDecodeThreads) { decode_threads = kDecodeThreads; } av_frame_.reset(avcodec_alloc_frame()); VideoCodecInfo info; info.success = false; info.provides_buffers = true; info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY; info.stream_info.surface_format = GetSurfaceFormat(); info.stream_info.surface_width = config.surface_width(); info.stream_info.surface_height = config.surface_height(); bool buffer_allocated = true; frame_queue_available_.clear(); for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) { scoped_refptr<VideoFrame> video_frame; VideoFrame::CreateFrame(VideoFrame::YV12, config.width(), config.height(), kNoTimestamp, kNoTimestamp, &video_frame); if (!video_frame.get()) { buffer_allocated = false; break; } frame_queue_available_.push_back(video_frame); } if (codec && avcodec_thread_init(codec_context_, decode_threads) >= 0 && avcodec_open(codec_context_, codec) >= 0 && av_frame_.get() && buffer_allocated) { info.success = true; } event_handler_ = event_handler; event_handler_->OnInitializeComplete(info); }
170,304
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 DocumentLoader::DidInstallNewDocument(Document* document) { document->SetReadyState(Document::kLoading); document->InitContentSecurityPolicy(content_security_policy_.Release()); if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); String suborigin_header = response_.HttpHeaderField(HTTPNames::Suborigin); if (!suborigin_header.IsNull()) { Vector<String> messages; Suborigin suborigin; if (ParseSuboriginHeader(suborigin_header, &suborigin, messages)) document->EnforceSuborigin(suborigin); for (auto& message : messages) { document->AddConsoleMessage( ConsoleMessage::Create(kSecurityMessageSource, kErrorMessageLevel, "Error with Suborigin header: " + message)); } } document->GetClientHintsPreferences().UpdateFrom(client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(HTTPNames::Content_Language); if (!header_content_language.IsEmpty()) { size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(HTTPNames::Origin_Trial)); String referrer_policy_header = response_.HttpHeaderField(HTTPNames::Referrer_Policy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } GetLocalFrameClient().DidCreateNewDocument(); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
void DocumentLoader::DidInstallNewDocument(Document* document) { void DocumentLoader::DidInstallNewDocument(Document* document, InstallNewDocumentReason reason) { document->SetReadyState(Document::kLoading); if (content_security_policy_) { document->InitContentSecurityPolicy(content_security_policy_.Release()); } if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); String suborigin_header = response_.HttpHeaderField(HTTPNames::Suborigin); if (!suborigin_header.IsNull()) { Vector<String> messages; Suborigin suborigin; if (ParseSuboriginHeader(suborigin_header, &suborigin, messages)) document->EnforceSuborigin(suborigin); for (auto& message : messages) { document->AddConsoleMessage( ConsoleMessage::Create(kSecurityMessageSource, kErrorMessageLevel, "Error with Suborigin header: " + message)); } } document->GetClientHintsPreferences().UpdateFrom(client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(HTTPNames::Content_Language); if (!header_content_language.IsEmpty()) { size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(HTTPNames::Origin_Trial)); String referrer_policy_header = response_.HttpHeaderField(HTTPNames::Referrer_Policy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } GetLocalFrameClient().DidCreateNewDocument(); }
172,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageCapture::ResolveWithMediaTrackConstraints( MediaTrackConstraints constraints, ScriptPromiseResolver* resolver) { DCHECK(resolver); resolver->Resolve(constraints); } Commit Message: Convert MediaTrackConstraints to a ScriptValue IDLDictionaries such as MediaTrackConstraints should not be stored on the heap which would happen when binding one as a parameter to a callback. This change converts the object to a ScriptValue ahead of time. This is fine because the value will be passed to a ScriptPromiseResolver that will converted it to a V8 value if it isn't already. Bug: 759457 Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8 Reviewed-on: https://chromium-review.googlesource.com/701358 Reviewed-by: Kentaro Hara <[email protected]> Commit-Queue: Reilly Grant <[email protected]> Cr-Commit-Position: refs/heads/master@{#507177} CWE ID: CWE-416
void ImageCapture::ResolveWithMediaTrackConstraints( ScriptValue constraints, ScriptPromiseResolver* resolver) { DCHECK(resolver); resolver->Resolve(constraints); }
172,962
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_gray_to_rgb_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_gray_to_rgb_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; }
173,635
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 __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd3_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); if (!IS_POSIXACL(inode) || !inode->i_op->set_acl) { error = -EOPNOTSUPP; goto out_errno; } error = fh_want_write(fh); if (error) goto out_errno; error = inode->i_op->set_acl(inode, argp->acl_access, ACL_TYPE_ACCESS); if (error) goto out_drop_write; error = inode->i_op->set_acl(inode, argp->acl_default, ACL_TYPE_DEFAULT); out_drop_write: fh_drop_write(fh); out_errno: nfserr = nfserrno(error); out: /* argp->acl_{access,default} may have been allocated in nfs3svc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); RETURN_STATUS(nfserr); } Commit Message: nfsd: check permissions when setting ACLs Use set_posix_acl, which includes proper permission checks, instead of calling ->set_acl directly. Without this anyone may be able to grant themselves permissions to a file by setting the ACL. Lock the inode to make the new checks atomic with respect to set_acl. (Also, nfsd was the only caller of set_acl not locking the inode, so I suspect this may fix other races.) This also simplifies the code, and ensures our ACLs are checked by posix_acl_valid. The permission checks and the inode locking were lost with commit 4ac7249e, which changed nfsd to use the set_acl inode operation directly instead of going through xattr handlers. Reported-by: David Sinquin <[email protected]> [[email protected]: use set_posix_acl] Fixes: 4ac7249e Cc: Christoph Hellwig <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-284
static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd3_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); error = fh_want_write(fh); if (error) goto out_errno; fh_lock(fh); error = set_posix_acl(inode, ACL_TYPE_ACCESS, argp->acl_access); if (error) goto out_drop_lock; error = set_posix_acl(inode, ACL_TYPE_DEFAULT, argp->acl_default); out_drop_lock: fh_unlock(fh); fh_drop_write(fh); out_errno: nfserr = nfserrno(error); out: /* argp->acl_{access,default} may have been allocated in nfs3svc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); RETURN_STATUS(nfserr); }
167,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: void qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); } 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
void qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); }
169,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: QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, QuicStringPiece data, QuicTime timestamp, size_t* const bytes_buffered, std::string* error_details) { CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed"; *bytes_buffered = 0; QuicStreamOffset offset = starting_offset; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } std::list<Gap>::iterator current_gap = gaps_.begin(); while (current_gap != gaps_.end() && current_gap->end_offset <= offset) { ++current_gap; } DCHECK(current_gap != gaps_.end()); if (offset < current_gap->begin_offset && offset + size <= current_gap->begin_offset) { QUIC_DVLOG(1) << "Duplicated data at offset: " << offset << " length: " << size; return QUIC_NO_ERROR; } if (offset < current_gap->begin_offset && offset + size > current_gap->begin_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat("Beginning of received data overlaps with buffered data.\n", "New frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", GapsDebugString(), "\n", "Current gaps: ", ReceivedFramesDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > current_gap->end_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat( "End of received data overlaps with buffered data.\nNew frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", ReceivedFramesDebugString(), "\n", "Current gaps: ", GapsDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (current_gap->begin_offset != starting_offset && current_gap->end_offset != starting_offset + data.length() && gaps_.size() >= kMaxNumGapsAllowed) { *error_details = "Too many gaps created for this stream."; return QUIC_TOO_MANY_FRAME_GAPS; } size_t total_written = 0; size_t source_remaining = size; const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); DCHECK_GT(blocks_count_, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (blocks_ == nullptr) { blocks_.reset(new BufferBlock*[blocks_count_]()); for (size_t i = 0; i < blocks_count_; ++i) { blocks_[i] = nullptr; } } if (write_block_num >= blocks_count_) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " blocks_count_ = ", blocks_count_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Gaps: ", GapsDebugString(), " Remaining frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; total_written += bytes_to_copy; } DCHECK_GT(total_written, 0u); *bytes_buffered = total_written; UpdateGapList(current_gap, starting_offset, total_written); frame_arrival_time_map_.insert( std::make_pair(starting_offset, FrameInfo(size, timestamp))); num_bytes_buffered_ += total_written; return QUIC_NO_ERROR; } Commit Message: Fix OOB Write in QuicStreamSequencerBuffer::OnStreamData BUG=778505 Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I1dfd1d26a2c7ee8fe047f7fe6e4ac2e9b97efa52 Reviewed-on: https://chromium-review.googlesource.com/748282 Commit-Queue: Ryan Hamilton <[email protected]> Reviewed-by: Zhongyi Shi <[email protected]> Cr-Commit-Position: refs/heads/master@{#513144} CWE ID: CWE-787
QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, QuicStringPiece data, QuicTime timestamp, size_t* const bytes_buffered, std::string* error_details) { CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed"; *bytes_buffered = 0; QuicStreamOffset offset = starting_offset; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } std::list<Gap>::iterator current_gap = gaps_.begin(); while (current_gap != gaps_.end() && current_gap->end_offset <= offset) { ++current_gap; } if (current_gap == gaps_.end()) { *error_details = "Received stream data outside of maximum range."; return QUIC_INTERNAL_ERROR; } if (offset < current_gap->begin_offset && offset + size <= current_gap->begin_offset) { QUIC_DVLOG(1) << "Duplicated data at offset: " << offset << " length: " << size; return QUIC_NO_ERROR; } if (offset < current_gap->begin_offset && offset + size > current_gap->begin_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat("Beginning of received data overlaps with buffered data.\n", "New frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", GapsDebugString(), "\n", "Current gaps: ", ReceivedFramesDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > current_gap->end_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat( "End of received data overlaps with buffered data.\nNew frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", ReceivedFramesDebugString(), "\n", "Current gaps: ", GapsDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_ || offset + size < offset) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (current_gap->begin_offset != starting_offset && current_gap->end_offset != starting_offset + data.length() && gaps_.size() >= kMaxNumGapsAllowed) { *error_details = "Too many gaps created for this stream."; return QUIC_TOO_MANY_FRAME_GAPS; } size_t total_written = 0; size_t source_remaining = size; const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); DCHECK_GT(blocks_count_, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (blocks_ == nullptr) { blocks_.reset(new BufferBlock*[blocks_count_]()); for (size_t i = 0; i < blocks_count_; ++i) { blocks_[i] = nullptr; } } if (write_block_num >= blocks_count_) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " blocks_count_ = ", blocks_count_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Gaps: ", GapsDebugString(), " Remaining frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; total_written += bytes_to_copy; } DCHECK_GT(total_written, 0u); *bytes_buffered = total_written; UpdateGapList(current_gap, starting_offset, total_written); frame_arrival_time_map_.insert( std::make_pair(starting_offset, FrameInfo(size, timestamp))); num_bytes_buffered_ += total_written; return QUIC_NO_ERROR; }
172,923
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 mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_restartable( grp, r, s, d, buf, blen, f_rng, p_rng, NULL ) ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); /* Use the same RNG for both blinding and ephemeral key generation */ return( ecdsa_sign_restartable( grp, r, s, d, buf, blen, f_rng, p_rng, f_rng, p_rng, NULL ) ); }
169,507
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 SyncManager::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, bool enable_sync_tabs_for_other_clients, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(post_factory); DVLOG(1) << "SyncManager starting Init..."; std::string server_string(sync_server_and_path); return data_->Init(database_location, event_handler, server_string, sync_server_port, use_ssl, blocking_task_runner, post_factory, registrar, extensions_activity_monitor, change_delegate, user_agent, credentials, enable_sync_tabs_for_other_clients, sync_notifier, restored_key_for_bootstrapping, testing_mode, encryptor, unrecoverable_error_handler, report_unrecoverable_error_function); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
bool SyncManager::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(post_factory); DVLOG(1) << "SyncManager starting Init..."; std::string server_string(sync_server_and_path); return data_->Init(database_location, event_handler, server_string, sync_server_port, use_ssl, blocking_task_runner, post_factory, registrar, extensions_activity_monitor, change_delegate, user_agent, credentials, sync_notifier, restored_key_for_bootstrapping, testing_mode, encryptor, unrecoverable_error_handler, report_unrecoverable_error_function); }
170,792
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 nl80211_trigger_scan(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct cfg80211_scan_request *request; struct nlattr *attr; struct wiphy *wiphy; int err, tmp, n_ssids = 0, n_channels, i; enum ieee80211_band band; size_t ie_len; if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE])) return -EINVAL; wiphy = &rdev->wiphy; if (!rdev->ops->scan) return -EOPNOTSUPP; if (rdev->scan_req) return -EBUSY; if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) { n_channels = validate_scan_freqs( info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]); if (!n_channels) return -EINVAL; } else { n_channels = 0; for (band = 0; band < IEEE80211_NUM_BANDS; band++) if (wiphy->bands[band]) n_channels += wiphy->bands[band]->n_channels; } if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) n_ssids++; if (n_ssids > wiphy->max_scan_ssids) return -EINVAL; if (info->attrs[NL80211_ATTR_IE]) ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); else ie_len = 0; if (ie_len > wiphy->max_scan_ie_len) return -EINVAL; request = kzalloc(sizeof(*request) + sizeof(*request->ssids) * n_ssids + sizeof(*request->channels) * n_channels + ie_len, GFP_KERNEL); if (!request) return -ENOMEM; if (n_ssids) request->ssids = (void *)&request->channels[n_channels]; request->n_ssids = n_ssids; if (ie_len) { if (request->ssids) request->ie = (void *)(request->ssids + n_ssids); else request->ie = (void *)(request->channels + n_channels); } i = 0; if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) { /* user specified, bail out if channel not found */ nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) { struct ieee80211_channel *chan; chan = ieee80211_get_channel(wiphy, nla_get_u32(attr)); if (!chan) { err = -EINVAL; goto out_free; } /* ignore disabled channels */ if (chan->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i] = chan; i++; } } else { /* all channels */ for (band = 0; band < IEEE80211_NUM_BANDS; band++) { int j; if (!wiphy->bands[band]) continue; for (j = 0; j < wiphy->bands[band]->n_channels; j++) { struct ieee80211_channel *chan; chan = &wiphy->bands[band]->channels[j]; if (chan->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i] = chan; i++; } } } if (!i) { err = -EINVAL; goto out_free; } request->n_channels = i; i = 0; if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) { nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) { if (request->ssids[i].ssid_len > IEEE80211_MAX_SSID_LEN) { err = -EINVAL; goto out_free; } memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr)); request->ssids[i].ssid_len = nla_len(attr); i++; } } if (info->attrs[NL80211_ATTR_IE]) { request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); memcpy((void *)request->ie, nla_data(info->attrs[NL80211_ATTR_IE]), request->ie_len); } request->dev = dev; request->wiphy = &rdev->wiphy; rdev->scan_req = request; err = rdev->ops->scan(&rdev->wiphy, dev, request); if (!err) { nl80211_send_scan_start(rdev, dev); dev_hold(dev); } else { out_free: rdev->scan_req = NULL; kfree(request); } return err; } Commit Message: nl80211: fix check for valid SSID size in scan operations In both trigger_scan and sched_scan operations, we were checking for the SSID length before assigning the value correctly. Since the memory was just kzalloc'ed, the check was always failing and SSID with over 32 characters were allowed to go through. This was causing a buffer overflow when copying the actual SSID to the proper place. This bug has been there since 2.6.29-rc4. Cc: [email protected] Signed-off-by: Luciano Coelho <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-119
static int nl80211_trigger_scan(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct cfg80211_scan_request *request; struct nlattr *attr; struct wiphy *wiphy; int err, tmp, n_ssids = 0, n_channels, i; enum ieee80211_band band; size_t ie_len; if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE])) return -EINVAL; wiphy = &rdev->wiphy; if (!rdev->ops->scan) return -EOPNOTSUPP; if (rdev->scan_req) return -EBUSY; if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) { n_channels = validate_scan_freqs( info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]); if (!n_channels) return -EINVAL; } else { n_channels = 0; for (band = 0; band < IEEE80211_NUM_BANDS; band++) if (wiphy->bands[band]) n_channels += wiphy->bands[band]->n_channels; } if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) n_ssids++; if (n_ssids > wiphy->max_scan_ssids) return -EINVAL; if (info->attrs[NL80211_ATTR_IE]) ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); else ie_len = 0; if (ie_len > wiphy->max_scan_ie_len) return -EINVAL; request = kzalloc(sizeof(*request) + sizeof(*request->ssids) * n_ssids + sizeof(*request->channels) * n_channels + ie_len, GFP_KERNEL); if (!request) return -ENOMEM; if (n_ssids) request->ssids = (void *)&request->channels[n_channels]; request->n_ssids = n_ssids; if (ie_len) { if (request->ssids) request->ie = (void *)(request->ssids + n_ssids); else request->ie = (void *)(request->channels + n_channels); } i = 0; if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) { /* user specified, bail out if channel not found */ nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) { struct ieee80211_channel *chan; chan = ieee80211_get_channel(wiphy, nla_get_u32(attr)); if (!chan) { err = -EINVAL; goto out_free; } /* ignore disabled channels */ if (chan->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i] = chan; i++; } } else { /* all channels */ for (band = 0; band < IEEE80211_NUM_BANDS; band++) { int j; if (!wiphy->bands[band]) continue; for (j = 0; j < wiphy->bands[band]->n_channels; j++) { struct ieee80211_channel *chan; chan = &wiphy->bands[band]->channels[j]; if (chan->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i] = chan; i++; } } } if (!i) { err = -EINVAL; goto out_free; } request->n_channels = i; i = 0; if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) { nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) { request->ssids[i].ssid_len = nla_len(attr); if (request->ssids[i].ssid_len > IEEE80211_MAX_SSID_LEN) { err = -EINVAL; goto out_free; } memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr)); i++; } } if (info->attrs[NL80211_ATTR_IE]) { request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); memcpy((void *)request->ie, nla_data(info->attrs[NL80211_ATTR_IE]), request->ie_len); } request->dev = dev; request->wiphy = &rdev->wiphy; rdev->scan_req = request; err = rdev->ops->scan(&rdev->wiphy, dev, request); if (!err) { nl80211_send_scan_start(rdev, dev); dev_hold(dev); } else { out_free: rdev->scan_req = NULL; kfree(request); } return err; }
165,858
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: nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[gdev->gd_layout_type]; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; } 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
nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { ops = nfsd4_layout_ops[gdev->gd_layout_type]; nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; }
168,148
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: std::unique_ptr<service_manager::Service> CreateMediaService() { return std::unique_ptr<service_manager::Service>( new ::media::MediaService(base::MakeUnique<CdmMojoMediaClient>())); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
std::unique_ptr<service_manager::Service> CreateMediaService() { std::unique_ptr<service_manager::Service> CreateCdmService() { return std::unique_ptr<service_manager::Service>( new ::media::MediaService(base::MakeUnique<CdmMojoMediaClient>())); }
171,941
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: entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst) { tor_assert(guard); if (! rst) return 1; // No restriction? No problem. return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN); } Commit Message: Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377. CWE ID: CWE-200
entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst) { tor_assert(guard); if (! rst) return 1; // No restriction? No problem. // Only one kind of restriction exists right now: excluding an exit // ID and all of its family. const node_t *node = node_get_by_id((const char*)rst->exclude_id); if (node && guard_in_node_family(guard, node)) return 0; return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN); }
168,450
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: LoadWatcher(ScriptContext* context, content::RenderFrame* frame, v8::Local<v8::Function> cb) : content::RenderFrameObserver(frame), context_(context), callback_(context->isolate(), cb) { if (ExtensionFrameHelper::Get(frame)-> did_create_current_document_element()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&LoadWatcher::CallbackAndDie, base::Unretained(this), true)); } } Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated BUG=585268,568130 Review URL: https://codereview.chromium.org/1684953002 Cr-Commit-Position: refs/heads/master@{#374758} CWE ID:
LoadWatcher(ScriptContext* context, LoadWatcher(content::RenderFrame* frame, const base::Callback<void(bool)>& callback) : content::RenderFrameObserver(frame), callback_(callback) {} void DidCreateDocumentElement() override { // The callback must be run as soon as the root element is available. // Running the callback may trigger DidCreateDocumentElement or // DidFailProvisionalLoad, so delete this before running the callback. base::Callback<void(bool)> callback = callback_; delete this; callback.Run(true); }
172,145
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: Cues::Cues( Segment* pSegment, long long start_, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start_), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_cue_points(NULL), m_count(0), m_preload_count(0), m_pos(start_) { } 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
Cues::Cues( Cues::~Cues() { const long n = m_count + m_preload_count; CuePoint** p = m_cue_points; CuePoint** const q = p + n; while (p != q) { CuePoint* const pCP = *p++; assert(pCP); delete pCP; } delete[] m_cue_points; }
174,262