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: static __inline__ int scm_check_creds(struct ucred *creds)
{
const struct cred *cred = current_cred();
kuid_t uid = make_kuid(cred->user_ns, creds->uid);
kgid_t gid = make_kgid(cred->user_ns, creds->gid);
if (!uid_valid(uid) || !gid_valid(gid))
return -EINVAL;
if ((creds->pid == task_tgid_vnr(current) ||
ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) &&
((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||
uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&
((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||
gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) {
return 0;
}
return -EPERM;
}
Commit Message: net: Check the correct namespace when spoofing pid over SCM_RIGHTS
This is a security bug.
The follow-up will fix nsproxy to discourage this type of issue from
happening again.
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Reviewed-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static __inline__ int scm_check_creds(struct ucred *creds)
{
const struct cred *cred = current_cred();
kuid_t uid = make_kuid(cred->user_ns, creds->uid);
kgid_t gid = make_kgid(cred->user_ns, creds->gid);
if (!uid_valid(uid) || !gid_valid(gid))
return -EINVAL;
if ((creds->pid == task_tgid_vnr(current) ||
ns_capable(task_active_pid_ns(current)->user_ns, CAP_SYS_ADMIN)) &&
((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||
uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&
((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||
gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) {
return 0;
}
return -EPERM;
}
| 165,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 altivec_unavailable_exception(struct pt_regs *regs)
{
#if !defined(CONFIG_ALTIVEC)
if (user_mode(regs)) {
/* A user program has executed an altivec instruction,
but this kernel doesn't support altivec. */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return;
}
#endif
printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception "
"%lx at %lx\n", regs->trap, regs->nip);
die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT);
}
Commit Message: [POWERPC] Never panic when taking altivec exceptions from userspace
At the moment we rely on a cpu feature bit or a firmware property to
detect altivec. If we dont have either of these and the cpu does in fact
support altivec we can cause a panic from userspace.
It seems safer to always send a signal if we manage to get an 0xf20
exception from userspace.
Signed-off-by: Anton Blanchard <[email protected]>
Signed-off-by: Paul Mackerras <[email protected]>
CWE ID: CWE-19 | void altivec_unavailable_exception(struct pt_regs *regs)
{
if (user_mode(regs)) {
/* A user program has executed an altivec instruction,
but this kernel doesn't support altivec. */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return;
}
printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception "
"%lx at %lx\n", regs->trap, regs->nip);
die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT);
}
| 168,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
skb_dst_drop(skb);
}
Commit Message: ipv4: keep skb->dst around in presence of IP options
Andrey Konovalov got crashes in __ip_options_echo() when a NULL skb->dst
is accessed.
ipv4_pktinfo_prepare() should not drop the dst if (evil) IP options
are present.
We could refine the test to the presence of ts_needtime or srr,
but IP options are not often used, so let's be conservative.
Thanks to syzkaller team for finding this bug.
Fixes: d826eb14ecef ("ipv4: PKTINFO doesnt need dst reference")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
/* We need to keep the dst for __ip_options_echo()
* We could restrict the test to opt.ts_needtime || opt.srr,
* but the following is good enough as IP options are not often used.
*/
if (unlikely(IPCB(skb)->opt.optlen))
skb_dst_force(skb);
else
skb_dst_drop(skb);
}
| 168,370 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Register(const GURL& url,
const base::FilePath& root_http,
ReportResponseHeadersOnUI report_on_ui) {
EXPECT_TRUE(
content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
base::FilePath file_path(root_http);
file_path =
file_path.AppendASCII(url.scheme() + "." + url.host() + ".html");
net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
url, base::WrapUnique(
new MirrorMockJobInterceptor(file_path, report_on_ui)));
}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID: | static void Register(const GURL& url,
| 172,579 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) image->colormap[i].red;
*q++=(unsigned char) image->colormap[i].green;
*q++=(unsigned char) image->colormap[i].blue;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ((size_t) image->colormap[i].red >> 8);
*q++=(unsigned char) image->colormap[i].red;
*q++=(unsigned char) ((size_t) image->colormap[i].green >> 8);
*q++=(unsigned char) image->colormap[i].green;
*q++=(unsigned char) ((size_t) image->colormap[i].blue >> 8);
*q++=(unsigned char) image->colormap[i].blue;
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)
CWE ID: CWE-119 | static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| 168,632 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
goto vcpu_destroy;
mutex_lock(&kvm->lock);
if (!kvm_vcpu_compatible(vcpu)) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto unlock_vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto unlock_vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
mutex_unlock(&kvm->lock);
kvm_arch_vcpu_postcreate(vcpu);
return r;
unlock_vcpu_destroy:
mutex_unlock(&kvm->lock);
vcpu_destroy:
kvm_arch_vcpu_destroy(vcpu);
return r;
}
Commit Message: KVM: Improve create VCPU parameter (CVE-2013-4587)
In multiple functions the vcpu_id is used as an offset into a bitfield. Ag
malicious user could specify a vcpu_id greater than 255 in order to set or
clear bits in kernel memory. This could be used to elevate priveges in the
kernel. This patch verifies that the vcpu_id provided is less than 255.
The api documentation already specifies that the vcpu_id must be less than
max_vcpus, but this is currently not checked.
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
if (id >= KVM_MAX_VCPUS)
return -EINVAL;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
goto vcpu_destroy;
mutex_lock(&kvm->lock);
if (!kvm_vcpu_compatible(vcpu)) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto unlock_vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto unlock_vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
mutex_unlock(&kvm->lock);
kvm_arch_vcpu_postcreate(vcpu);
return r;
unlock_vcpu_destroy:
mutex_unlock(&kvm->lock);
vcpu_destroy:
kvm_arch_vcpu_destroy(vcpu);
return r;
}
| 165,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: void FrameImpl::GoForward() {
NOTIMPLEMENTED();
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | void FrameImpl::GoForward() {
if (web_contents_->GetController().CanGoForward())
web_contents_->GetController().GoForward();
}
| 172,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BackendImpl::OnEntryDestroyEnd() {
DecreaseNumRefs();
if (data_->header.num_bytes > max_size_ && !read_only_ &&
(up_ticks_ > kTrimDelay || user_flags_ & kNoRandom))
eviction_.TrimCache(false);
}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20 | void BackendImpl::OnEntryDestroyEnd() {
DecreaseNumRefs();
consider_evicting_at_op_end_ = true;
}
void BackendImpl::OnSyncBackendOpComplete() {
if (consider_evicting_at_op_end_) {
if (data_->header.num_bytes > max_size_ && !read_only_ &&
(up_ticks_ > kTrimDelay || user_flags_ & kNoRandom))
eviction_.TrimCache(false);
consider_evicting_at_op_end_ = false;
}
}
| 172,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: activate_desktop_file (ActivateParameters *parameters,
NautilusFile *file)
{
ActivateParametersDesktop *parameters_desktop;
char *primary, *secondary, *display_name;
GtkWidget *dialog;
GdkScreen *screen;
char *uri;
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
if (!nautilus_file_is_trusted_link (file))
{
/* copy the parts of parameters we are interested in as the orignal will be freed */
parameters_desktop = g_new0 (ActivateParametersDesktop, 1);
if (parameters->parent_window)
{
parameters_desktop->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
parameters_desktop->file = nautilus_file_ref (file);
primary = _("Untrusted application launcher");
display_name = nautilus_file_get_display_name (file);
secondary =
g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. "
"If you do not know the source of this file, launching it may be unsafe."
),
display_name);
dialog = gtk_message_dialog_new (parameters->parent_window,
0,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", primary,
"secondary-text", secondary,
NULL);
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Launch Anyway"), RESPONSE_RUN);
if (nautilus_file_can_set_permissions (file))
{
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("Mark as _Trusted"), RESPONSE_MARK_TRUSTED);
}
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);
g_signal_connect (dialog, "response",
G_CALLBACK (untrusted_launcher_response_callback),
parameters_desktop);
gtk_widget_show (dialog);
g_free (display_name);
g_free (secondary);
return;
}
uri = nautilus_file_get_uri (file);
DEBUG ("Launching trusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | activate_desktop_file (ActivateParameters *parameters,
NautilusFile *file)
{
ActivateParametersDesktop *parameters_desktop;
char *primary, *secondary, *display_name;
GtkWidget *dialog;
GdkScreen *screen;
char *uri;
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
if (!nautilus_file_is_trusted_link (file))
{
/* copy the parts of parameters we are interested in as the orignal will be freed */
parameters_desktop = g_new0 (ActivateParametersDesktop, 1);
if (parameters->parent_window)
{
parameters_desktop->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
parameters_desktop->file = nautilus_file_ref (file);
primary = _("Untrusted application launcher");
display_name = nautilus_file_get_display_name (file);
secondary =
g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. "
"If you do not know the source of this file, launching it may be unsafe."
),
display_name);
dialog = gtk_message_dialog_new (parameters->parent_window,
0,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", primary,
"secondary-text", secondary,
NULL);
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);
if (nautilus_file_can_set_permissions (file))
{
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("Trust and _Launch"), GTK_RESPONSE_OK);
}
g_signal_connect (dialog, "response",
G_CALLBACK (untrusted_launcher_response_callback),
parameters_desktop);
gtk_widget_show (dialog);
g_free (display_name);
g_free (secondary);
return;
}
uri = nautilus_file_get_uri (file);
DEBUG ("Launching trusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
| 167,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AutomationProvider::SendFindRequest(
TabContents* tab_contents,
bool with_json,
const string16& search_string,
bool forward,
bool match_case,
bool find_next,
IPC::Message* reply_message) {
int request_id = FindInPageNotificationObserver::kFindInPageRequestId;
FindInPageNotificationObserver* observer =
new FindInPageNotificationObserver(this,
tab_contents,
with_json,
reply_message);
if (!with_json) {
find_in_page_observer_.reset(observer);
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
if (wrapper)
wrapper->GetFindManager()->set_current_find_request_id(request_id);
tab_contents->render_view_host()->StartFinding(
FindInPageNotificationObserver::kFindInPageRequestId,
search_string,
forward,
match_case,
find_next);
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void AutomationProvider::SendFindRequest(
TabContents* tab_contents,
bool with_json,
const string16& search_string,
bool forward,
bool match_case,
bool find_next,
IPC::Message* reply_message) {
int request_id = FindInPageNotificationObserver::kFindInPageRequestId;
FindInPageNotificationObserver* observer =
new FindInPageNotificationObserver(this,
tab_contents,
with_json,
reply_message);
if (!with_json) {
find_in_page_observer_.reset(observer);
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
if (wrapper)
wrapper->find_tab_helper()->set_current_find_request_id(request_id);
tab_contents->render_view_host()->StartFinding(
FindInPageNotificationObserver::kFindInPageRequestId,
search_string,
forward,
match_case,
find_next);
}
| 170,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 enum AVPixelFormat h263_get_format(AVCodecContext *avctx)
{
/* MPEG-4 Studio Profile only, not supported by hardware */
if (avctx->bits_per_raw_sample > 8) {
av_assert1(avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);
return avctx->pix_fmt;
}
if (avctx->codec->id == AV_CODEC_ID_MSS2)
return AV_PIX_FMT_YUV420P;
if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {
if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)
avctx->color_range = AVCOL_RANGE_MPEG;
return AV_PIX_FMT_GRAY8;
}
return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);
}
Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile
The profile field is changed by code inside and outside the decoder,
its not a reliable indicator of the internal codec state.
Maintaining it consistency with studio_profile is messy.
Its easier to just avoid it and use only studio_profile
Fixes: assertion failure
Fixes: ffmpeg_crash_9.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-617 | static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)
{
MpegEncContext *s = avctx->priv_data;
/* MPEG-4 Studio Profile only, not supported by hardware */
if (avctx->bits_per_raw_sample > 8) {
av_assert1(s->studio_profile);
return avctx->pix_fmt;
}
if (avctx->codec->id == AV_CODEC_ID_MSS2)
return AV_PIX_FMT_YUV420P;
if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {
if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)
avctx->color_range = AVCOL_RANGE_MPEG;
return AV_PIX_FMT_GRAY8;
}
return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);
}
| 169,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 check_underflow(const struct ip6t_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ipv6))
return false;
t = ip6t_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | static bool check_underflow(const struct ip6t_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(e))
return false;
t = ip6t_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
| 167,373 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __u8 *nci_extract_rf_params_nfcf_passive_poll(struct nci_dev *ndev,
struct rf_tech_specific_params_nfcf_poll *nfcf_poll,
__u8 *data)
{
nfcf_poll->bit_rate = *data++;
nfcf_poll->sensf_res_len = *data++;
pr_debug("bit_rate %d, sensf_res_len %d\n",
nfcf_poll->bit_rate, nfcf_poll->sensf_res_len);
memcpy(nfcf_poll->sensf_res, data, nfcf_poll->sensf_res_len);
data += nfcf_poll->sensf_res_len;
return data;
}
Commit Message: NFC: Prevent multiple buffer overflows in NCI
Fix multiple remotely-exploitable stack-based buffer overflows due to
the NCI code pulling length fields directly from incoming frames and
copying too much data into statically-sized arrays.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: Lauro Ramos Venancio <[email protected]>
Cc: Aloisio Almeida Jr <[email protected]>
Cc: Samuel Ortiz <[email protected]>
Cc: David S. Miller <[email protected]>
Acked-by: Ilan Elias <[email protected]>
Signed-off-by: Samuel Ortiz <[email protected]>
CWE ID: CWE-119 | static __u8 *nci_extract_rf_params_nfcf_passive_poll(struct nci_dev *ndev,
struct rf_tech_specific_params_nfcf_poll *nfcf_poll,
__u8 *data)
{
nfcf_poll->bit_rate = *data++;
nfcf_poll->sensf_res_len = min_t(__u8, *data++, NFC_SENSF_RES_MAXSIZE);
pr_debug("bit_rate %d, sensf_res_len %d\n",
nfcf_poll->bit_rate, nfcf_poll->sensf_res_len);
memcpy(nfcf_poll->sensf_res, data, nfcf_poll->sensf_res_len);
data += nfcf_poll->sensf_res_len;
return data;
}
| 166,203 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl,
enum x86_transfer_type transfer,
struct desc_struct *desc)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* NULL selector is not valid for TR, CS and SS (except for long mode) */
if ((seg == VCPU_SREG_CS
|| (seg == VCPU_SREG_SS
&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))
|| seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s) {
if (transfer == X86_TRANSFER_CALL_JMP)
return X86EMUL_UNHANDLEABLE;
goto exception;
}
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
if (!(seg_desc.type & 1)) {
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector,
&seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
}
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (is_noncanonical_address(get_desc_base(&seg_desc) |
((u64)base3 << 32)))
return emulate_gp(ctxt, 0);
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
if (desc)
*desc = seg_desc;
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
Commit Message: KVM: x86: fix emulation of "MOV SS, null selector"
This is CVE-2017-2583. On Intel this causes a failed vmentry because
SS's type is neither 3 nor 7 (even though the manual says this check is
only done for usable SS, and the dmesg splat says that SS is unusable!).
On AMD it's worse: svm.c is confused and sets CPL to 0 in the vmcb.
The fix fabricates a data segment descriptor when SS is set to a null
selector, so that CPL and SS.DPL are set correctly in the VMCS/vmcb.
Furthermore, only allow setting SS to a NULL selector if SS.RPL < 3;
this in turn ensures CPL < 3 because RPL must be equal to CPL.
Thanks to Andy Lutomirski and Willy Tarreau for help in analyzing
the bug and deciphering the manuals.
Reported-by: Xiaohan Zhang <[email protected]>
Fixes: 79d5b4c3cd809c770d4bf9812635647016c56011
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: | static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl,
enum x86_transfer_type transfer,
struct desc_struct *desc)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
/* NULL selector is not valid for TR, CS and (except for long mode) SS */
if (null_selector) {
if (seg == VCPU_SREG_CS || seg == VCPU_SREG_TR)
goto exception;
if (seg == VCPU_SREG_SS) {
if (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl)
goto exception;
/*
* ctxt->ops->set_segment expects the CPL to be in
* SS.DPL, so fake an expand-up 32-bit data segment.
*/
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = cpl;
seg_desc.d = 1;
seg_desc.g = 1;
}
/* Skip all following checks */
goto load;
}
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s) {
if (transfer == X86_TRANSFER_CALL_JMP)
return X86EMUL_UNHANDLEABLE;
goto exception;
}
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
if (!(seg_desc.type & 1)) {
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector,
&seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
}
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (is_noncanonical_address(get_desc_base(&seg_desc) |
((u64)base3 << 32)))
return emulate_gp(ctxt, 0);
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
if (desc)
*desc = seg_desc;
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
| 168,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772 | static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned* lengths;
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if (!lengths)
free(tree->lengths);
tree->lengths = lengths;
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
| 169,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
*buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
Commit Message: 7zip: fix crash when parsing certain archives
Fuzzing with CRCs disabled revealed that a call to get_uncompressed_data()
would sometimes fail to return at least 'minimum' bytes. This can cause
the crc32() invocation in header_bytes to read off into invalid memory.
A specially crafted archive can use this to cause a crash.
An ASAN trace is below, but ASAN is not required - an uninstrumented
binary will also crash.
==7719==ERROR: AddressSanitizer: SEGV on unknown address 0x631000040000 (pc 0x7fbdb3b3ec1d bp 0x7ffe77a51310 sp 0x7ffe77a51150 T0)
==7719==The signal is caused by a READ memory access.
#0 0x7fbdb3b3ec1c in crc32_z (/lib/x86_64-linux-gnu/libz.so.1+0x2c1c)
#1 0x84f5eb in header_bytes (/tmp/libarchive/bsdtar+0x84f5eb)
#2 0x856156 in read_Header (/tmp/libarchive/bsdtar+0x856156)
#3 0x84e134 in slurp_central_directory (/tmp/libarchive/bsdtar+0x84e134)
#4 0x849690 in archive_read_format_7zip_read_header (/tmp/libarchive/bsdtar+0x849690)
#5 0x5713b7 in _archive_read_next_header2 (/tmp/libarchive/bsdtar+0x5713b7)
#6 0x570e63 in _archive_read_next_header (/tmp/libarchive/bsdtar+0x570e63)
#7 0x6f08bd in archive_read_next_header (/tmp/libarchive/bsdtar+0x6f08bd)
#8 0x52373f in read_archive (/tmp/libarchive/bsdtar+0x52373f)
#9 0x5257be in tar_mode_x (/tmp/libarchive/bsdtar+0x5257be)
#10 0x51daeb in main (/tmp/libarchive/bsdtar+0x51daeb)
#11 0x7fbdb27cab96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310
#12 0x41dd09 in _start (/tmp/libarchive/bsdtar+0x41dd09)
This was primarly done with afl and FairFuzz. Some early corpus entries
may have been generated by qsym.
CWE ID: CWE-125 | get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
*buff = __archive_read_ahead(a, minimum, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
| 169,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pim_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
#ifdef notyet /* currently we see only version and type */
ND_TCHECK(pim->pim_rsv);
#endif
switch (PIM_VER(pim->pim_typever)) {
case 2:
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, "PIMv%u, %s, length %u",
PIM_VER(pim->pim_typever),
tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)),
len));
return;
} else {
ND_PRINT((ndo, "PIMv%u, length %u\n\t%s",
PIM_VER(pim->pim_typever),
len,
tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever))));
pimv2_print(ndo, bp, len, bp2);
}
break;
default:
ND_PRINT((ndo, "PIMv%u, length %u",
PIM_VER(pim->pim_typever),
len));
break;
}
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
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), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | pim_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const struct pim *pim = (const struct pim *)bp;
#ifdef notyet /* currently we see only version and type */
ND_TCHECK(pim->pim_rsv);
#endif
ND_TCHECK(pim->pim_typever);
switch (PIM_VER(pim->pim_typever)) {
case 2:
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, "PIMv%u, %s, length %u",
PIM_VER(pim->pim_typever),
tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)),
len));
return;
} else {
ND_PRINT((ndo, "PIMv%u, length %u\n\t%s",
PIM_VER(pim->pim_typever),
len,
tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever))));
pimv2_print(ndo, bp, len, bp2);
}
break;
default:
ND_PRINT((ndo, "PIMv%u, length %u",
PIM_VER(pim->pim_typever),
len));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
| 167,854 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 parse_report(transport_smart *transport, git_push *push)
{
git_pkt *pkt = NULL;
const char *line_end = NULL;
gitno_buffer *buf = &transport->buffer;
int error, recvd;
git_buf data_pkt_buf = GIT_BUF_INIT;
for (;;) {
if (buf->offset > 0)
error = git_pkt_parse_line(&pkt, buf->data,
&line_end, buf->offset);
else
error = GIT_EBUFS;
if (error < 0 && error != GIT_EBUFS) {
error = -1;
goto done;
}
if (error == GIT_EBUFS) {
if ((recvd = gitno_recv(buf)) < 0) {
error = recvd;
goto done;
}
if (recvd == 0) {
giterr_set(GITERR_NET, "early EOF");
error = GIT_EEOF;
goto done;
}
continue;
}
gitno_consume(buf, line_end);
error = 0;
if (pkt == NULL)
continue;
switch (pkt->type) {
case GIT_PKT_DATA:
/* This is a sideband packet which contains other packets */
error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf);
break;
case GIT_PKT_ERR:
giterr_set(GITERR_NET, "report-status: Error reported: %s",
((git_pkt_err *)pkt)->error);
error = -1;
break;
case GIT_PKT_PROGRESS:
if (transport->progress_cb) {
git_pkt_progress *p = (git_pkt_progress *) pkt;
error = transport->progress_cb(p->data, p->len, transport->message_cb_payload);
}
break;
default:
error = add_push_report_pkt(push, pkt);
break;
}
git_pkt_free(pkt);
/* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */
if (error == GIT_ITEROVER) {
error = 0;
if (data_pkt_buf.size > 0) {
/* If there was data remaining in the pack data buffer,
* then the server sent a partial pkt-line */
giterr_set(GITERR_NET, "Incomplete pack data pkt-line");
error = GIT_ERROR;
}
goto done;
}
if (error < 0) {
goto done;
}
}
done:
git_buf_free(&data_pkt_buf);
return error;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476 | static int parse_report(transport_smart *transport, git_push *push)
{
git_pkt *pkt = NULL;
const char *line_end = NULL;
gitno_buffer *buf = &transport->buffer;
int error, recvd;
git_buf data_pkt_buf = GIT_BUF_INIT;
for (;;) {
if (buf->offset > 0)
error = git_pkt_parse_line(&pkt, buf->data,
&line_end, buf->offset);
else
error = GIT_EBUFS;
if (error < 0 && error != GIT_EBUFS) {
error = -1;
goto done;
}
if (error == GIT_EBUFS) {
if ((recvd = gitno_recv(buf)) < 0) {
error = recvd;
goto done;
}
if (recvd == 0) {
giterr_set(GITERR_NET, "early EOF");
error = GIT_EEOF;
goto done;
}
continue;
}
gitno_consume(buf, line_end);
error = 0;
switch (pkt->type) {
case GIT_PKT_DATA:
/* This is a sideband packet which contains other packets */
error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf);
break;
case GIT_PKT_ERR:
giterr_set(GITERR_NET, "report-status: Error reported: %s",
((git_pkt_err *)pkt)->error);
error = -1;
break;
case GIT_PKT_PROGRESS:
if (transport->progress_cb) {
git_pkt_progress *p = (git_pkt_progress *) pkt;
error = transport->progress_cb(p->data, p->len, transport->message_cb_payload);
}
break;
default:
error = add_push_report_pkt(push, pkt);
break;
}
git_pkt_free(pkt);
/* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */
if (error == GIT_ITEROVER) {
error = 0;
if (data_pkt_buf.size > 0) {
/* If there was data remaining in the pack data buffer,
* then the server sent a partial pkt-line */
giterr_set(GITERR_NET, "Incomplete pack data pkt-line");
error = GIT_ERROR;
}
goto done;
}
if (error < 0) {
goto done;
}
}
done:
git_buf_free(&data_pkt_buf);
return error;
}
| 168,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787 | reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
| 166,875 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileStream::FileStream(base::File file,
const scoped_refptr<base::TaskRunner>& task_runner)
: context_(base::MakeUnique<Context>(std::move(file), task_runner)) {}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | FileStream::FileStream(base::File file,
const scoped_refptr<base::TaskRunner>& task_runner)
| 173,263 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI PHP_FUNCTION(fread)
{
zval *arg1;
long len;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) {
RETURN_FALSE;
}
PHP_STREAM_TO_ZVAL(stream, &arg1);
if (len <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(len + 1);
Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
Commit Message: Fix bug #72114 - int/size_t confusion in fread
CWE ID: CWE-190 | PHPAPI PHP_FUNCTION(fread)
{
zval *arg1;
long len;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) {
RETURN_FALSE;
}
PHP_STREAM_TO_ZVAL(stream, &arg1);
if (len <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (len > INT_MAX) {
/* string length is int in 5.x so we can not read more than int */
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(len + 1);
Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
| 167,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebPluginDelegateProxy::SendUpdateGeometry(
bool bitmaps_changed) {
PluginMsg_UpdateGeometry_Param param;
param.window_rect = plugin_rect_;
param.clip_rect = clip_rect_;
param.windowless_buffer0 = TransportDIB::DefaultHandleValue();
param.windowless_buffer1 = TransportDIB::DefaultHandleValue();
param.windowless_buffer_index = back_buffer_index();
param.background_buffer = TransportDIB::DefaultHandleValue();
param.transparent = transparent_;
#if defined(OS_POSIX)
if (bitmaps_changed)
#endif
{
if (transport_stores_[0].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(),
¶m.windowless_buffer0);
if (transport_stores_[1].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(),
¶m.windowless_buffer1);
if (background_store_.dib.get())
CopyTransportDIBHandleForMessage(background_store_.dib->handle(),
¶m.background_buffer);
}
IPC::Message* msg;
#if defined(OS_WIN)
if (UseSynchronousGeometryUpdates()) {
msg = new PluginMsg_UpdateGeometrySync(instance_id_, param);
} else // NOLINT
#endif
{
msg = new PluginMsg_UpdateGeometry(instance_id_, param);
msg->set_unblock(true);
}
Send(msg);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void WebPluginDelegateProxy::SendUpdateGeometry(
bool bitmaps_changed) {
PluginMsg_UpdateGeometry_Param param;
param.window_rect = plugin_rect_;
param.clip_rect = clip_rect_;
param.windowless_buffer0 = TransportDIB::DefaultHandleValue();
param.windowless_buffer1 = TransportDIB::DefaultHandleValue();
param.windowless_buffer_index = back_buffer_index();
param.background_buffer = TransportDIB::DefaultHandleValue();
param.transparent = transparent_;
#if defined(OS_POSIX)
if (bitmaps_changed)
#endif
{
if (transport_stores_[0].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(),
¶m.windowless_buffer0,
channel_host_->peer_pid());
if (transport_stores_[1].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(),
¶m.windowless_buffer1,
channel_host_->peer_pid());
if (background_store_.dib.get())
CopyTransportDIBHandleForMessage(background_store_.dib->handle(),
¶m.background_buffer,
channel_host_->peer_pid());
}
IPC::Message* msg;
#if defined(OS_WIN)
if (UseSynchronousGeometryUpdates()) {
msg = new PluginMsg_UpdateGeometrySync(instance_id_, param);
} else // NOLINT
#endif
{
msg = new PluginMsg_UpdateGeometry(instance_id_, param);
msg->set_unblock(true);
}
Send(msg);
}
| 170,956 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
Commit Message: KVM: x86: Don't report guest userspace emulation error to userspace
Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to
user-space") disabled the reporting of L2 (nested guest) emulation failures to
userspace due to race-condition between a vmexit and the instruction emulator.
The same rational applies also to userspace applications that are permitted by
the guest OS to access MMIO area or perform PIO.
This patch extends the current behavior - of injecting a #UD instead of
reporting it to userspace - also for guest userspace code.
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-362 | static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
| 166,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UDPSocketLibevent::InternalConnect(const IPEndPoint& address) {
DCHECK(CalledOnValidThread());
DCHECK(!is_connected());
DCHECK(!remote_address_.get());
int addr_family = address.GetSockAddrFamily();
int rv = CreateSocket(addr_family);
if (rv < 0)
return rv;
if (bind_type_ == DatagramSocket::RANDOM_BIND) {
size_t addr_size =
addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize;
IPAddressNumber addr_any(addr_size);
rv = RandomBind(addr_any);
}
if (rv < 0) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv);
Close();
return rv;
}
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len)) {
Close();
return ERR_ADDRESS_INVALID;
}
rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len));
if (rv < 0) {
int result = MapSystemError(errno);
Close();
return result;
}
remote_address_.reset(new IPEndPoint(address));
return rv;
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) {
DCHECK(CalledOnValidThread());
DCHECK(!is_connected());
DCHECK(!remote_address_.get());
int addr_family = address.GetSockAddrFamily();
int rv = CreateSocket(addr_family);
if (rv < 0)
return rv;
if (bind_type_ == DatagramSocket::RANDOM_BIND) {
size_t addr_size =
addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize;
IPAddressNumber addr_any(addr_size);
rv = RandomBind(addr_any);
}
if (rv < 0) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv);
Close();
return rv;
}
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len)) {
Close();
return ERR_ADDRESS_INVALID;
}
rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len));
if (rv < 0) {
int result = MapSystemError(errno);
Close();
return result;
}
remote_address_.reset(new IPEndPoint(address));
return rv;
}
| 171,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::getConfig(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::getConfig(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
| 174,134 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 send_reply(struct svcxprt_rdma *rdma,
struct svc_rqst *rqstp,
struct page *page,
struct rpcrdma_msg *rdma_resp,
struct svc_rdma_req_map *vec,
int byte_count,
u32 inv_rkey)
{
struct svc_rdma_op_ctxt *ctxt;
struct ib_send_wr send_wr;
u32 xdr_off;
int sge_no;
int sge_bytes;
int page_no;
int pages;
int ret = -EIO;
/* Prepare the context */
ctxt = svc_rdma_get_context(rdma);
ctxt->direction = DMA_TO_DEVICE;
ctxt->pages[0] = page;
ctxt->count = 1;
/* Prepare the SGE for the RPCRDMA Header */
ctxt->sge[0].lkey = rdma->sc_pd->local_dma_lkey;
ctxt->sge[0].length =
svc_rdma_xdr_get_reply_hdr_len((__be32 *)rdma_resp);
ctxt->sge[0].addr =
ib_dma_map_page(rdma->sc_cm_id->device, page, 0,
ctxt->sge[0].length, DMA_TO_DEVICE);
if (ib_dma_mapping_error(rdma->sc_cm_id->device, ctxt->sge[0].addr))
goto err;
svc_rdma_count_mappings(rdma, ctxt);
ctxt->direction = DMA_TO_DEVICE;
/* Map the payload indicated by 'byte_count' */
xdr_off = 0;
for (sge_no = 1; byte_count && sge_no < vec->count; sge_no++) {
sge_bytes = min_t(size_t, vec->sge[sge_no].iov_len, byte_count);
byte_count -= sge_bytes;
ctxt->sge[sge_no].addr =
dma_map_xdr(rdma, &rqstp->rq_res, xdr_off,
sge_bytes, DMA_TO_DEVICE);
xdr_off += sge_bytes;
if (ib_dma_mapping_error(rdma->sc_cm_id->device,
ctxt->sge[sge_no].addr))
goto err;
svc_rdma_count_mappings(rdma, ctxt);
ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey;
ctxt->sge[sge_no].length = sge_bytes;
}
if (byte_count != 0) {
pr_err("svcrdma: Could not map %d bytes\n", byte_count);
goto err;
}
/* Save all respages in the ctxt and remove them from the
* respages array. They are our pages until the I/O
* completes.
*/
pages = rqstp->rq_next_page - rqstp->rq_respages;
for (page_no = 0; page_no < pages; page_no++) {
ctxt->pages[page_no+1] = rqstp->rq_respages[page_no];
ctxt->count++;
rqstp->rq_respages[page_no] = NULL;
}
rqstp->rq_next_page = rqstp->rq_respages + 1;
if (sge_no > rdma->sc_max_sge) {
pr_err("svcrdma: Too many sges (%d)\n", sge_no);
goto err;
}
memset(&send_wr, 0, sizeof send_wr);
ctxt->cqe.done = svc_rdma_wc_send;
send_wr.wr_cqe = &ctxt->cqe;
send_wr.sg_list = ctxt->sge;
send_wr.num_sge = sge_no;
if (inv_rkey) {
send_wr.opcode = IB_WR_SEND_WITH_INV;
send_wr.ex.invalidate_rkey = inv_rkey;
} else
send_wr.opcode = IB_WR_SEND;
send_wr.send_flags = IB_SEND_SIGNALED;
ret = svc_rdma_send(rdma, &send_wr);
if (ret)
goto err;
return 0;
err:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
return ret;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static int send_reply(struct svcxprt_rdma *rdma,
static int svc_rdma_send_reply_msg(struct svcxprt_rdma *rdma,
__be32 *rdma_argp, __be32 *rdma_resp,
struct svc_rqst *rqstp,
__be32 *wr_lst, __be32 *rp_ch)
{
struct svc_rdma_op_ctxt *ctxt;
u32 inv_rkey;
int ret;
dprintk("svcrdma: sending %s reply: head=%zu, pagelen=%u, tail=%zu\n",
(rp_ch ? "RDMA_NOMSG" : "RDMA_MSG"),
rqstp->rq_res.head[0].iov_len,
rqstp->rq_res.page_len,
rqstp->rq_res.tail[0].iov_len);
ctxt = svc_rdma_get_context(rdma);
ret = svc_rdma_map_reply_hdr(rdma, ctxt, rdma_resp,
svc_rdma_reply_hdr_len(rdma_resp));
if (ret < 0)
goto err;
if (!rp_ch) {
ret = svc_rdma_map_reply_msg(rdma, ctxt,
&rqstp->rq_res, wr_lst);
if (ret < 0)
goto err;
}
svc_rdma_save_io_pages(rqstp, ctxt);
inv_rkey = 0;
if (rdma->sc_snd_w_inv)
inv_rkey = svc_rdma_get_inv_rkey(rdma_argp, wr_lst, rp_ch);
ret = svc_rdma_post_send_wr(rdma, ctxt, 1 + ret, inv_rkey);
if (ret)
goto err;
return 0;
err:
pr_err("svcrdma: failed to post Send WR (%d)\n", ret);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
return ret;
}
/* Given the client-provided Write and Reply chunks, the server was not
* able to form a complete reply. Return an RDMA_ERROR message so the
* client can retire this RPC transaction. As above, the Send completion
* routine releases payload pages that were part of a previous RDMA Write.
*
* Remote Invalidation is skipped for simplicity.
*/
static int svc_rdma_send_error_msg(struct svcxprt_rdma *rdma,
__be32 *rdma_resp, struct svc_rqst *rqstp)
{
struct svc_rdma_op_ctxt *ctxt;
__be32 *p;
int ret;
ctxt = svc_rdma_get_context(rdma);
/* Replace the original transport header with an
* RDMA_ERROR response. XID etc are preserved.
*/
p = rdma_resp + 3;
*p++ = rdma_error;
*p = err_chunk;
ret = svc_rdma_map_reply_hdr(rdma, ctxt, rdma_resp, 20);
if (ret < 0)
goto err;
svc_rdma_save_io_pages(rqstp, ctxt);
ret = svc_rdma_post_send_wr(rdma, ctxt, 1 + ret, 0);
if (ret)
goto err;
return 0;
err:
pr_err("svcrdma: failed to post Send WR (%d)\n", ret);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
return ret;
}
| 168,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area,
char *base_uri, xps_resource *dict,
char *opacity_att, fz_xml *opacity_mask_tag)
{
float opacity;
if (!opacity_att && !opacity_mask_tag)
return;
opacity = 1;
if (opacity_att)
opacity = fz_atof(opacity_att);
if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush"))
{
char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity");
char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color");
if (scb_opacity_att)
opacity = opacity * fz_atof(scb_opacity_att);
if (scb_color_att)
{
fz_colorspace *colorspace;
float samples[32];
xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples);
opacity = opacity * samples[0];
}
opacity_mask_tag = NULL;
}
if (doc->opacity_top + 1 < nelem(doc->opacity))
{
doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity;
doc->opacity_top++;
}
if (opacity_mask_tag)
{
fz_begin_mask(doc->dev, area, 0, NULL, NULL);
xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag);
fz_end_mask(doc->dev);
}
}
Commit Message:
CWE ID: CWE-119 | xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area,
char *base_uri, xps_resource *dict,
char *opacity_att, fz_xml *opacity_mask_tag)
{
float opacity;
if (!opacity_att && !opacity_mask_tag)
return;
opacity = 1;
if (opacity_att)
opacity = fz_atof(opacity_att);
if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush"))
{
char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity");
char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color");
if (scb_opacity_att)
opacity = opacity * fz_atof(scb_opacity_att);
if (scb_color_att)
{
fz_colorspace *colorspace;
float samples[FZ_MAX_COLORS];
xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples);
opacity = opacity * samples[0];
}
opacity_mask_tag = NULL;
}
if (doc->opacity_top + 1 < nelem(doc->opacity))
{
doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity;
doc->opacity_top++;
}
if (opacity_mask_tag)
{
fz_begin_mask(doc->dev, area, 0, NULL, NULL);
xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag);
fz_end_mask(doc->dev);
}
}
| 165,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode image_clamping_mode,
ImageDecodingMode decode_mode) {
auto paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return;
auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode);
if (paint_image.decoding_mode() != paint_image_decoding_mode) {
paint_image = PaintImageBuilder::WithCopy(std::move(paint_image))
.set_decoding_mode(paint_image_decoding_mode)
.TakePaintImage();
}
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect,
image_clamping_mode, paint_image);
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode image_clamping_mode,
ImageDecodingMode decode_mode) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return;
auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode);
if (paint_image.decoding_mode() != paint_image_decoding_mode) {
paint_image = PaintImageBuilder::WithCopy(std::move(paint_image))
.set_decoding_mode(paint_image_decoding_mode)
.TakePaintImage();
}
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect,
image_clamping_mode, paint_image);
}
| 172,594 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DiscardTest(DiscardReason reason) {
const base::TimeTicks kDummyLastActiveTime =
base::TimeTicks() + kShortDelay;
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
content::WebContentsTester::For(initial_web_contents)
->SetLastActiveTime(kDummyLastActiveTime);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
background_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_EQ(kDummyLastActiveTime,
tab_strip_model_->GetWebContentsAt(0)->GetLastActiveTime());
source_->SetFocusedTabStripModelForTesting(nullptr);
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | void DiscardTest(DiscardReason reason) {
const base::TimeTicks kDummyLastActiveTime =
base::TimeTicks() + kShortDelay;
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
content::WebContentsTester::For(initial_web_contents)
->SetLastActiveTime(kDummyLastActiveTime);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true));
background_lifecycle_unit->Discard(reason);
::testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_EQ(kDummyLastActiveTime,
tab_strip_model_->GetWebContentsAt(0)->GetLastActiveTime());
source_->SetFocusedTabStripModelForTesting(nullptr);
}
| 172,226 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void build_l4proto_tcp(const struct nf_conntrack *ct, struct nethdr *n)
{
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
if (!nfct_attr_is_set(ct, ATTR_TCP_STATE))
return;
ct_build_u8(ct, ATTR_TCP_STATE, n, NTA_TCP_STATE);
if (CONFIG(sync).tcp_window_tracking) {
ct_build_u8(ct, ATTR_TCP_WSCALE_ORIG, n, NTA_TCP_WSCALE_ORIG);
ct_build_u8(ct, ATTR_TCP_WSCALE_REPL, n, NTA_TCP_WSCALE_REPL);
}
}
Commit Message:
CWE ID: CWE-17 | static void build_l4proto_tcp(const struct nf_conntrack *ct, struct nethdr *n)
{
if (!nfct_attr_is_set(ct, ATTR_TCP_STATE))
return;
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
ct_build_u8(ct, ATTR_TCP_STATE, n, NTA_TCP_STATE);
if (CONFIG(sync).tcp_window_tracking) {
ct_build_u8(ct, ATTR_TCP_WSCALE_ORIG, n, NTA_TCP_WSCALE_ORIG);
ct_build_u8(ct, ATTR_TCP_WSCALE_REPL, n, NTA_TCP_WSCALE_REPL);
}
}
| 164,632 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TileIndependenceTest()
: EncoderTest(GET_PARAM(0)),
md5_fw_order_(),
md5_inv_order_(),
n_tiles_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg;
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
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 | TileIndependenceTest()
: EncoderTest(GET_PARAM(0)),
md5_fw_order_(),
md5_inv_order_(),
n_tiles_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
| 174,584 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,
struct iw_exif_state *e, iw_uint32 ifd)
{
unsigned int tag_count;
unsigned int i;
unsigned int tag_pos;
unsigned int tag_id;
unsigned int v;
double v_dbl;
if(ifd<8 || ifd>e->d_len-18) return;
tag_count = iw_get_ui16_e(&e->d[ifd],e->endian);
if(tag_count>1000) return; // Sanity check.
for(i=0;i<tag_count;i++) {
tag_pos = ifd+2+i*12;
if(tag_pos+12 > e->d_len) return; // Avoid overruns.
tag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian);
switch(tag_id) {
case 274: // 274 = Orientation
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_orientation = v;
}
break;
case 296: // 296 = ResolutionUnit
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_density_unit = v;
}
break;
case 282: // 282 = XResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_x = v_dbl;
}
break;
case 283: // 283 = YResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_y = v_dbl;
}
break;
}
}
}
Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data
Fixes issues #22, #23, #24, #25
CWE ID: CWE-125 | static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,
struct iw_exif_state *e, iw_uint32 ifd)
{
unsigned int tag_count;
unsigned int i;
unsigned int tag_pos;
unsigned int tag_id;
unsigned int v;
double v_dbl;
if(ifd<8 || e->d_len<18 || ifd>e->d_len-18) return;
tag_count = get_exif_ui16(e, ifd);
if(tag_count>1000) return; // Sanity check.
for(i=0;i<tag_count;i++) {
tag_pos = ifd+2+i*12;
if(tag_pos+12 > e->d_len) return; // Avoid overruns.
tag_id = get_exif_ui16(e, tag_pos);
switch(tag_id) {
case 274: // 274 = Orientation
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_orientation = v;
}
break;
case 296: // 296 = ResolutionUnit
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_density_unit = v;
}
break;
case 282: // 282 = XResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_x = v_dbl;
}
break;
case 283: // 283 = YResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_y = v_dbl;
}
break;
}
}
}
| 168,116 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
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(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(long) image->resolution.x);
length=WriteLSBLong(file,1);
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
(void) fputc(c,file);
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent);
}
(void) RelinquishUniqueFileResource(filename);
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/196
CWE ID: CWE-20 | static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
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(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(long) image->resolution.x);
length=WriteLSBLong(file,1);
status=MagickTrue;
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
if (fputc(c,file) != c)
status=MagickFalse;
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent);
}
(void) RelinquishUniqueFileResource(filename);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
| 168,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ptaReadStream(FILE *fp)
{
char typestr[128];
l_int32 i, n, ix, iy, type, version;
l_float32 x, y;
PTA *pta;
PROCNAME("ptaReadStream");
if (!fp)
return (PTA *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, "\n Pta Version %d\n", &version) != 1)
return (PTA *)ERROR_PTR("not a pta file", procName, NULL);
if (version != PTA_VERSION_NUMBER)
return (PTA *)ERROR_PTR("invalid pta version", procName, NULL);
if (fscanf(fp, " Number of pts = %d; format = %s\n", &n, typestr) != 2)
return (PTA *)ERROR_PTR("not a pta file", procName, NULL);
if (!strcmp(typestr, "float"))
type = 0;
else /* typestr is "integer" */
type = 1;
if ((pta = ptaCreate(n)) == NULL)
return (PTA *)ERROR_PTR("pta not made", procName, NULL);
for (i = 0; i < n; i++) {
if (type == 0) { /* data is float */
if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) {
ptaDestroy(&pta);
return (PTA *)ERROR_PTR("error reading floats", procName, NULL);
}
ptaAddPt(pta, x, y);
} else { /* data is integer */
if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) {
ptaDestroy(&pta);
return (PTA *)ERROR_PTR("error reading ints", procName, NULL);
}
ptaAddPt(pta, ix, iy);
}
}
return pta;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119 | ptaReadStream(FILE *fp)
{
char typestr[128]; /* hardcoded below in fscanf */
l_int32 i, n, ix, iy, type, version;
l_float32 x, y;
PTA *pta;
PROCNAME("ptaReadStream");
if (!fp)
return (PTA *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, "\n Pta Version %d\n", &version) != 1)
return (PTA *)ERROR_PTR("not a pta file", procName, NULL);
if (version != PTA_VERSION_NUMBER)
return (PTA *)ERROR_PTR("invalid pta version", procName, NULL);
if (fscanf(fp, " Number of pts = %d; format = %127s\n", &n, typestr) != 2)
return (PTA *)ERROR_PTR("not a pta file", procName, NULL);
if (!strcmp(typestr, "float"))
type = 0;
else /* typestr is "integer" */
type = 1;
if ((pta = ptaCreate(n)) == NULL)
return (PTA *)ERROR_PTR("pta not made", procName, NULL);
for (i = 0; i < n; i++) {
if (type == 0) { /* data is float */
if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) {
ptaDestroy(&pta);
return (PTA *)ERROR_PTR("error reading floats", procName, NULL);
}
ptaAddPt(pta, x, y);
} else { /* data is integer */
if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) {
ptaDestroy(&pta);
return (PTA *)ERROR_PTR("error reading ints", procName, NULL);
}
ptaAddPt(pta, ix, iy);
}
}
return pta;
}
| 169,328 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame,
const GURL& url,
GURL* new_url) {
if (url.SchemeIs(chrome::kExtensionScheme) &&
!ExtensionResourceRequestPolicy::CanRequestResource(
url,
GURL(frame->document().url()),
extension_dispatcher_->extensions())) {
*new_url = GURL("chrome-extension://invalid/");
return true;
}
return false;
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame,
const GURL& url,
GURL* new_url) {
if (url.SchemeIs(chrome::kExtensionScheme) &&
!ExtensionResourceRequestPolicy::CanRequestResource(
url,
frame,
extension_dispatcher_->extensions())) {
*new_url = GURL("chrome-extension://invalid/");
return true;
}
return false;
}
| 171,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: videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
int i;
dprintk(2,"vm_close %p [count=%d,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count--;
if (0 == map->count) {
dprintk(1,"munmap %p q=%p\n",map,q);
mutex_lock(&q->lock);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map != map)
continue;
q->ops->buf_release(q,q->bufs[i]);
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
}
mutex_unlock(&q->lock);
kfree(map);
}
return;
}
Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap
This is pretty serious bug. map->count is never initialized after the
call to kmalloc making the count start at some random trash value. The
end result is leaking videobufs.
Also, fix up the debug statements to print unsigned values.
Pushed to http://ifup.org/hg/v4l-dvb too
Signed-off-by: Brandon Philips <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
int i;
dprintk(2,"vm_close %p [count=%u,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count--;
if (0 == map->count) {
dprintk(1,"munmap %p q=%p\n",map,q);
mutex_lock(&q->lock);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map != map)
continue;
q->ops->buf_release(q,q->bufs[i]);
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
}
mutex_unlock(&q->lock);
kfree(map);
}
return;
}
| 168,918 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AviaryScheddPlugin::processJob(const char *key,
const char *,
int )
{
PROC_ID id;
ClassAd *jobAd;
if (!IS_JOB(key)) return false;
id = getProcByString(key);
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key);
return false;
}
if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) {
dprintf(D_ALWAYS,
"NOTICE: Failed to lookup ad for %s - maybe deleted\n",
key);
return false;
}
MyString submissionName;
if (GetAttributeString(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
PROC_ID dagman;
if (GetAttributeInt(id.cluster, id.proc,
ATTR_DAGMAN_JOB_ID,
&dagman.cluster) >= 0) {
dagman.proc = 0;
if (GetAttributeString(dagman.cluster, dagman.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
submissionName.sprintf("%s#%d", Name, dagman.cluster);
}
} else {
submissionName.sprintf("%s#%d", Name, id.cluster);
}
MyString tmp;
tmp += "\"";
tmp += submissionName;
tmp += "\"";
SetAttribute(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
tmp.Value());
}
return true;
}
Commit Message:
CWE ID: CWE-20 | AviaryScheddPlugin::processJob(const char *key,
const char *,
int )
{
PROC_ID id;
ClassAd *jobAd;
if (!IS_JOB(key)) return false;
id = getProcByString(key);
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key);
return false;
}
if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) {
dprintf(D_ALWAYS,
"NOTICE: Failed to lookup ad for %s - maybe deleted\n",
key);
return false;
}
MyString submissionName;
if (GetAttributeString(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
PROC_ID dagman;
if (GetAttributeInt(id.cluster, id.proc,
ATTR_DAGMAN_JOB_ID,
&dagman.cluster) >= 0) {
dagman.proc = 0;
if (GetAttributeString(dagman.cluster, dagman.proc,
ATTR_JOB_SUBMISSION,
submissionName) < 0) {
submissionName.sprintf("%s#%d", Name, dagman.cluster);
}
} else {
submissionName.sprintf("%s#%d", Name, id.cluster);
}
MyString tmp;
tmp += "\"";
tmp += submissionName;
tmp += "\"";
SetAttribute(id.cluster, id.proc,
ATTR_JOB_SUBMISSION,
tmp.Value());
}
return true;
}
| 164,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: static void *__alloc_from_pool(size_t size, struct page **ret_page, gfp_t flags)
{
unsigned long val;
void *ptr = NULL;
if (!atomic_pool) {
WARN(1, "coherent pool not initialised!\n");
return NULL;
}
val = gen_pool_alloc(atomic_pool, size);
if (val) {
phys_addr_t phys = gen_pool_virt_to_phys(atomic_pool, val);
*ret_page = phys_to_page(phys);
ptr = (void *)val;
if (flags & __GFP_ZERO)
memset(ptr, 0, size);
}
return ptr;
}
Commit Message: arm64: dma-mapping: always clear allocated buffers
Buffers allocated by dma_alloc_coherent() are always zeroed on Alpha,
ARM (32bit), MIPS, PowerPC, x86/x86_64 and probably other architectures.
It turned out that some drivers rely on this 'feature'. Allocated buffer
might be also exposed to userspace with dma_mmap() call, so clearing it
is desired from security point of view to avoid exposing random memory
to userspace. This patch unifies dma_alloc_coherent() behavior on ARM64
architecture with other implementations by unconditionally zeroing
allocated buffer.
Cc: <[email protected]> # v3.14+
Signed-off-by: Marek Szyprowski <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
CWE ID: CWE-200 | static void *__alloc_from_pool(size_t size, struct page **ret_page, gfp_t flags)
{
unsigned long val;
void *ptr = NULL;
if (!atomic_pool) {
WARN(1, "coherent pool not initialised!\n");
return NULL;
}
val = gen_pool_alloc(atomic_pool, size);
if (val) {
phys_addr_t phys = gen_pool_virt_to_phys(atomic_pool, val);
*ret_page = phys_to_page(phys);
ptr = (void *)val;
memset(ptr, 0, size);
}
return ptr;
}
| 167,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderWidgetHostViewAura::WasHidden() {
if (host_->is_hidden())
return;
host_->WasHidden();
released_front_lock_ = NULL;
if (ShouldReleaseFrontSurface() &&
host_->is_accelerated_compositing_active()) {
current_surface_ = 0;
UpdateExternalTexture();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
aura::RootWindow* root_window = window_->GetRootWindow();
if (root_window) {
HWND parent = root_window->GetAcceleratedWidget();
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(parent, HideWindowsCallback, lparam);
}
#endif
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostViewAura::WasHidden() {
if (host_->is_hidden())
return;
host_->WasHidden();
released_front_lock_ = NULL;
#if defined(OS_WIN)
aura::RootWindow* root_window = window_->GetRootWindow();
if (root_window) {
HWND parent = root_window->GetAcceleratedWidget();
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(parent, HideWindowsCallback, lparam);
}
#endif
}
| 171,388 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx)
{
const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8;
if (avctx->lowres==1) {
c->idct_put = ff_jref_idct4_put;
c->idct_add = ff_jref_idct4_add;
c->idct = ff_j_rev_dct4;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==2) {
c->idct_put = ff_jref_idct2_put;
c->idct_add = ff_jref_idct2_add;
c->idct = ff_j_rev_dct2;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==3) {
c->idct_put = ff_jref_idct1_put;
c->idct_add = ff_jref_idct1_add;
c->idct = ff_j_rev_dct1;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) {
/* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT
However, it only uses idct_put */
if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO)
c->idct_put = ff_simple_idct_put_int32_10bit;
else {
c->idct_put = ff_simple_idct_put_int16_10bit;
c->idct_add = ff_simple_idct_add_int16_10bit;
c->idct = ff_simple_idct_int16_10bit;
}
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->bits_per_raw_sample == 12) {
c->idct_put = ff_simple_idct_put_int16_12bit;
c->idct_add = ff_simple_idct_add_int16_12bit;
c->idct = ff_simple_idct_int16_12bit;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->idct_algo == FF_IDCT_INT) {
c->idct_put = ff_jref_idct_put;
c->idct_add = ff_jref_idct_add;
c->idct = ff_j_rev_dct;
c->perm_type = FF_IDCT_PERM_LIBMPEG2;
#if CONFIG_FAANIDCT
} else if (avctx->idct_algo == FF_IDCT_FAAN) {
c->idct_put = ff_faanidct_put;
c->idct_add = ff_faanidct_add;
c->idct = ff_faanidct;
c->perm_type = FF_IDCT_PERM_NONE;
#endif /* CONFIG_FAANIDCT */
} else { // accurate/default
/* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */
c->idct_put = ff_simple_idct_put_int16_8bit;
c->idct_add = ff_simple_idct_add_int16_8bit;
c->idct = ff_simple_idct_int16_8bit;
c->perm_type = FF_IDCT_PERM_NONE;
}
}
}
c->put_pixels_clamped = ff_put_pixels_clamped_c;
c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
c->add_pixels_clamped = ff_add_pixels_clamped_c;
if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID)
ff_xvid_idct_init(c, avctx);
if (ARCH_AARCH64)
ff_idctdsp_init_aarch64(c, avctx, high_bit_depth);
if (ARCH_ALPHA)
ff_idctdsp_init_alpha(c, avctx, high_bit_depth);
if (ARCH_ARM)
ff_idctdsp_init_arm(c, avctx, high_bit_depth);
if (ARCH_PPC)
ff_idctdsp_init_ppc(c, avctx, high_bit_depth);
if (ARCH_X86)
ff_idctdsp_init_x86(c, avctx, high_bit_depth);
if (ARCH_MIPS)
ff_idctdsp_init_mips(c, avctx, high_bit_depth);
ff_init_scantable_permutation(c->idct_permutation,
c->perm_type);
}
Commit Message: avcodec/idctdsp: Transmit studio_profile to init instead of using AVCodecContext profile
These 2 fields are not always the same, it is simpler to always use the same field
for detecting studio profile
Fixes: null pointer dereference
Fixes: ffmpeg_crash_3.avi
Found-by: Thuan Pham <[email protected]>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx)
{
const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8;
if (avctx->lowres==1) {
c->idct_put = ff_jref_idct4_put;
c->idct_add = ff_jref_idct4_add;
c->idct = ff_j_rev_dct4;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==2) {
c->idct_put = ff_jref_idct2_put;
c->idct_add = ff_jref_idct2_add;
c->idct = ff_j_rev_dct2;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==3) {
c->idct_put = ff_jref_idct1_put;
c->idct_add = ff_jref_idct1_add;
c->idct = ff_j_rev_dct1;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) {
/* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT
However, it only uses idct_put */
if (c->mpeg4_studio_profile)
c->idct_put = ff_simple_idct_put_int32_10bit;
else {
c->idct_put = ff_simple_idct_put_int16_10bit;
c->idct_add = ff_simple_idct_add_int16_10bit;
c->idct = ff_simple_idct_int16_10bit;
}
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->bits_per_raw_sample == 12) {
c->idct_put = ff_simple_idct_put_int16_12bit;
c->idct_add = ff_simple_idct_add_int16_12bit;
c->idct = ff_simple_idct_int16_12bit;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->idct_algo == FF_IDCT_INT) {
c->idct_put = ff_jref_idct_put;
c->idct_add = ff_jref_idct_add;
c->idct = ff_j_rev_dct;
c->perm_type = FF_IDCT_PERM_LIBMPEG2;
#if CONFIG_FAANIDCT
} else if (avctx->idct_algo == FF_IDCT_FAAN) {
c->idct_put = ff_faanidct_put;
c->idct_add = ff_faanidct_add;
c->idct = ff_faanidct;
c->perm_type = FF_IDCT_PERM_NONE;
#endif /* CONFIG_FAANIDCT */
} else { // accurate/default
/* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */
c->idct_put = ff_simple_idct_put_int16_8bit;
c->idct_add = ff_simple_idct_add_int16_8bit;
c->idct = ff_simple_idct_int16_8bit;
c->perm_type = FF_IDCT_PERM_NONE;
}
}
}
c->put_pixels_clamped = ff_put_pixels_clamped_c;
c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
c->add_pixels_clamped = ff_add_pixels_clamped_c;
if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID)
ff_xvid_idct_init(c, avctx);
if (ARCH_AARCH64)
ff_idctdsp_init_aarch64(c, avctx, high_bit_depth);
if (ARCH_ALPHA)
ff_idctdsp_init_alpha(c, avctx, high_bit_depth);
if (ARCH_ARM)
ff_idctdsp_init_arm(c, avctx, high_bit_depth);
if (ARCH_PPC)
ff_idctdsp_init_ppc(c, avctx, high_bit_depth);
if (ARCH_X86)
ff_idctdsp_init_x86(c, avctx, high_bit_depth);
if (ARCH_MIPS)
ff_idctdsp_init_mips(c, avctx, high_bit_depth);
ff_init_scantable_permutation(c->idct_permutation,
c->perm_type);
}
| 169,189 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,
int atomic)
{
unsigned long copy;
while (len > 0) {
while (!iov->iov_len)
iov++;
copy = min_t(unsigned long, len, iov->iov_len);
if (atomic) {
if (__copy_from_user_inatomic(to, iov->iov_base, copy))
return -EFAULT;
} else {
if (copy_from_user(to, iov->iov_base, copy))
return -EFAULT;
}
to += copy;
len -= copy;
iov->iov_base += copy;
iov->iov_len -= copy;
}
return 0;
}
Commit Message: new helper: copy_page_from_iter()
parallel to copy_page_to_iter(). pipe_write() switched to it (and became
->write_iter()).
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,
| 166,686 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LosslessTestLarge()
: EncoderTest(GET_PARAM(0)),
psnr_(kMaxPsnr),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
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 | LosslessTestLarge()
LosslessTest()
: EncoderTest(GET_PARAM(0)),
psnr_(kMaxPsnr),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
| 174,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AcceleratedStaticBitmapImage::RetainOriginalSkImage() {
DCHECK(texture_holder_->IsSkiaTextureHolder());
original_skia_image_ = texture_holder_->GetSkImage();
original_skia_image_context_provider_wrapper_ = ContextProviderWrapper();
DCHECK(original_skia_image_);
Thread* thread = Platform::Current()->CurrentThread();
original_skia_image_thread_id_ = thread->ThreadId();
original_skia_image_task_runner_ = thread->GetTaskRunner();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void AcceleratedStaticBitmapImage::RetainOriginalSkImage() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(texture_holder_->IsSkiaTextureHolder());
original_skia_image_ = texture_holder_->GetSkImage();
original_skia_image_context_provider_wrapper_ = ContextProviderWrapper();
DCHECK(original_skia_image_);
Thread* thread = Platform::Current()->CurrentThread();
original_skia_image_task_runner_ = thread->GetTaskRunner();
}
| 172,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DECLAREcpFunc(cpSeparate2ContigByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
for (row = 0; row < imagelength; row++) {
/* merge channels */
for (s = 0; s < spp; s++) {
if (TIFFReadScanline(in, inbuf, row, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = (uint8*)inbuf;
outp = ((uint8*)outbuf) + s;
for (n = imagewidth; n-- > 0;) {
*outp = *inp++;
outp += spp;
}
}
if (TIFFWriteScanline(out, outbuf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and
cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and
http://bugzilla.maptools.org/show_bug.cgi?id=2657
CWE ID: CWE-119 | DECLAREcpFunc(cpSeparate2ContigByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
uint16 bps = 0;
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps != 8 )
{
TIFFError(TIFFFileName(in),
"Error, can only handle BitsPerSample=8 in %s",
"cpSeparate2ContigByRow");
return 0;
}
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
for (row = 0; row < imagelength; row++) {
/* merge channels */
for (s = 0; s < spp; s++) {
if (TIFFReadScanline(in, inbuf, row, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = (uint8*)inbuf;
outp = ((uint8*)outbuf) + s;
for (n = imagewidth; n-- > 0;) {
*outp = *inp++;
outp += spp;
}
}
if (TIFFWriteScanline(out, outbuf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
| 168,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NaClProcessHost::OnPpapiChannelCreated(
const IPC::ChannelHandle& channel_handle) {
DCHECK(enable_ipc_proxy_);
ReplyToRenderer(channel_handle);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void NaClProcessHost::OnPpapiChannelCreated(
return ReplyToRenderer() && StartNaClExecution();
}
| 170,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes)
{
ulg rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR WARNING: grayscale needs to be expanded and channels reset! */
*pRowbytes = rowbytes = channels*width;
*pChannels = channels;
if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
return NULL;
}
Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height));
/* now we can go ahead and just read the whole image */
fread(image_data, 1L, rowbytes*height, saved_infile);
return image_data;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes)
{
ulg rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR WARNING: grayscale needs to be expanded and channels reset! */
*pRowbytes = rowbytes = channels*width;
*pChannels = channels;
if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
return NULL;
}
Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height));
/* now we can go ahead and just read the whole image */
if (fread(image_data, 1L, rowbytes*height, saved_infile) <
rowbytes*height) {
free (image_data);
image_data = NULL;
return NULL;
}
return image_data;
}
| 173,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mountpoint_last(struct nameidata *nd, struct path *path)
{
int error = 0;
struct dentry *dentry;
struct dentry *dir = nd->path.dentry;
/* If we're in rcuwalk, drop out of it to handle last component */
if (nd->flags & LOOKUP_RCU) {
if (unlazy_walk(nd, NULL)) {
error = -ECHILD;
goto out;
}
}
nd->flags &= ~LOOKUP_PARENT;
if (unlikely(nd->last_type != LAST_NORM)) {
error = handle_dots(nd, nd->last_type);
if (error)
goto out;
dentry = dget(nd->path.dentry);
goto done;
}
mutex_lock(&dir->d_inode->i_mutex);
dentry = d_lookup(dir, &nd->last);
if (!dentry) {
/*
* No cached dentry. Mounted dentries are pinned in the cache,
* so that means that this dentry is probably a symlink or the
* path doesn't actually point to a mounted dentry.
*/
dentry = d_alloc(dir, &nd->last);
if (!dentry) {
error = -ENOMEM;
mutex_unlock(&dir->d_inode->i_mutex);
goto out;
}
dentry = lookup_real(dir->d_inode, dentry, nd->flags);
error = PTR_ERR(dentry);
if (IS_ERR(dentry)) {
mutex_unlock(&dir->d_inode->i_mutex);
goto out;
}
}
mutex_unlock(&dir->d_inode->i_mutex);
done:
if (!dentry->d_inode || d_is_negative(dentry)) {
error = -ENOENT;
dput(dentry);
goto out;
}
path->dentry = dentry;
path->mnt = mntget(nd->path.mnt);
if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW))
return 1;
follow_mount(path);
error = 0;
out:
terminate_walk(nd);
return error;
}
Commit Message: fs: umount on symlink leaks mnt count
Currently umount on symlink blocks following umount:
/vz is separate mount
# ls /vz/ -al | grep test
drwxr-xr-x. 2 root root 4096 Jul 19 01:14 testdir
lrwxrwxrwx. 1 root root 11 Jul 19 01:16 testlink -> /vz/testdir
# umount -l /vz/testlink
umount: /vz/testlink: not mounted (expected)
# lsof /vz
# umount /vz
umount: /vz: device is busy. (unexpected)
In this case mountpoint_last() gets an extra refcount on path->mnt
Signed-off-by: Vasily Averin <[email protected]>
Acked-by: Ian Kent <[email protected]>
Acked-by: Jeff Layton <[email protected]>
Cc: [email protected]
Signed-off-by: Christoph Hellwig <[email protected]>
CWE ID: CWE-59 | mountpoint_last(struct nameidata *nd, struct path *path)
{
int error = 0;
struct dentry *dentry;
struct dentry *dir = nd->path.dentry;
/* If we're in rcuwalk, drop out of it to handle last component */
if (nd->flags & LOOKUP_RCU) {
if (unlazy_walk(nd, NULL)) {
error = -ECHILD;
goto out;
}
}
nd->flags &= ~LOOKUP_PARENT;
if (unlikely(nd->last_type != LAST_NORM)) {
error = handle_dots(nd, nd->last_type);
if (error)
goto out;
dentry = dget(nd->path.dentry);
goto done;
}
mutex_lock(&dir->d_inode->i_mutex);
dentry = d_lookup(dir, &nd->last);
if (!dentry) {
/*
* No cached dentry. Mounted dentries are pinned in the cache,
* so that means that this dentry is probably a symlink or the
* path doesn't actually point to a mounted dentry.
*/
dentry = d_alloc(dir, &nd->last);
if (!dentry) {
error = -ENOMEM;
mutex_unlock(&dir->d_inode->i_mutex);
goto out;
}
dentry = lookup_real(dir->d_inode, dentry, nd->flags);
error = PTR_ERR(dentry);
if (IS_ERR(dentry)) {
mutex_unlock(&dir->d_inode->i_mutex);
goto out;
}
}
mutex_unlock(&dir->d_inode->i_mutex);
done:
if (!dentry->d_inode || d_is_negative(dentry)) {
error = -ENOENT;
dput(dentry);
goto out;
}
path->dentry = dentry;
path->mnt = nd->path.mnt;
if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW))
return 1;
mntget(path->mnt);
follow_mount(path);
error = 0;
out:
terminate_walk(nd);
return error;
}
| 166,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags);
if (offset == 0)
break;
}
}
return 0;
}
Commit Message: Bail out on partial reads, from Alexander Cherepanov
CWE ID: CWE-20 | dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags);
if (offset == 0)
break;
}
}
return 0;
}
| 166,767 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
int i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, size_t offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
size_t i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
| 165,485 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool(
ResourceProvider* resource_provider,
ContextProvider* context_provider,
size_t num_threads,
size_t max_transfer_buffer_usage_bytes)
: RasterWorkerPool(resource_provider, context_provider, num_threads),
shutdown_(false),
scheduled_raster_task_count_(0),
bytes_pending_upload_(0),
max_bytes_pending_upload_(max_transfer_buffer_usage_bytes),
has_performed_uploads_since_last_flush_(false),
check_for_completed_raster_tasks_pending_(false),
should_notify_client_if_no_tasks_are_pending_(false),
should_notify_client_if_no_tasks_required_for_activation_are_pending_(
false) {
}
Commit Message: cc: Simplify raster task completion notification logic
(Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/)
Previously the pixel buffer raster worker pool used a combination of
polling and explicit notifications from the raster worker pool to decide
when to tell the client about the completion of 1) all tasks or 2) the
subset of tasks required for activation. This patch simplifies the logic
by only triggering the notification based on the OnRasterTasksFinished
and OnRasterTasksRequiredForActivationFinished calls from the worker
pool.
BUG=307841,331534
Review URL: https://codereview.chromium.org/99873007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool(
ResourceProvider* resource_provider,
ContextProvider* context_provider,
size_t num_threads,
size_t max_transfer_buffer_usage_bytes)
: RasterWorkerPool(resource_provider, context_provider, num_threads),
shutdown_(false),
scheduled_raster_task_count_(0),
bytes_pending_upload_(0),
max_bytes_pending_upload_(max_transfer_buffer_usage_bytes),
has_performed_uploads_since_last_flush_(false),
check_for_completed_raster_tasks_pending_(false),
should_notify_client_if_no_tasks_are_pending_(false),
should_notify_client_if_no_tasks_required_for_activation_are_pending_(
false),
raster_finished_task_pending_(false),
raster_required_for_activation_finished_task_pending_(false) {
}
| 171,262 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uipc_read_task(void *arg)
{
int ch_id;
int result;
UNUSED(arg);
prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0);
raise_priority_a2dp(TASK_UIPC_READ);
while (uipc_main.running)
{
uipc_main.read_set = uipc_main.active_set;
result = select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL);
if (result == 0)
{
BTIF_TRACE_EVENT("select timeout");
continue;
}
else if (result < 0)
{
BTIF_TRACE_EVENT("select failed %s", strerror(errno));
continue;
}
UIPC_LOCK();
/* clear any wakeup interrupt */
uipc_check_interrupt_locked();
/* check pending task events */
uipc_check_task_flags_locked();
/* make sure we service audio channel first */
uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO);
/* check for other connections */
for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++)
{
if (ch_id != UIPC_CH_ID_AV_AUDIO)
uipc_check_fd_locked(ch_id);
}
UIPC_UNLOCK();
}
BTIF_TRACE_EVENT("UIPC READ THREAD EXITING");
uipc_main_cleanup();
uipc_main.tid = 0;
BTIF_TRACE_EVENT("UIPC READ THREAD DONE");
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static void uipc_read_task(void *arg)
{
int ch_id;
int result;
UNUSED(arg);
prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0);
raise_priority_a2dp(TASK_UIPC_READ);
while (uipc_main.running)
{
uipc_main.read_set = uipc_main.active_set;
result = TEMP_FAILURE_RETRY(select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL));
if (result == 0)
{
BTIF_TRACE_EVENT("select timeout");
continue;
}
else if (result < 0)
{
BTIF_TRACE_EVENT("select failed %s", strerror(errno));
continue;
}
UIPC_LOCK();
/* clear any wakeup interrupt */
uipc_check_interrupt_locked();
/* check pending task events */
uipc_check_task_flags_locked();
/* make sure we service audio channel first */
uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO);
/* check for other connections */
for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++)
{
if (ch_id != UIPC_CH_ID_AV_AUDIO)
uipc_check_fd_locked(ch_id);
}
UIPC_UNLOCK();
}
BTIF_TRACE_EVENT("UIPC READ THREAD EXITING");
uipc_main_cleanup();
uipc_main.tid = 0;
BTIF_TRACE_EVENT("UIPC READ THREAD DONE");
}
| 173,498 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated", "app.window",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
| 172,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebContentsImpl::ShowingInterstitialPage() const {
return GetRenderManager()->interstitial_page() != NULL;
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | bool WebContentsImpl::ShowingInterstitialPage() const {
return interstitial_page_ != nullptr;
}
| 172,334 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: otp_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request,
krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond, void *arg)
{
krb5_keyblock *armor_key = NULL;
krb5_pa_otp_req *req = NULL;
struct request_state *rs;
krb5_error_code retval;
krb5_data d, plaintext;
char *config;
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
/* Get the FAST armor key. */
armor_key = cb->fast_armor(context, rock);
if (armor_key == NULL) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
com_err("otp", retval, "No armor key found when verifying padata");
goto error;
}
/* Decode the request. */
d = make_data(pa->contents, pa->length);
retval = decode_krb5_pa_otp_req(&d, &req);
if (retval != 0) {
com_err("otp", retval, "Unable to decode OTP request");
goto error;
}
/* Decrypt the nonce from the request. */
retval = decrypt_encdata(context, armor_key, req, &plaintext);
if (retval != 0) {
com_err("otp", retval, "Unable to decrypt nonce");
goto error;
}
/* Verify the nonce or timestamp. */
retval = nonce_verify(context, armor_key, &plaintext);
if (retval != 0)
retval = timestamp_verify(context, &plaintext);
krb5_free_data_contents(context, &plaintext);
if (retval != 0) {
com_err("otp", retval, "Unable to verify nonce or timestamp");
goto error;
}
/* Create the request state. */
rs = k5alloc(sizeof(struct request_state), &retval);
if (rs == NULL)
goto error;
rs->arg = arg;
rs->respond = respond;
/* Get the principal's OTP configuration string. */
retval = cb->get_string(context, rock, "otp", &config);
if (retval == 0 && config == NULL)
retval = KRB5_PREAUTH_FAILED;
if (retval != 0) {
free(rs);
goto error;
}
/* Send the request. */
otp_state_verify((otp_state *)moddata, cb->event_context(context, rock),
request->client, config, req, on_response, rs);
cb->free_string(context, rock, config);
k5_free_pa_otp_req(context, req);
return;
error:
k5_free_pa_otp_req(context, req);
(*respond)(arg, retval, NULL, NULL, NULL);
}
Commit Message: Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]
CWE ID: CWE-264 | otp_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request,
krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond, void *arg)
{
krb5_keyblock *armor_key = NULL;
krb5_pa_otp_req *req = NULL;
struct request_state *rs;
krb5_error_code retval;
krb5_data d, plaintext;
char *config;
/* Get the FAST armor key. */
armor_key = cb->fast_armor(context, rock);
if (armor_key == NULL) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
com_err("otp", retval, "No armor key found when verifying padata");
goto error;
}
/* Decode the request. */
d = make_data(pa->contents, pa->length);
retval = decode_krb5_pa_otp_req(&d, &req);
if (retval != 0) {
com_err("otp", retval, "Unable to decode OTP request");
goto error;
}
/* Decrypt the nonce from the request. */
retval = decrypt_encdata(context, armor_key, req, &plaintext);
if (retval != 0) {
com_err("otp", retval, "Unable to decrypt nonce");
goto error;
}
/* Verify the nonce or timestamp. */
retval = nonce_verify(context, armor_key, &plaintext);
if (retval != 0)
retval = timestamp_verify(context, &plaintext);
krb5_free_data_contents(context, &plaintext);
if (retval != 0) {
com_err("otp", retval, "Unable to verify nonce or timestamp");
goto error;
}
/* Create the request state. Save the response callback, and the
* enc_tkt_reply pointer so we can set the TKT_FLG_PRE_AUTH flag later. */
rs = k5alloc(sizeof(struct request_state), &retval);
if (rs == NULL)
goto error;
rs->arg = arg;
rs->respond = respond;
rs->enc_tkt_reply = enc_tkt_reply;
/* Get the principal's OTP configuration string. */
retval = cb->get_string(context, rock, "otp", &config);
if (retval == 0 && config == NULL)
retval = KRB5_PREAUTH_FAILED;
if (retval != 0) {
free(rs);
goto error;
}
/* Send the request. */
otp_state_verify((otp_state *)moddata, cb->event_context(context, rock),
request->client, config, req, on_response, rs);
cb->free_string(context, rock, config);
k5_free_pa_otp_req(context, req);
return;
error:
k5_free_pa_otp_req(context, req);
(*respond)(arg, retval, NULL, NULL, NULL);
}
| 166,677 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltStylesheetPtr XSLStyleSheet::compileStyleSheet()
{
if (m_embedded)
return xsltLoadStylesheetPI(document());
ASSERT(!m_stylesheetDocTaken);
xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc);
if (result)
m_stylesheetDocTaken = true;
return result;
}
Commit Message: Avoid reparsing an XSLT stylesheet after the first failure.
Certain libxslt versions appear to leave the doc in an invalid state when parsing fails. We should cache this result and avoid re-parsing.
(The test cannot be converted to text-only due to its invalid stylesheet).
[email protected],[email protected],[email protected]
BUG=271939
Review URL: https://chromiumcodereview.appspot.com/23103007
git-svn-id: svn://svn.chromium.org/blink/trunk@156248 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | xsltStylesheetPtr XSLStyleSheet::compileStyleSheet()
{
if (m_embedded)
return xsltLoadStylesheetPI(document());
// Certain libxslt versions are corrupting the xmlDoc on compilation failures -
// hence attempting to recompile after a failure is unsafe.
if (m_compilationFailed)
return 0;
ASSERT(!m_stylesheetDocTaken);
xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc);
if (result)
m_stylesheetDocTaken = true;
else
m_compilationFailed = true;
return result;
}
| 171,185 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (!frame) {
args.GetReturnValue().SetNull();
return;
}
WebDataSource* data_source = frame->dataSource();
if (!data_source) {
args.GetReturnValue().SetNull();
return;
}
DocumentState* document_state = DocumentState::FromDataSource(data_source);
if (!document_state) {
args.GetReturnValue().SetNull();
return;
}
double request_time = document_state->request_time().ToDoubleT();
double start_load_time = document_state->start_load_time().ToDoubleT();
double commit_load_time = document_state->commit_load_time().ToDoubleT();
double finish_document_load_time =
document_state->finish_document_load_time().ToDoubleT();
double finish_load_time = document_state->finish_load_time().ToDoubleT();
double first_paint_time = document_state->first_paint_time().ToDoubleT();
double first_paint_after_load_time =
document_state->first_paint_after_load_time().ToDoubleT();
std::string navigation_type =
GetNavigationType(data_source->navigationType());
bool was_fetched_via_spdy = document_state->was_fetched_via_spdy();
bool was_npn_negotiated = document_state->was_npn_negotiated();
std::string npn_negotiated_protocol =
document_state->npn_negotiated_protocol();
bool was_alternate_protocol_available =
document_state->was_alternate_protocol_available();
std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString(
document_state->connection_info());
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> load_times = v8::Object::New(isolate);
load_times->Set(v8::String::NewFromUtf8(isolate, "requestTime"),
v8::Number::New(isolate, request_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "startLoadTime"),
v8::Number::New(isolate, start_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "commitLoadTime"),
v8::Number::New(isolate, commit_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"),
v8::Number::New(isolate, finish_document_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "finishLoadTime"),
v8::Number::New(isolate, finish_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintTime"),
v8::Number::New(isolate, first_paint_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"),
v8::Number::New(isolate, first_paint_after_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "navigationType"),
v8::String::NewFromUtf8(isolate, navigation_type.c_str()));
load_times->Set(v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"),
v8::Boolean::New(isolate, was_fetched_via_spdy));
load_times->Set(v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"),
v8::Boolean::New(isolate, was_npn_negotiated));
load_times->Set(
v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"),
v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"),
v8::Boolean::New(isolate, was_alternate_protocol_available));
load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"),
v8::String::NewFromUtf8(isolate, connection_info.c_str()));
args.GetReturnValue().Set(load_times);
}
Commit Message: Cache csi info before passing it to JS setters.
JS setters invalidate the pointers frame, data_source and document_state.
BUG=590455
Review URL: https://codereview.chromium.org/1751553002
Cr-Commit-Position: refs/heads/master@{#379047}
CWE ID: | static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().SetNull();
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (!frame) {
return;
}
WebDataSource* data_source = frame->dataSource();
if (!data_source) {
return;
}
DocumentState* document_state = DocumentState::FromDataSource(data_source);
if (!document_state) {
return;
}
double request_time = document_state->request_time().ToDoubleT();
double start_load_time = document_state->start_load_time().ToDoubleT();
double commit_load_time = document_state->commit_load_time().ToDoubleT();
double finish_document_load_time =
document_state->finish_document_load_time().ToDoubleT();
double finish_load_time = document_state->finish_load_time().ToDoubleT();
double first_paint_time = document_state->first_paint_time().ToDoubleT();
double first_paint_after_load_time =
document_state->first_paint_after_load_time().ToDoubleT();
std::string navigation_type =
GetNavigationType(data_source->navigationType());
bool was_fetched_via_spdy = document_state->was_fetched_via_spdy();
bool was_npn_negotiated = document_state->was_npn_negotiated();
std::string npn_negotiated_protocol =
document_state->npn_negotiated_protocol();
bool was_alternate_protocol_available =
document_state->was_alternate_protocol_available();
std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString(
document_state->connection_info());
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context> ctx = isolate->GetCurrentContext();
v8::Local<v8::Object> load_times = v8::Object::New(isolate);
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "requestTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, request_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "startLoadTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, start_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "commitLoadTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, commit_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx,
v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, finish_document_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "finishLoadTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, finish_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "firstPaintTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, first_paint_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx,
v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, first_paint_after_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "navigationType",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::String::NewFromUtf8(isolate, navigation_type.c_str(),
v8::NewStringType::kNormal)
.ToLocalChecked())
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Boolean::New(isolate, was_fetched_via_spdy))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "wasNpnNegotiated",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Boolean::New(isolate, was_npn_negotiated))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx,
v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::String::NewFromUtf8(isolate,
npn_negotiated_protocol.c_str(),
v8::NewStringType::kNormal)
.ToLocalChecked())
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate,
"wasAlternateProtocolAvailable",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Boolean::New(isolate, was_alternate_protocol_available))
.FromMaybe(false)) {
return;
}
if (!load_times
->Set(ctx, v8::String::NewFromUtf8(isolate, "connectionInfo",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::String::NewFromUtf8(isolate, connection_info.c_str(),
v8::NewStringType::kNormal)
.ToLocalChecked())
.FromMaybe(false)) {
return;
}
args.GetReturnValue().Set(load_times);
}
| 172,118 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool blit_is_unsafe(struct CirrusVGAState *s)
{
/* should be the case, see cirrus_bitblt_start */
assert(s->cirrus_blt_width > 0);
assert(s->cirrus_blt_height > 0);
if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch,
s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) {
return true;
}
return false;
}
Commit Message:
CWE ID: CWE-119 | static bool blit_is_unsafe(struct CirrusVGAState *s)
{
/* should be the case, see cirrus_bitblt_start */
assert(s->cirrus_blt_width > 0);
assert(s->cirrus_blt_height > 0);
if (s->cirrus_blt_width > CIRRUS_BLTBUFSIZE) {
return true;
}
if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch,
s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) {
return true;
}
return false;
}
| 164,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HeapAllocator::backingExpand(void* address, size_t newSize) {
if (!address)
return false;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return false;
ASSERT(!state->isInGC());
ASSERT(state->isAllocationAllowed());
DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return false;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
ASSERT(header->checkHeader());
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
bool succeed = arena->expandObject(header, newSize);
if (succeed)
state->allocationPointAdjusted(arena->arenaIndex());
return succeed;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | bool HeapAllocator::backingExpand(void* address, size_t newSize) {
if (!address)
return false;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return false;
ASSERT(!state->isInGC());
ASSERT(state->isAllocationAllowed());
DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return false;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
header->checkHeader();
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
bool succeed = arena->expandObject(header, newSize);
if (succeed)
state->allocationPointAdjusted(arena->arenaIndex());
return succeed;
}
| 172,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
goto vcpu_destroy;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto unlock_vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto unlock_vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
mutex_unlock(&kvm->lock);
return r;
unlock_vcpu_destroy:
mutex_unlock(&kvm->lock);
vcpu_destroy:
kvm_arch_vcpu_destroy(vcpu);
return r;
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-399 | static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
goto vcpu_destroy;
mutex_lock(&kvm->lock);
if (!kvm_vcpu_compatible(vcpu)) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto unlock_vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto unlock_vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
mutex_unlock(&kvm->lock);
return r;
unlock_vcpu_destroy:
mutex_unlock(&kvm->lock);
vcpu_destroy:
kvm_arch_vcpu_destroy(vcpu);
return r;
}
| 165,621 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder)
{
RELEASE_ASSERT(!holder.IsEmpty());
RELEASE_ASSERT(holder->IsObject());
v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder);
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Context> context = scriptState->context();
auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate);
if (privateIsInitialized.hasValue(context, holderObject))
return; // Already initialized.
v8::TryCatch block(isolate);
v8::Local<v8::Value> initializeFunction;
if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) {
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(initializeFunction), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) {
fprintf(stderr, "Private script error: Object constructor threw an exception.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (classObject->GetPrototype() != holderObject->GetPrototype()) {
if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate));
}
Commit Message: Blink-in-JS should not run micro tasks
If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug
(see 645211 for concrete steps).
This CL makes Blink-in-JS use callInternalFunction (instead of callFunction)
to avoid running micro tasks after Blink-in-JS' callbacks.
BUG=645211
Review-Url: https://codereview.chromium.org/2330843002
Cr-Commit-Position: refs/heads/master@{#417874}
CWE ID: CWE-79 | static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder)
{
RELEASE_ASSERT(!holder.IsEmpty());
RELEASE_ASSERT(holder->IsObject());
v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder);
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Context> context = scriptState->context();
auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate);
if (privateIsInitialized.hasValue(context, holderObject))
return; // Already initialized.
v8::TryCatch block(isolate);
v8::Local<v8::Value> initializeFunction;
if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) {
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(initializeFunction), holder, 0, 0, isolate).ToLocal(&result)) {
fprintf(stderr, "Private script error: Object constructor threw an exception.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (classObject->GetPrototype() != holderObject->GetPrototype()) {
if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate));
}
| 172,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeMockRenderThread::OnDidGetPrintedPagesCount(
int cookie, int number_pages) {
if (printer_.get())
printer_->SetPrintedPagesCount(cookie, number_pages);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void ChromeMockRenderThread::OnDidGetPrintedPagesCount(
int cookie, int number_pages) {
printer_->SetPrintedPagesCount(cookie, number_pages);
}
| 170,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
{
struct sctp_association *asoc = sctp_id2assoc(sk, id);
struct sctp_sock *sp = sctp_sk(sk);
struct socket *sock;
int err = 0;
if (!asoc)
return -EINVAL;
/* An association cannot be branched off from an already peeled-off
* socket, nor is this supported for tcp style sockets.
*/
if (!sctp_style(sk, UDP))
return -EINVAL;
/* Create a new socket. */
err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
if (err < 0)
return err;
sctp_copy_sock(sock->sk, sk, asoc);
/* Make peeled-off sockets more like 1-1 accepted sockets.
* Set the daddr and initialize id to something more random
*/
sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
*sockp = sock;
return err;
}
Commit Message: sctp: deny peeloff operation on asocs with threads sleeping on it
commit 2dcab5984841 ("sctp: avoid BUG_ON on sctp_wait_for_sndbuf")
attempted to avoid a BUG_ON call when the association being used for a
sendmsg() is blocked waiting for more sndbuf and another thread did a
peeloff operation on such asoc, moving it to another socket.
As Ben Hutchings noticed, then in such case it would return without
locking back the socket and would cause two unlocks in a row.
Further analysis also revealed that it could allow a double free if the
application managed to peeloff the asoc that is created during the
sendmsg call, because then sctp_sendmsg() would try to free the asoc
that was created only for that call.
This patch takes another approach. It will deny the peeloff operation
if there is a thread sleeping on the asoc, so this situation doesn't
exist anymore. This avoids the issues described above and also honors
the syscalls that are already being handled (it can be multiple sendmsg
calls).
Joint work with Xin Long.
Fixes: 2dcab5984841 ("sctp: avoid BUG_ON on sctp_wait_for_sndbuf")
Cc: Alexander Popov <[email protected]>
Cc: Ben Hutchings <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: Xin Long <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-415 | int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
{
struct sctp_association *asoc = sctp_id2assoc(sk, id);
struct sctp_sock *sp = sctp_sk(sk);
struct socket *sock;
int err = 0;
if (!asoc)
return -EINVAL;
/* If there is a thread waiting on more sndbuf space for
* sending on this asoc, it cannot be peeled.
*/
if (waitqueue_active(&asoc->wait))
return -EBUSY;
/* An association cannot be branched off from an already peeled-off
* socket, nor is this supported for tcp style sockets.
*/
if (!sctp_style(sk, UDP))
return -EINVAL;
/* Create a new socket. */
err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
if (err < 0)
return err;
sctp_copy_sock(sock->sk, sk, asoc);
/* Make peeled-off sockets more like 1-1 accepted sockets.
* Set the daddr and initialize id to something more random
*/
sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
*sockp = sock;
return err;
}
| 168,342 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt,
NetClientState *nc)
{
struct iovec fragment[NET_MAX_FRAG_SG_LIST];
size_t fragment_len = 0;
bool more_frags = false;
/* some pointers for shorter code */
void *l2_iov_base, *l3_iov_base;
size_t l2_iov_len, l3_iov_len;
int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx;
size_t src_offset = 0;
size_t fragment_offset = 0;
l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base;
l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len;
l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;
l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len;
/* Copy headers */
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len;
/* Put as much data as possible and send */
do {
fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset,
fragment, &dst_idx);
more_frags = (fragment_offset + fragment_len < pkt->payload_len);
eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base,
l3_iov_len, fragment_len, fragment_offset, more_frags);
eth_fix_ip4_checksum(l3_iov_base, l3_iov_len);
net_tx_pkt_sendv(pkt, nc, fragment, dst_idx);
fragment_offset += fragment_len;
} while (more_frags);
return true;
}
Commit Message:
CWE ID: CWE-399 | static bool net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt,
NetClientState *nc)
{
struct iovec fragment[NET_MAX_FRAG_SG_LIST];
size_t fragment_len = 0;
bool more_frags = false;
/* some pointers for shorter code */
void *l2_iov_base, *l3_iov_base;
size_t l2_iov_len, l3_iov_len;
int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx;
size_t src_offset = 0;
size_t fragment_offset = 0;
l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base;
l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len;
l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;
l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len;
/* Copy headers */
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len;
/* Put as much data as possible and send */
do {
fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset,
fragment, &dst_idx);
more_frags = (fragment_offset + fragment_len < pkt->payload_len);
eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base,
l3_iov_len, fragment_len, fragment_offset, more_frags);
eth_fix_ip4_checksum(l3_iov_base, l3_iov_len);
net_tx_pkt_sendv(pkt, nc, fragment, dst_idx);
fragment_offset += fragment_len;
} while (fragment_len && more_frags);
return true;
}
| 164,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rndis_query_response(USBNetState *s,
rndis_query_msg_type *buf, unsigned int length)
{
rndis_query_cmplt_type *resp;
/* oid_supported_list is the largest data reply */
uint8_t infobuf[sizeof(oid_supported_list)];
uint32_t bufoffs, buflen;
int infobuflen;
unsigned int resplen;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen, infobuf,
resplen = sizeof(rndis_query_cmplt_type) +
((infobuflen < 0) ? 0 : infobuflen);
resp = rndis_queue_response(s, resplen);
if (!resp)
return USB_RET_STALL;
resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
resp->MessageLength = cpu_to_le32(resplen);
if (infobuflen < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
resp->InformationBufferLength = cpu_to_le32(0);
resp->InformationBufferOffset = cpu_to_le32(0);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
resp->InformationBufferOffset =
cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
resp->InformationBufferLength = cpu_to_le32(infobuflen);
memcpy(resp + 1, infobuf, infobuflen);
return 0;
}
Commit Message:
CWE ID: CWE-189 | static int rndis_query_response(USBNetState *s,
rndis_query_msg_type *buf, unsigned int length)
{
rndis_query_cmplt_type *resp;
/* oid_supported_list is the largest data reply */
uint8_t infobuf[sizeof(oid_supported_list)];
uint32_t bufoffs, buflen;
int infobuflen;
unsigned int resplen;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (buflen > length || bufoffs >= length || bufoffs + buflen > length) {
return USB_RET_STALL;
}
infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen, infobuf,
resplen = sizeof(rndis_query_cmplt_type) +
((infobuflen < 0) ? 0 : infobuflen);
resp = rndis_queue_response(s, resplen);
if (!resp)
return USB_RET_STALL;
resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
resp->MessageLength = cpu_to_le32(resplen);
if (infobuflen < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
resp->InformationBufferLength = cpu_to_le32(0);
resp->InformationBufferOffset = cpu_to_le32(0);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
resp->InformationBufferOffset =
cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
resp->InformationBufferLength = cpu_to_le32(infobuflen);
memcpy(resp + 1, infobuf, infobuflen);
return 0;
}
| 165,185 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 handle_data_packet(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, int data_len) {
struct mt_mactelnet_control_hdr cpkt;
struct mt_packet pdata;
unsigned char *data = pkthdr->data;
unsigned int act_size = 0;
int got_user_packet = 0;
int got_pass_packet = 0;
int got_width_packet = 0;
int got_height_packet = 0;
int success;
/* Parse first control packet */
success = parse_control_packet(data, data_len - MT_HEADER_LEN, &cpkt);
while (success) {
if (cpkt.cptype == MT_CPTYPE_BEGINAUTH) {
int plen,i;
if (!curconn->have_pass_salt) {
for (i = 0; i < 16; ++i) {
curconn->pass_salt[i] = rand() % 256;
}
curconn->have_pass_salt = 1;
memset(curconn->trypassword, 0, sizeof(curconn->trypassword));
}
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
plen = add_control_packet(&pdata, MT_CPTYPE_PASSSALT, (curconn->pass_salt), 16);
curconn->outcounter += plen;
send_udp(curconn, &pdata);
/* Don't change the username after the state is active */
} else if (cpkt.cptype == MT_CPTYPE_USERNAME && curconn->state != STATE_ACTIVE) {
memcpy(curconn->username, cpkt.data, act_size = (cpkt.length > MT_MNDP_MAX_STRING_SIZE - 1 ? MT_MNDP_MAX_STRING_SIZE - 1 : cpkt.length));
curconn->username[act_size] = 0;
got_user_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_WIDTH && cpkt.length >= 2) {
unsigned short width;
memcpy(&width, cpkt.data, 2);
curconn->terminal_width = le16toh(width);
got_width_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_HEIGHT && cpkt.length >= 2) {
unsigned short height;
memcpy(&height, cpkt.data, 2);
curconn->terminal_height = le16toh(height);
got_height_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_TYPE) {
memcpy(curconn->terminal_type, cpkt.data, act_size = (cpkt.length > 30 - 1 ? 30 - 1 : cpkt.length));
curconn->terminal_type[act_size] = 0;
} else if (cpkt.cptype == MT_CPTYPE_PASSWORD) {
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(curconn->trypassword, 17);
#endif
memcpy(curconn->trypassword, cpkt.data, 17);
got_pass_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
/* relay data from client to shell */
if (curconn->state == STATE_ACTIVE && curconn->ptsfd != -1) {
write(curconn->ptsfd, cpkt.data, cpkt.length);
}
} else {
syslog(LOG_WARNING, _("(%d) Unhandeled control packet type: %d"), curconn->seskey, cpkt.cptype);
}
/* Parse next control packet */
success = parse_control_packet(NULL, 0, &cpkt);
}
if (got_user_packet && got_pass_packet) {
user_login(curconn, pkthdr);
}
if (curconn->state == STATE_ACTIVE && (got_width_packet || got_height_packet)) {
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
Commit Message: Merge pull request #20 from eyalitki/master
2nd round security fixes from eyalitki
CWE ID: CWE-119 | static void handle_data_packet(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, int data_len) {
struct mt_mactelnet_control_hdr cpkt;
struct mt_packet pdata;
unsigned char *data = pkthdr->data;
unsigned int act_size = 0;
int got_user_packet = 0;
int got_pass_packet = 0;
int got_width_packet = 0;
int got_height_packet = 0;
int success;
/* Parse first control packet */
success = parse_control_packet(data, data_len - MT_HEADER_LEN, &cpkt);
while (success) {
if (cpkt.cptype == MT_CPTYPE_BEGINAUTH) {
int plen,i;
if (!curconn->have_pass_salt) {
for (i = 0; i < 16; ++i) {
curconn->pass_salt[i] = rand() % 256;
}
curconn->have_pass_salt = 1;
memset(curconn->trypassword, 0, sizeof(curconn->trypassword));
}
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
plen = add_control_packet(&pdata, MT_CPTYPE_PASSSALT, (curconn->pass_salt), 16);
curconn->outcounter += plen;
send_udp(curconn, &pdata);
/* Don't change the username after the state is active */
} else if (cpkt.cptype == MT_CPTYPE_USERNAME && curconn->state != STATE_ACTIVE) {
memcpy(curconn->username, cpkt.data, act_size = (cpkt.length > MT_MNDP_MAX_STRING_SIZE - 1 ? MT_MNDP_MAX_STRING_SIZE - 1 : cpkt.length));
curconn->username[act_size] = 0;
got_user_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_WIDTH && cpkt.length >= 2) {
unsigned short width;
memcpy(&width, cpkt.data, 2);
curconn->terminal_width = le16toh(width);
got_width_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_HEIGHT && cpkt.length >= 2) {
unsigned short height;
memcpy(&height, cpkt.data, 2);
curconn->terminal_height = le16toh(height);
got_height_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_TYPE) {
memcpy(curconn->terminal_type, cpkt.data, act_size = (cpkt.length > 30 - 1 ? 30 - 1 : cpkt.length));
curconn->terminal_type[act_size] = 0;
} else if (cpkt.cptype == MT_CPTYPE_PASSWORD && cpkt.length == 17) {
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(curconn->trypassword, 17);
#endif
memcpy(curconn->trypassword, cpkt.data, 17);
got_pass_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
/* relay data from client to shell */
if (curconn->state == STATE_ACTIVE && curconn->ptsfd != -1) {
write(curconn->ptsfd, cpkt.data, cpkt.length);
}
} else {
syslog(LOG_WARNING, _("(%d) Unhandeled control packet type: %d, length: %d"), curconn->seskey, cpkt.cptype, cpkt.length);
}
/* Parse next control packet */
success = parse_control_packet(NULL, 0, &cpkt);
}
if (got_user_packet && got_pass_packet) {
user_login(curconn, pkthdr);
}
if (curconn->state == STATE_ACTIVE && (got_width_packet || got_height_packet)) {
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
| 166,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BiquadDSPKernel::process(const float* source, float* destination, size_t framesToProcess)
{
ASSERT(source && destination && biquadProcessor());
updateCoefficientsIfNecessary(true, false);
m_biquad.process(source, destination, framesToProcess);
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void BiquadDSPKernel::process(const float* source, float* destination, size_t framesToProcess)
{
ASSERT(source && destination && biquadProcessor());
// The audio thread can't block on this lock; skip updating the coefficients for this block if
// necessary. We'll get them the next time around.
{
MutexTryLocker tryLocker(m_processLock);
if (tryLocker.locked())
updateCoefficientsIfNecessary();
}
m_biquad.process(source, destination, framesToProcess);
}
| 171,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebRunnerContentBrowserClient::CreateBrowserMainParts(
const content::MainFunctionParams& parameters) {
DCHECK(context_channel_);
return new WebRunnerBrowserMainParts(std::move(context_channel_));
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | WebRunnerContentBrowserClient::CreateBrowserMainParts(
const content::MainFunctionParams& parameters) {
DCHECK(context_channel_);
main_parts_ = new WebRunnerBrowserMainParts(std::move(context_channel_));
return main_parts_;
}
| 172,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: alloc_limit_failure (char *fn_name, size_t size)
{
fprintf (stderr,
"%s: Maximum allocation size exceeded "
"(maxsize = %lu; size = %lu).\n",
fn_name,
(unsigned long)alloc_limit,
(unsigned long)size);
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190 | alloc_limit_failure (char *fn_name, size_t size)
{
fprintf (stderr,
"%s: Maximum allocation size exceeded "
"(maxsize = %lu; size = %lu).\n",
fn_name,
(unsigned long)alloc_limit,
(unsigned long)size);
}
| 168,355 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(void)
{
fwrite(signature, sizeof signature, 1, stdout);
put_chunk(IHDR, sizeof IHDR);
for(;;)
put_chunk(unknown, sizeof unknown);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | main(void)
{
fwrite(signature, sizeof signature, 1, stdout);
put_chunk(IHDR, sizeof IHDR);
for (;;)
put_chunk(unknown, sizeof unknown);
}
| 173,577 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 perform_gamma_transform_tests(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/))
{
unsigned int i, j;
for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, palette_number,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
pm->use_input_precision, 0 /*do not scale16*/);
if (fail(pm))
return;
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void perform_gamma_transform_tests(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
while (next_format(&colour_type, &bit_depth, &palette_number,
pm->test_lbg_gamma_transform, pm->test_tRNS))
{
unsigned int i, j;
for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, palette_number,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
pm->use_input_precision, 0 /*do not scale16*/);
if (fail(pm))
return;
}
}
}
| 173,683 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_default_root(pool *p, int allow_symlinks, char **root) {
config_rec *c = NULL;
char *dir = NULL;
int res;
c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE);
while (c) {
pr_signals_handle();
/* Check the groups acl */
if (c->argc < 2) {
dir = c->argv[0];
break;
}
res = pr_expr_eval_group_and(((char **) c->argv)+1);
if (res) {
dir = c->argv[0];
break;
}
c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE);
}
if (dir) {
char *new_dir;
/* Check for any expandable variables. */
new_dir = path_subst_uservar(p, &dir);
if (new_dir != NULL) {
dir = new_dir;
}
if (strncmp(dir, "/", 2) == 0) {
dir = NULL;
} else {
char *realdir;
int xerrno = 0;
if (allow_symlinks == FALSE) {
char *path, target_path[PR_TUNABLE_PATH_MAX + 1];
struct stat st;
size_t pathlen;
/* First, deal with any possible interpolation. dir_realpath() will
* do this for us, but dir_realpath() ALSO automatically follows
* symlinks, which is what we do NOT want to do here.
*/
path = dir;
if (*path != '/') {
if (*path == '~') {
if (pr_fs_interpolate(dir, target_path,
sizeof(target_path)-1) < 0) {
return -1;
}
path = target_path;
}
}
/* Note: lstat(2) is sensitive to the presence of a trailing slash on
* the path, particularly in the case of a symlink to a directory.
* Thus to get the correct test, we need to remove any trailing slash
* that might be present. Subtle.
*/
pathlen = strlen(path);
if (pathlen > 1 &&
path[pathlen-1] == '/') {
path[pathlen-1] = '\0';
}
pr_fs_clear_cache();
res = pr_fsio_lstat(path, &st);
if (res < 0) {
xerrno = errno;
pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path,
strerror(xerrno));
errno = xerrno;
return -1;
}
if (S_ISLNK(st.st_mode)) {
pr_log_pri(PR_LOG_WARNING,
"error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks "
"config)", path);
errno = EPERM;
return -1;
}
}
/* We need to be the final user here so that if the user has their home
* directory with a mode the user proftpd is running (i.e. the User
* directive) as can not traverse down, we can still have the default
* root.
*/
PRIVS_USER
realdir = dir_realpath(p, dir);
xerrno = errno;
PRIVS_RELINQUISH
if (realdir) {
dir = realdir;
} else {
/* Try to provide a more informative message. */
char interp_dir[PR_TUNABLE_PATH_MAX + 1];
memset(interp_dir, '\0', sizeof(interp_dir));
(void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1);
pr_log_pri(PR_LOG_NOTICE,
"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s",
dir, interp_dir, strerror(xerrno));
errno = xerrno;
}
}
}
*root = dir;
return 0;
}
Commit Message: Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks
is off, to 1.3.5 branch.
CWE ID: CWE-59 | static int get_default_root(pool *p, int allow_symlinks, char **root) {
config_rec *c = NULL;
char *dir = NULL;
int res;
c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE);
while (c) {
pr_signals_handle();
/* Check the groups acl */
if (c->argc < 2) {
dir = c->argv[0];
break;
}
res = pr_expr_eval_group_and(((char **) c->argv)+1);
if (res) {
dir = c->argv[0];
break;
}
c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE);
}
if (dir) {
char *new_dir;
/* Check for any expandable variables. */
new_dir = path_subst_uservar(p, &dir);
if (new_dir != NULL) {
dir = new_dir;
}
if (strncmp(dir, "/", 2) == 0) {
dir = NULL;
} else {
char *realdir;
int xerrno = 0;
if (allow_symlinks == FALSE) {
char *path, target_path[PR_TUNABLE_PATH_MAX + 1];
size_t pathlen;
/* First, deal with any possible interpolation. dir_realpath() will
* do this for us, but dir_realpath() ALSO automatically follows
* symlinks, which is what we do NOT want to do here.
*/
path = dir;
if (*path != '/') {
if (*path == '~') {
if (pr_fs_interpolate(dir, target_path,
sizeof(target_path)-1) < 0) {
return -1;
}
path = target_path;
}
}
/* Note: lstat(2) is sensitive to the presence of a trailing slash on
* the path, particularly in the case of a symlink to a directory.
* Thus to get the correct test, we need to remove any trailing slash
* that might be present. Subtle.
*/
pathlen = strlen(path);
if (pathlen > 1 &&
path[pathlen-1] == '/') {
path[pathlen-1] = '\0';
}
res = is_symlink_path(p, path, pathlen);
if (res < 0) {
if (errno == EPERM) {
pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink "
"(denied by AllowChrootSymlinks config)", path);
}
errno = EPERM;
return -1;
}
}
/* We need to be the final user here so that if the user has their home
* directory with a mode the user proftpd is running (i.e. the User
* directive) as can not traverse down, we can still have the default
* root.
*/
PRIVS_USER
realdir = dir_realpath(p, dir);
xerrno = errno;
PRIVS_RELINQUISH
if (realdir) {
dir = realdir;
} else {
/* Try to provide a more informative message. */
char interp_dir[PR_TUNABLE_PATH_MAX + 1];
memset(interp_dir, '\0', sizeof(interp_dir));
(void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1);
pr_log_pri(PR_LOG_NOTICE,
"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s",
dir, interp_dir, strerror(xerrno));
errno = xerrno;
}
}
}
*root = dir;
return 0;
}
| 170,070 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ParamTraits<FilePath>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
FilePath::StringType value;
if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value))
return false;
*r = FilePath(value);
return true;
}
Commit Message: Validate that paths don't contain embedded NULLs at deserialization.
BUG=166867
Review URL: https://chromiumcodereview.appspot.com/11743009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool ParamTraits<FilePath>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
FilePath::StringType value;
if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value))
return false;
// Reject embedded NULs as they can cause security checks to go awry.
if (value.find(FILE_PATH_LITERAL('\0')) != FilePath::StringType::npos)
return false;
*r = FilePath(value);
return true;
}
| 171,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Chapters::Atom::~Atom()
{
}
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 | Chapters::Atom::~Atom()
const char* SegmentInfo::GetMuxingAppAsUTF8() const {
return m_pMuxingAppAsUTF8;
}
| 174,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
return;
} else {
bucket = &(*bucket)->next;
}
}
}
/* }}} */
Commit Message:
CWE ID: CWE-190 | CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
return;
} else {
bucket = &(*bucket)->next;
}
}
}
/* }}} */
| 164,982 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void show_object(struct object *object, struct strbuf *path,
const char *last, void *data)
{
struct bitmap *base = data;
bitmap_set(base, find_object_pos(object->oid.hash));
mark_as_seen(object);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void show_object(struct object *object, struct strbuf *path,
static void show_object(struct object *object, const char *name, void *data)
{
struct bitmap *base = data;
bitmap_set(base, find_object_pos(object->oid.hash));
mark_as_seen(object);
}
| 167,421 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WM_SYMBOL midi *WildMidi_Open(const char *midifile) {
uint8_t *mididata = NULL;
uint32_t midisize = 0;
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midifile == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0);
return (NULL);
}
if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) {
return (NULL);
}
if (memcmp(mididata,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(mididata, midisize);
} else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(mididata, midisize);
} else if (memcmp(mididata, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(mididata, midisize);
} else if (memcmp(mididata, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(mididata, midisize);
} else {
ret = (void *) _WM_ParseNewMidi(mididata, midisize);
}
free(mididata);
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input
Fixes bug #178.
CWE ID: CWE-119 | WM_SYMBOL midi *WildMidi_Open(const char *midifile) {
uint8_t *mididata = NULL;
uint32_t midisize = 0;
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midifile == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0);
return (NULL);
}
if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) {
return (NULL);
}
if (midisize < 18) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return (NULL);
}
if (memcmp(mididata,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(mididata, midisize);
} else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(mididata, midisize);
} else if (memcmp(mididata, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(mididata, midisize);
} else if (memcmp(mididata, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(mididata, midisize);
} else {
ret = (void *) _WM_ParseNewMidi(mididata, midisize);
}
free(mididata);
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
| 169,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
Commit Message: Add sanity check for debug trace print statement (fix #1420)
CWE ID: CWE-476 | void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)?jswGetBasicObjectName(var):"unknown ArrayBuffer"); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
| 169,217 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
Commit Message: irda: Fix missing msg_namelen update in irda_recvmsg_dgram()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about irda_recvmsg_dgram() not filling the msg_name in case it was
set.
Cc: Samuel Ortiz <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
msg->msg_namelen = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
| 166,039 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::GetFirst(const BlockEntry*& pBlockEntry) const
{
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0; ; )
{
if (pCluster == NULL)
{
pBlockEntry = GetEOS();
return 1;
}
if (pCluster->EOS())
{
#if 0
if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded
{
pBlockEntry = GetEOS();
return 1;
}
#else
if (m_pSegment->DoneParsing())
{
pBlockEntry = GetEOS();
return 1;
}
#endif
pBlockEntry = 0;
return E_BUFFER_NOT_FULL;
}
long status = pCluster->GetFirst(pBlockEntry);
if (status < 0) //error
return status;
if (pBlockEntry == 0) //empty cluster
{
pCluster = m_pSegment->GetNext(pCluster);
continue;
}
for (;;)
{
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
const long long tn = pBlock->GetTrackNumber();
if ((tn == m_info.number) && VetEntry(pBlockEntry))
return 0;
const BlockEntry* pNextEntry;
status = pCluster->GetNext(pBlockEntry, pNextEntry);
if (status < 0) //error
return status;
if (pNextEntry == 0)
break;
pBlockEntry = pNextEntry;
}
++i;
if (i >= 100)
break;
pCluster = m_pSegment->GetNext(pCluster);
}
pBlockEntry = GetEOS(); //so we can return a non-NULL value
return 1;
}
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 Track::GetFirst(const BlockEntry*& pBlockEntry) const
if (pCluster->EOS()) {
#if 0
if (m_pSegment->Unparsed() <= 0) { //all clusters have been loaded
pBlockEntry = GetEOS();
return 1;
}
#else
if (m_pSegment->DoneParsing()) {
pBlockEntry = GetEOS();
return 1;
}
#endif
pBlockEntry = 0;
return E_BUFFER_NOT_FULL;
}
long status = pCluster->GetFirst(pBlockEntry);
| 174,319 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) {
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len -
JP2_BOX_HDRLEN(false))) {
jas_eprintf("cannot copy box data\n");
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
}
| 168,319 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CaptivePortalDetector::DetectCaptivePortal(
const GURL& url,
const DetectionCallback& detection_callback) {
DCHECK(CalledOnValidThread());
DCHECK(!FetchingURL());
DCHECK(detection_callback_.is_null());
detection_callback_ = detection_callback;
url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
url_fetcher_->SetAutomaticallyRetryOn5xx(false);
url_fetcher_->SetRequestContext(request_context_.get());
url_fetcher_->SetLoadFlags(
net::LOAD_BYPASS_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190 | void CaptivePortalDetector::DetectCaptivePortal(
const GURL& url,
const DetectionCallback& detection_callback) {
DCHECK(CalledOnValidThread());
DCHECK(!FetchingURL());
DCHECK(detection_callback_.is_null());
detection_callback_ = detection_callback;
url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
url_fetcher_->SetAutomaticallyRetryOn5xx(false);
url_fetcher_->SetRequestContext(request_context_.get());
data_use_measurement::DataUseUserData::AttachToFetcher(
url_fetcher_.get(),
data_use_measurement::DataUseUserData::CAPTIVE_PORTAL);
url_fetcher_->SetLoadFlags(
net::LOAD_BYPASS_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
}
| 172,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: static int cuse_channel_release(struct inode *inode, struct file *file)
{
struct fuse_dev *fud = file->private_data;
struct cuse_conn *cc = fc_to_cc(fud->fc);
int rc;
/* remove from the conntbl, no more access from this point on */
mutex_lock(&cuse_lock);
list_del_init(&cc->list);
mutex_unlock(&cuse_lock);
/* remove device */
if (cc->dev)
device_unregister(cc->dev);
if (cc->cdev) {
unregister_chrdev_region(cc->cdev->dev, 1);
cdev_del(cc->cdev);
}
rc = fuse_dev_release(inode, file); /* puts the base reference */
return rc;
}
Commit Message: cuse: fix memory leak
The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc,
and the original ref count is never dropped.
Reported-by: Colin Ian King <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure")
Cc: <[email protected]> # v4.2+
CWE ID: CWE-399 | static int cuse_channel_release(struct inode *inode, struct file *file)
{
struct fuse_dev *fud = file->private_data;
struct cuse_conn *cc = fc_to_cc(fud->fc);
int rc;
/* remove from the conntbl, no more access from this point on */
mutex_lock(&cuse_lock);
list_del_init(&cc->list);
mutex_unlock(&cuse_lock);
/* remove device */
if (cc->dev)
device_unregister(cc->dev);
if (cc->cdev) {
unregister_chrdev_region(cc->cdev->dev, 1);
cdev_del(cc->cdev);
}
/* Base reference is now owned by "fud" */
fuse_conn_put(&cc->fc);
rc = fuse_dev_release(inode, file); /* puts the base reference */
return rc;
}
| 167,573 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; "
"т > t; [шщ] > w; ട > s;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add more confusable character map entries
When comparing domain names with top 10k domain names for confusability,
characters with diacritics are decomposed into base + diacritic marks
(Unicode Normalization Form D) and diacritics are dropped before
calculating the confusability skeleton because two characters with and
without a diacritics is NOT regarded as confusable.
However, there are a dozen of characters (most of them are Cyrillic)
with a diacritic-like mark attached but they are not decomposed into
base + diacritics by NFD (e.g. U+049B, қ; Cyrillic Small Letter Ka
with Descender). This CL treats them the same way as their "base"
characters. For instance, қ (U+049B) is treated as confusable with
Latin k because к (U+043A; Cyrillic Small Letter Ka) is.
They're curated from the following sets:
[:IdentifierStatus=Allowed:] & [:Ll:] &
[[:sc=Cyrillic:] -
[[\u01cd-\u01dc][\u1c80-\u1c8f][\u1e00-\u1e9b][\u1f00-\u1fff]
[\ua640-\ua69f][\ua720-\ua7ff]]] &
[:NFD_Inert=Yes:]
[:IdentifierStatus=Allowed:] & [:Ll:] &
[[:sc=Latin:] - [[\u01cd-\u01dc][\u1e00-\u1e9b][\ua720-\ua7ff]]] &
[:NFD_Inert=Yes:]
[:IdentifierStatus=Allowed:] & [:Ll:] & [[:sc=Greek:]] &
[:NFD_Inert=Yes:]
Bug: 793628,798892
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I20c6af13defa295f6952f33d75987e87ce1853d0
Reviewed-on: https://chromium-review.googlesource.com/860567
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Eric Lawrence <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529129}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+00FE (þ), U+03FC (ϼ), U+048F (ҏ)} => p
// - {U+0127 (ħ), U+043D (н), U+045B (ћ), U+04A3 (ң), U+04A5 (ҥ),
// U+04C8 (ӈ), U+0527 (ԧ), U+0529 (ԩ)} => h
// - {U+0138 (ĸ), U+03BA (κ), U+043A (к), U+049B (қ), U+049D (ҝ),
// U+049F (ҟ), U+04A1(ҡ), U+04C4 (ӄ), U+051F (ԟ)} => k
// - {U+0167 (ŧ), U+0442 (т), U+04AD (ҭ)} => t
// - {U+0185 (ƅ), U+044C (ь), U+048D (ҍ), U+0432 (в)} => b
// - {U+03C9 (ω), U+0448 (ш), U+0449 (щ)} => w
// - {U+043C (м), U+04CE (ӎ)} => m
// - U+0491 (ґ) => r
// - U+0493 (ғ) => f
// - U+04AB (ҫ) => c
// - U+04B1 (ұ) => y
// - U+03C7 (χ), U+04B3 (ҳ), U+04FD (ӽ), U+04FF (ӿ) => x
// - U+04BD (ҽ), U+04BF (ҿ) => e
// - U+04CF (ӏ) => l
// - U+0503 (ԃ) => d
// - U+050D (ԍ) => g
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŧтҭ] > t;"
"[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;"
"п > n; ћ > h; ґ > r; ғ > f; ҫ > c;"
"ұ > y; [χҳӽӿ] > x; [ҽҿ] > e; ӏ > l;"
"ԃ > d; ԍ > g; ട > s"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,910 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FrameSequenceState_gif::drawFrame(int frameNr,
Color8888* outputPtr, int outputPixelStride, int previousFrameNr) {
GifFileType* gif = mFrameSequence.getGif();
if (!gif) {
ALOGD("Cannot drawFrame, mGif is NULL");
return -1;
}
#if GIF_DEBUG
ALOGD(" drawFrame on %p nr %d on addr %p, previous frame nr %d",
this, frameNr, outputPtr, previousFrameNr);
#endif
const int height = mFrameSequence.getHeight();
const int width = mFrameSequence.getWidth();
GraphicsControlBlock gcb;
int start = max(previousFrameNr + 1, 0);
for (int i = max(start - 1, 0); i < frameNr; i++) {
int neededPreservedFrame = mFrameSequence.getRestoringFrame(i);
if (neededPreservedFrame >= 0 && (mPreserveBufferFrame != neededPreservedFrame)) {
#if GIF_DEBUG
ALOGD("frame %d needs frame %d preserved, but %d is currently, so drawing from scratch",
i, neededPreservedFrame, mPreserveBufferFrame);
#endif
start = 0;
}
}
for (int i = start; i <= frameNr; i++) {
DGifSavedExtensionToGCB(gif, i, &gcb);
const SavedImage& frame = gif->SavedImages[i];
#if GIF_DEBUG
bool frameOpaque = gcb.TransparentColor == NO_TRANSPARENT_COLOR;
ALOGD("producing frame %d, drawing frame %d (opaque %d, disp %d, del %d)",
frameNr, i, frameOpaque, gcb.DisposalMode, gcb.DelayTime);
#endif
if (i == 0) {
Color8888 bgColor = mFrameSequence.getBackgroundColor();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
outputPtr[y * outputPixelStride + x] = bgColor;
}
}
} else {
GraphicsControlBlock prevGcb;
DGifSavedExtensionToGCB(gif, i - 1, &prevGcb);
const SavedImage& prevFrame = gif->SavedImages[i - 1];
bool prevFrameDisposed = willBeCleared(prevGcb);
bool newFrameOpaque = gcb.TransparentColor == NO_TRANSPARENT_COLOR;
bool prevFrameCompletelyCovered = newFrameOpaque
&& checkIfCover(frame.ImageDesc, prevFrame.ImageDesc);
if (prevFrameDisposed && !prevFrameCompletelyCovered) {
switch (prevGcb.DisposalMode) {
case DISPOSE_BACKGROUND: {
Color8888* dst = outputPtr + prevFrame.ImageDesc.Left +
prevFrame.ImageDesc.Top * outputPixelStride;
GifWord copyWidth, copyHeight;
getCopySize(prevFrame.ImageDesc, width, height, copyWidth, copyHeight);
for (; copyHeight > 0; copyHeight--) {
setLineColor(dst, TRANSPARENT, copyWidth);
dst += outputPixelStride;
}
} break;
case DISPOSE_PREVIOUS: {
restorePreserveBuffer(outputPtr, outputPixelStride);
} break;
}
}
if (mFrameSequence.getPreservedFrame(i - 1)) {
savePreserveBuffer(outputPtr, outputPixelStride, i - 1);
}
}
bool willBeCleared = gcb.DisposalMode == DISPOSE_BACKGROUND
|| gcb.DisposalMode == DISPOSE_PREVIOUS;
if (i == frameNr || !willBeCleared) {
const ColorMapObject* cmap = gif->SColorMap;
if (frame.ImageDesc.ColorMap) {
cmap = frame.ImageDesc.ColorMap;
}
if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) {
ALOGW("Warning: potentially corrupt color map");
}
const unsigned char* src = (unsigned char*)frame.RasterBits;
Color8888* dst = outputPtr + frame.ImageDesc.Left +
frame.ImageDesc.Top * outputPixelStride;
GifWord copyWidth, copyHeight;
getCopySize(frame.ImageDesc, width, height, copyWidth, copyHeight);
for (; copyHeight > 0; copyHeight--) {
copyLine(dst, src, cmap, gcb.TransparentColor, copyWidth);
src += frame.ImageDesc.Width;
dst += outputPixelStride;
}
}
}
const int maxFrame = gif->ImageCount;
const int lastFrame = (frameNr + maxFrame - 1) % maxFrame;
DGifSavedExtensionToGCB(gif, lastFrame, &gcb);
return getDelayMs(gcb);
}
Commit Message: Skip composition of frames lacking a color map
Bug:68399117
Change-Id: I32f1d6856221b8a60130633edb69da2d2986c27c
(cherry picked from commit 0dc887f70eeea8d707cb426b96c6756edd1c607d)
CWE ID: CWE-20 | long FrameSequenceState_gif::drawFrame(int frameNr,
Color8888* outputPtr, int outputPixelStride, int previousFrameNr) {
GifFileType* gif = mFrameSequence.getGif();
if (!gif) {
ALOGD("Cannot drawFrame, mGif is NULL");
return -1;
}
#if GIF_DEBUG
ALOGD(" drawFrame on %p nr %d on addr %p, previous frame nr %d",
this, frameNr, outputPtr, previousFrameNr);
#endif
const int height = mFrameSequence.getHeight();
const int width = mFrameSequence.getWidth();
GraphicsControlBlock gcb;
int start = max(previousFrameNr + 1, 0);
for (int i = max(start - 1, 0); i < frameNr; i++) {
int neededPreservedFrame = mFrameSequence.getRestoringFrame(i);
if (neededPreservedFrame >= 0 && (mPreserveBufferFrame != neededPreservedFrame)) {
#if GIF_DEBUG
ALOGD("frame %d needs frame %d preserved, but %d is currently, so drawing from scratch",
i, neededPreservedFrame, mPreserveBufferFrame);
#endif
start = 0;
}
}
for (int i = start; i <= frameNr; i++) {
DGifSavedExtensionToGCB(gif, i, &gcb);
const SavedImage& frame = gif->SavedImages[i];
#if GIF_DEBUG
bool frameOpaque = gcb.TransparentColor == NO_TRANSPARENT_COLOR;
ALOGD("producing frame %d, drawing frame %d (opaque %d, disp %d, del %d)",
frameNr, i, frameOpaque, gcb.DisposalMode, gcb.DelayTime);
#endif
if (i == 0) {
Color8888 bgColor = mFrameSequence.getBackgroundColor();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
outputPtr[y * outputPixelStride + x] = bgColor;
}
}
} else {
GraphicsControlBlock prevGcb;
DGifSavedExtensionToGCB(gif, i - 1, &prevGcb);
const SavedImage& prevFrame = gif->SavedImages[i - 1];
bool prevFrameDisposed = willBeCleared(prevGcb);
bool newFrameOpaque = gcb.TransparentColor == NO_TRANSPARENT_COLOR;
bool prevFrameCompletelyCovered = newFrameOpaque
&& checkIfCover(frame.ImageDesc, prevFrame.ImageDesc);
if (prevFrameDisposed && !prevFrameCompletelyCovered) {
switch (prevGcb.DisposalMode) {
case DISPOSE_BACKGROUND: {
Color8888* dst = outputPtr + prevFrame.ImageDesc.Left +
prevFrame.ImageDesc.Top * outputPixelStride;
GifWord copyWidth, copyHeight;
getCopySize(prevFrame.ImageDesc, width, height, copyWidth, copyHeight);
for (; copyHeight > 0; copyHeight--) {
setLineColor(dst, TRANSPARENT, copyWidth);
dst += outputPixelStride;
}
} break;
case DISPOSE_PREVIOUS: {
restorePreserveBuffer(outputPtr, outputPixelStride);
} break;
}
}
if (mFrameSequence.getPreservedFrame(i - 1)) {
savePreserveBuffer(outputPtr, outputPixelStride, i - 1);
}
}
bool willBeCleared = gcb.DisposalMode == DISPOSE_BACKGROUND
|| gcb.DisposalMode == DISPOSE_PREVIOUS;
if (i == frameNr || !willBeCleared) {
const ColorMapObject* cmap = gif->SColorMap;
if (frame.ImageDesc.ColorMap) {
cmap = frame.ImageDesc.ColorMap;
}
// If a cmap is missing, the frame can't be decoded, so we skip it.
if (cmap) {
const unsigned char* src = (unsigned char*)frame.RasterBits;
Color8888* dst = outputPtr + frame.ImageDesc.Left +
frame.ImageDesc.Top * outputPixelStride;
GifWord copyWidth, copyHeight;
getCopySize(frame.ImageDesc, width, height, copyWidth, copyHeight);
for (; copyHeight > 0; copyHeight--) {
copyLine(dst, src, cmap, gcb.TransparentColor, copyWidth);
src += frame.ImageDesc.Width;
dst += outputPixelStride;
}
}
}
}
const int maxFrame = gif->ImageCount;
const int lastFrame = (frameNr + maxFrame - 1) % maxFrame;
DGifSavedExtensionToGCB(gif, lastFrame, &gcb);
return getDelayMs(gcb);
}
| 174,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t SoundTriggerHwService::Module::loadSoundModel(const sp<IMemory>& modelMemory,
sound_model_handle_t *handle)
{
ALOGV("loadSoundModel() handle");
if (!captureHotwordAllowed()) {
return PERMISSION_DENIED;
}
if (modelMemory == 0 || modelMemory->pointer() == NULL) {
ALOGE("loadSoundModel() modelMemory is 0 or has NULL pointer()");
return BAD_VALUE;
}
struct sound_trigger_sound_model *sound_model =
(struct sound_trigger_sound_model *)modelMemory->pointer();
AutoMutex lock(mLock);
if (mModels.size() >= mDescriptor.properties.max_sound_models) {
ALOGW("loadSoundModel(): Not loading, max number of models (%d) would be exceeded",
mDescriptor.properties.max_sound_models);
return INVALID_OPERATION;
}
status_t status = mHwDevice->load_sound_model(mHwDevice, sound_model,
SoundTriggerHwService::soundModelCallback,
this, handle);
if (status != NO_ERROR) {
return status;
}
audio_session_t session;
audio_io_handle_t ioHandle;
audio_devices_t device;
status = AudioSystem::acquireSoundTriggerSession(&session, &ioHandle, &device);
if (status != NO_ERROR) {
return status;
}
sp<Model> model = new Model(*handle, session, ioHandle, device, sound_model->type);
mModels.replaceValueFor(*handle, model);
return status;
}
Commit Message: soundtrigger: add size check on sound model and recogntion data
Bug: 30148546
Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0
(cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8)
(cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd)
CWE ID: CWE-264 | status_t SoundTriggerHwService::Module::loadSoundModel(const sp<IMemory>& modelMemory,
sound_model_handle_t *handle)
{
ALOGV("loadSoundModel() handle");
if (!captureHotwordAllowed()) {
return PERMISSION_DENIED;
}
if (modelMemory == 0 || modelMemory->pointer() == NULL) {
ALOGE("loadSoundModel() modelMemory is 0 or has NULL pointer()");
return BAD_VALUE;
}
struct sound_trigger_sound_model *sound_model =
(struct sound_trigger_sound_model *)modelMemory->pointer();
size_t structSize;
if (sound_model->type == SOUND_MODEL_TYPE_KEYPHRASE) {
structSize = sizeof(struct sound_trigger_phrase_sound_model);
} else {
structSize = sizeof(struct sound_trigger_sound_model);
}
if (sound_model->data_offset < structSize ||
sound_model->data_size > (UINT_MAX - sound_model->data_offset) ||
modelMemory->size() < sound_model->data_offset ||
sound_model->data_size > (modelMemory->size() - sound_model->data_offset)) {
android_errorWriteLog(0x534e4554, "30148546");
ALOGE("loadSoundModel() data_size is too big");
return BAD_VALUE;
}
AutoMutex lock(mLock);
if (mModels.size() >= mDescriptor.properties.max_sound_models) {
ALOGW("loadSoundModel(): Not loading, max number of models (%d) would be exceeded",
mDescriptor.properties.max_sound_models);
return INVALID_OPERATION;
}
status_t status = mHwDevice->load_sound_model(mHwDevice, sound_model,
SoundTriggerHwService::soundModelCallback,
this, handle);
if (status != NO_ERROR) {
return status;
}
audio_session_t session;
audio_io_handle_t ioHandle;
audio_devices_t device;
status = AudioSystem::acquireSoundTriggerSession(&session, &ioHandle, &device);
if (status != NO_ERROR) {
return status;
}
sp<Model> model = new Model(*handle, session, ioHandle, device, sound_model->type);
mModels.replaceValueFor(*handle, model);
return status;
}
| 173,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 spl_load_fit_image(struct spl_load_info *info, ulong sector,
void *fit, ulong base_offset, int node,
struct spl_image_info *image_info)
{
int offset;
size_t length;
int len;
ulong size;
ulong load_addr, load_ptr;
void *src;
ulong overhead;
int nr_sectors;
int align_len = ARCH_DMA_MINALIGN - 1;
uint8_t image_comp = -1, type = -1;
const void *data;
bool external_data = false;
if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
(IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
if (fit_image_get_type(fit, node, &type))
puts("Cannot get image type.\n");
else
debug("%s ", genimg_get_type_name(type));
}
if (IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP)) {
if (fit_image_get_comp(fit, node, &image_comp))
puts("Cannot get image compression format.\n");
else
debug("%s ", genimg_get_comp_name(image_comp));
}
if (fit_image_get_load(fit, node, &load_addr))
load_addr = image_info->load_addr;
if (!fit_image_get_data_position(fit, node, &offset)) {
external_data = true;
} else if (!fit_image_get_data_offset(fit, node, &offset)) {
offset += base_offset;
external_data = true;
}
if (external_data) {
/* External data */
if (fit_image_get_data_size(fit, node, &len))
return -ENOENT;
load_ptr = (load_addr + align_len) & ~align_len;
length = len;
overhead = get_aligned_image_overhead(info, offset);
nr_sectors = get_aligned_image_size(info, length, offset);
if (info->read(info,
sector + get_aligned_image_offset(info, offset),
nr_sectors, (void *)load_ptr) != nr_sectors)
return -EIO;
debug("External data: dst=%lx, offset=%x, size=%lx\n",
load_ptr, offset, (unsigned long)length);
src = (void *)load_ptr + overhead;
} else {
/* Embedded data */
if (fit_image_get_data(fit, node, &data, &length)) {
puts("Cannot get image data/size\n");
return -ENOENT;
}
debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
(unsigned long)length);
src = (void *)data;
}
#ifdef CONFIG_SPL_FIT_SIGNATURE
printf("## Checking hash(es) for Image %s ... ",
fit_get_name(fit, node, NULL));
if (!fit_image_verify_with_data(fit, node,
src, length))
return -EPERM;
puts("OK\n");
#endif
#ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
board_fit_image_post_process(&src, &length);
#endif
if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
size = length;
if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
src, &size)) {
puts("Uncompressing error\n");
return -EIO;
}
length = size;
} else {
memcpy((void *)load_addr, src, length);
}
if (image_info) {
image_info->load_addr = load_addr;
image_info->size = length;
image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
}
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | static int spl_load_fit_image(struct spl_load_info *info, ulong sector,
void *fit, ulong base_offset, int node,
struct spl_image_info *image_info)
{
int offset;
size_t length;
int len;
ulong size;
ulong load_addr, load_ptr;
void *src;
ulong overhead;
int nr_sectors;
int align_len = ARCH_DMA_MINALIGN - 1;
uint8_t image_comp = -1, type = -1;
const void *data;
bool external_data = false;
if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
(IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
if (fit_image_get_type(fit, node, &type))
puts("Cannot get image type.\n");
else
debug("%s ", genimg_get_type_name(type));
}
if (IS_ENABLED(CONFIG_SPL_GZIP)) {
fit_image_get_comp(fit, node, &image_comp);
debug("%s ", genimg_get_comp_name(image_comp));
}
if (fit_image_get_load(fit, node, &load_addr))
load_addr = image_info->load_addr;
if (!fit_image_get_data_position(fit, node, &offset)) {
external_data = true;
} else if (!fit_image_get_data_offset(fit, node, &offset)) {
offset += base_offset;
external_data = true;
}
if (external_data) {
/* External data */
if (fit_image_get_data_size(fit, node, &len))
return -ENOENT;
load_ptr = (load_addr + align_len) & ~align_len;
length = len;
overhead = get_aligned_image_overhead(info, offset);
nr_sectors = get_aligned_image_size(info, length, offset);
if (info->read(info,
sector + get_aligned_image_offset(info, offset),
nr_sectors, (void *)load_ptr) != nr_sectors)
return -EIO;
debug("External data: dst=%lx, offset=%x, size=%lx\n",
load_ptr, offset, (unsigned long)length);
src = (void *)load_ptr + overhead;
} else {
/* Embedded data */
if (fit_image_get_data(fit, node, &data, &length)) {
puts("Cannot get image data/size\n");
return -ENOENT;
}
debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
(unsigned long)length);
src = (void *)data;
}
#ifdef CONFIG_SPL_FIT_SIGNATURE
printf("## Checking hash(es) for Image %s ... ",
fit_get_name(fit, node, NULL));
if (!fit_image_verify_with_data(fit, node,
src, length))
return -EPERM;
puts("OK\n");
#endif
#ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
board_fit_image_post_process(&src, &length);
#endif
if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
size = length;
if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
src, &size)) {
puts("Uncompressing error\n");
return -EIO;
}
length = size;
} else {
memcpy((void *)load_addr, src, length);
}
if (image_info) {
image_info->load_addr = load_addr;
image_info->size = length;
image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
}
return 0;
}
| 169,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: validate_T(void)
/* Validate the above table - this just builds the above values */
{
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i)
{
if (transform_info[i].when & TRANSFORM_R)
read_transforms |= transform_info[i].transform;
if (transform_info[i].when & TRANSFORM_W)
write_transforms |= transform_info[i].transform;
}
/* Reversible transforms are those which are supported on both read and
* write.
*/
rw_transforms = read_transforms & write_transforms;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | validate_T(void)
/* Validate the above table - this just builds the above values */
{
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL)
{
if (transform_info[i].when & TRANSFORM_R)
read_transforms |= transform_info[i].transform;
if (transform_info[i].when & TRANSFORM_W)
write_transforms |= transform_info[i].transform;
}
/* Reversible transforms are those which are supported on both read and
* write.
*/
rw_transforms = read_transforms & write_transforms;
}
| 173,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AppModalDialog::~AppModalDialog() {
}
Commit Message: Fix a Windows crash bug with javascript alerts from extension popups.
BUG=137707
Review URL: https://chromiumcodereview.appspot.com/10828423
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | AppModalDialog::~AppModalDialog() {
CompleteDialog();
}
| 170,755 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b)
{
return b[0] | (b[1]<<8);
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682 | IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b)
{
return (unsigned int)b[0] | ((unsigned int)b[1]<<8);
}
| 168,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
{
if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE))
IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u "
"addr %pM\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) {
IWL_DEBUG_ASSOC(priv,
"STA id %u addr %pM already present in uCode "
"(according to driver)\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
} else {
priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE;
IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
}
}
Commit Message: iwlwifi: Sanity check for sta_id
On my testing, I saw some strange behavior
[ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00
[ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode
not sure how it happen, but adding the sanity check to prevent memory
corruption
Signed-off-by: Wey-Yi Guy <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-119 | static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
static int iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
{
if (sta_id >= IWLAGN_STATION_COUNT) {
IWL_ERR(priv, "invalid sta_id %u", sta_id);
return -EINVAL;
}
if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE))
IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u "
"addr %pM\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) {
IWL_DEBUG_ASSOC(priv,
"STA id %u addr %pM already present in uCode "
"(according to driver)\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
} else {
priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE;
IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
}
return 0;
}
| 169,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
dec->numtiles = dec->numhtiles * dec->numvtiles;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
Commit Message: Fixed another integer overflow problem.
CWE ID: CWE-190 | static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
| 168,742 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_compr_allocate_buffer(struct snd_compr_stream *stream,
struct snd_compr_params *params)
{
unsigned int buffer_size;
void *buffer;
buffer_size = params->buffer.fragment_size * params->buffer.fragments;
if (stream->ops->copy) {
buffer = NULL;
/* if copy is defined the driver will be required to copy
* the data from core
*/
} else {
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
}
stream->runtime->fragment_size = params->buffer.fragment_size;
stream->runtime->fragments = params->buffer.fragments;
stream->runtime->buffer = buffer;
stream->runtime->buffer_size = buffer_size;
return 0;
}
Commit Message: ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()
These are 32 bit values that come from the user, we need to check for
integer overflows or we could end up allocating a smaller buffer than
expected.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | static int snd_compr_allocate_buffer(struct snd_compr_stream *stream,
struct snd_compr_params *params)
{
unsigned int buffer_size;
void *buffer;
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size)
return -EINVAL;
buffer_size = params->buffer.fragment_size * params->buffer.fragments;
if (stream->ops->copy) {
buffer = NULL;
/* if copy is defined the driver will be required to copy
* the data from core
*/
} else {
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
}
stream->runtime->fragment_size = params->buffer.fragment_size;
stream->runtime->fragments = params->buffer.fragments;
stream->runtime->buffer = buffer;
stream->runtime->buffer_size = buffer_size;
return 0;
}
| 167,610 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
Stream_Write_UINT32(s, header->MessageType);
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125 | void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
Stream_Write_UINT32(s, header->MessageType);
}
| 169,281 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val)
{
int i;
int c;
ulonglong v;
v = 0;
for (i = n; i > 0; --i) {
if ((c = jas_stream_getc(in)) == EOF)
return -1;
v = (v << 8) | c;
}
*val = v;
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val)
static int jas_iccgetuint(jas_stream_t *in, int n, jas_ulonglong *val)
{
int i;
int c;
jas_ulonglong v;
v = 0;
for (i = n; i > 0; --i) {
if ((c = jas_stream_getc(in)) == EOF)
return -1;
v = (v << 8) | c;
}
*val = v;
return 0;
}
| 168,684 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), GetExtension()->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
GetExtension()->id(),
GetExtension()->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
const Extension* extension = GetExtension();
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(::switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), extension->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
::switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
extension->id(),
extension->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
| 171,654 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DiceTurnSyncOnHelper::AbortAndDelete() {
if (signin_aborted_mode_ == SigninAbortedMode::REMOVE_ACCOUNT) {
token_service_->RevokeCredentials(account_info_.account_id);
}
delete this;
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void DiceTurnSyncOnHelper::AbortAndDelete() {
if (signin_aborted_mode_ == SigninAbortedMode::REMOVE_ACCOUNT) {
token_service_->RevokeCredentials(
account_info_.account_id,
signin_metrics::SourceForRefreshTokenOperation::
kDiceTurnOnSyncHelper_Abort);
}
delete this;
}
| 172,574 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_generic_init)
{
char *key, *iv;
int key_len, iv_len;
zval *mcryptind;
unsigned char *key_s, *iv_s;
int max_key_size, key_size, iv_size;
php_mcrypt *pm;
int result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
max_key_size = mcrypt_enc_get_key_size(pm->td);
iv_size = mcrypt_enc_get_iv_size(pm->td);
if (key_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0");
}
key_s = emalloc(key_len);
memset(key_s, 0, key_len);
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
if (key_len > max_key_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
key_size = max_key_size;
} else {
key_size = key_len;
}
memcpy(key_s, key, key_len);
if (iv_len != iv_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
if (iv_len > iv_size) {
iv_len = iv_size;
}
}
memcpy(iv_s, iv, iv_len);
mcrypt_generic_deinit(pm->td);
result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
zend_list_delete(Z_LVAL_P(mcryptind));
switch (result) {
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect");
break;
case -4:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error");
break;
case -1:
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error");
break;
}
} else {
pm->init = 1;
}
RETVAL_LONG(result);
efree(iv_s);
efree(key_s);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_generic_init)
{
char *key, *iv;
int key_len, iv_len;
zval *mcryptind;
unsigned char *key_s, *iv_s;
int max_key_size, key_size, iv_size;
php_mcrypt *pm;
int result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
max_key_size = mcrypt_enc_get_key_size(pm->td);
iv_size = mcrypt_enc_get_iv_size(pm->td);
if (key_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0");
}
key_s = emalloc(key_len);
memset(key_s, 0, key_len);
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
if (key_len > max_key_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
key_size = max_key_size;
} else {
key_size = key_len;
}
memcpy(key_s, key, key_len);
if (iv_len != iv_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
if (iv_len > iv_size) {
iv_len = iv_size;
}
}
memcpy(iv_s, iv, iv_len);
mcrypt_generic_deinit(pm->td);
result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
zend_list_delete(Z_LVAL_P(mcryptind));
switch (result) {
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect");
break;
case -4:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error");
break;
case -1:
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error");
break;
}
} else {
pm->init = 1;
}
RETVAL_LONG(result);
efree(iv_s);
efree(key_s);
}
| 167,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseCompressionEntry(long long start, long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; // consume payload
assert(pos <= stop);
}
if (!valid)
return E_FILE_FORMAT_INVALID;
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long ContentEncoding::ParseCompressionEntry(long long start, long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (!valid)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
Commit Message:
CWE ID: CWE-772 | vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
| 164,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: print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
Commit Message: CVE-2017-12899/DECnet: Fix bounds checking.
If we're skipping over padding before the *real* flags, check whether
the real flags are in the captured data before fetching it. This fixes
a buffer over-read discovered by Kamil Frankowicz.
Note one place where we don't need to do bounds checking as it's already
been done.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
/* Our caller has already checked for mflags */
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
| 170,034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.