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 int cp2112_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
unsigned long flags;
int ret;
spin_lock_irqsave(&dev->lock, flags);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto fail;
}
buf[1] |= 1 << offset;
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto fail;
}
spin_unlock_irqrestore(&dev->lock, flags);
/*
* Set gpio value when output direction is already set,
* as specified in AN495, Rev. 0.2, cpt. 4.4
*/
cp2112_gpio_set(chip, offset, value);
return 0;
fail:
spin_unlock_irqrestore(&dev->lock, flags);
return ret < 0 ? ret : -EIO;
}
Commit Message: HID: cp2112: fix sleep-while-atomic
A recent commit fixing DMA-buffers on stack added a shared transfer
buffer protected by a spinlock. This is broken as the USB HID request
callbacks can sleep. Fix this up by replacing the spinlock with a mutex.
Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable")
Cc: stable <[email protected]> # 4.9
Signed-off-by: Johan Hovold <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-404 | static int cp2112_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto fail;
}
buf[1] |= 1 << offset;
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto fail;
}
mutex_unlock(&dev->lock);
/*
* Set gpio value when output direction is already set,
* as specified in AN495, Rev. 0.2, cpt. 4.4
*/
cp2112_gpio_set(chip, offset, value);
return 0;
fail:
mutex_unlock(&dev->lock);
return ret < 0 ? ret : -EIO;
}
| 168,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
int ret = -ENOMEM, i;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
if (npages > ARRAY_SIZE(pages))
return -ERANGE;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
/* Handle the case where the passed-in buffer is too short */
if (res.acl_flags & NFS4_ACL_TRUNC) {
/* Did the user only issue a request for the acl length? */
if (buf == NULL)
goto out_ok;
ret = -ERANGE;
goto out_free;
}
nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len);
if (buf)
_copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
out_ok:
ret = res.acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
return ret;
}
Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached
Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in
__nfs4_get_acl_uncached" accidently dropped the checking for too small
result buffer length.
If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount
supporting ACLs, the ACL has not been cached and the buffer suplied is
too short, we still copy the complete ACL, resulting in kernel and user
space memory corruption.
Signed-off-by: Sven Wegener <[email protected]>
Cc: [email protected]
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-119 | static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
int ret = -ENOMEM, i;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
if (npages > ARRAY_SIZE(pages))
return -ERANGE;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
/* Handle the case where the passed-in buffer is too short */
if (res.acl_flags & NFS4_ACL_TRUNC) {
/* Did the user only issue a request for the acl length? */
if (buf == NULL)
goto out_ok;
ret = -ERANGE;
goto out_free;
}
nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len);
if (buf) {
if (res.acl_len > buflen) {
ret = -ERANGE;
goto out_free;
}
_copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
}
out_ok:
ret = res.acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
return ret;
}
| 165,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: bool WebRequestPermissions::HideRequest(
const extensions::InfoMap* extension_info_map,
const extensions::WebRequestInfo& request) {
if (request.is_web_view)
return false;
if (request.is_pac_request)
return true;
bool is_request_from_browser = request.render_process_id == -1;
bool is_request_from_webui_renderer = false;
if (!is_request_from_browser) {
if (request.is_web_view)
return false;
if (extension_info_map &&
extension_info_map->process_map().Contains(extensions::kWebStoreAppId,
request.render_process_id)) {
return true;
}
is_request_from_webui_renderer =
content::ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings(
request.render_process_id);
}
return IsSensitiveURL(request.url, is_request_from_browser ||
is_request_from_webui_renderer) ||
!HasWebRequestScheme(request.url);
}
Commit Message: Hide DevTools frontend from webRequest API
Prevent extensions from observing requests for remote DevTools frontends
and add regression tests.
And update ExtensionTestApi to support initializing the embedded test
server and port from SetUpCommandLine (before SetUpOnMainThread).
BUG=797497,797500
TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735
Reviewed-on: https://chromium-review.googlesource.com/844316
Commit-Queue: Rob Wu <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528187}
CWE ID: CWE-200 | bool WebRequestPermissions::HideRequest(
const extensions::InfoMap* extension_info_map,
const extensions::WebRequestInfo& request) {
if (request.is_web_view)
return false;
if (request.is_pac_request)
return true;
bool is_request_from_browser =
request.render_process_id == -1 &&
// Browser requests are often of the "other" resource type.
// Main frame requests are not unconditionally seen as a sensitive browser
// request, because a request can also be browser-driven if there is no
// process to associate the request with. E.g. navigations via the
// chrome.tabs.update extension API.
request.type != content::RESOURCE_TYPE_MAIN_FRAME;
bool is_request_from_webui_renderer = false;
if (!is_request_from_browser) {
if (request.is_web_view)
return false;
if (extension_info_map &&
extension_info_map->process_map().Contains(extensions::kWebStoreAppId,
request.render_process_id)) {
return true;
}
is_request_from_webui_renderer =
content::ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings(
request.render_process_id);
}
return IsSensitiveURL(request.url, is_request_from_browser ||
is_request_from_webui_renderer) ||
!HasWebRequestScheme(request.url);
}
| 172,672 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_default_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
UNUSED(bit_depth)
this->next = *that;
*that = this;
return 1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_default_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
UNUSED(bit_depth)
this->next = *that;
*that = this;
return 1;
}
| 173,620 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() {
return GetBooleanParam(
switches::kEnableContextualSearchNowOnTapBarIntegration,
&is_now_on_tap_bar_integration_enabled_cached_,
&is_now_on_tap_bar_integration_enabled_);
}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID: | bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() {
bool ContextualSearchFieldTrial::IsContextualCardsBarIntegrationEnabled() {
return GetBooleanParam(
switches::kEnableContextualSearchContextualCardsBarIntegration,
&is_contextual_cards_bar_integration_enabled_cached_,
&is_contextual_cards_bar_integration_enabled_);
}
| 171,644 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderWidgetHostViewGtk::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, true, 0);
}
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 RenderWidgetHostViewGtk::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, params.surface_handle, 0);
}
| 171,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const {
if (parent_widget_)
return parent_widget_->GetClientAreaBoundsInScreen();
return PopupViewCommon().GetWindowBounds(delegate_->container_view());
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const {
| 172,093 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gs_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct gs_usb *dev;
int rc = -ENOMEM;
unsigned int icount, i;
struct gs_host_config hconf = {
.byte_order = 0x0000beef,
};
struct gs_device_config dconf;
/* send host config */
rc = usb_control_msg(interface_to_usbdev(intf),
usb_sndctrlpipe(interface_to_usbdev(intf), 0),
GS_USB_BREQ_HOST_FORMAT,
USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
1,
intf->altsetting[0].desc.bInterfaceNumber,
&hconf,
sizeof(hconf),
1000);
if (rc < 0) {
dev_err(&intf->dev, "Couldn't send data format (err=%d)\n",
rc);
return rc;
}
/* read device config */
rc = usb_control_msg(interface_to_usbdev(intf),
usb_rcvctrlpipe(interface_to_usbdev(intf), 0),
GS_USB_BREQ_DEVICE_CONFIG,
USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
1,
intf->altsetting[0].desc.bInterfaceNumber,
&dconf,
sizeof(dconf),
1000);
if (rc < 0) {
dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n",
rc);
return rc;
}
icount = dconf.icount + 1;
dev_info(&intf->dev, "Configuring for %d interfaces\n", icount);
if (icount > GS_MAX_INTF) {
dev_err(&intf->dev,
"Driver cannot handle more that %d CAN interfaces\n",
GS_MAX_INTF);
return -EINVAL;
}
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
init_usb_anchor(&dev->rx_submitted);
atomic_set(&dev->active_channels, 0);
usb_set_intfdata(intf, dev);
dev->udev = interface_to_usbdev(intf);
for (i = 0; i < icount; i++) {
dev->canch[i] = gs_make_candev(i, intf, &dconf);
if (IS_ERR_OR_NULL(dev->canch[i])) {
/* save error code to return later */
rc = PTR_ERR(dev->canch[i]);
/* on failure destroy previously created candevs */
icount = i;
for (i = 0; i < icount; i++)
gs_destroy_candev(dev->canch[i]);
usb_kill_anchored_urbs(&dev->rx_submitted);
kfree(dev);
return rc;
}
dev->canch[i]->parent = dev;
}
return 0;
}
Commit Message: can: gs_usb: Don't use stack memory for USB transfers
Fixes: 05ca5270005c can: gs_usb: add ethtool set_phys_id callback to locate physical device
The gs_usb driver is performing USB transfers using buffers allocated on
the stack. This causes the driver to not function with vmapped stacks.
Instead, allocate memory for the transfer buffers.
Signed-off-by: Ethan Zonca <[email protected]>
Cc: linux-stable <[email protected]> # >= v4.8
Signed-off-by: Marc Kleine-Budde <[email protected]>
CWE ID: CWE-119 | static int gs_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct gs_usb *dev;
int rc = -ENOMEM;
unsigned int icount, i;
struct gs_host_config *hconf;
struct gs_device_config *dconf;
hconf = kmalloc(sizeof(*hconf), GFP_KERNEL);
if (!hconf)
return -ENOMEM;
hconf->byte_order = 0x0000beef;
/* send host config */
rc = usb_control_msg(interface_to_usbdev(intf),
usb_sndctrlpipe(interface_to_usbdev(intf), 0),
GS_USB_BREQ_HOST_FORMAT,
USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
1,
intf->altsetting[0].desc.bInterfaceNumber,
hconf,
sizeof(*hconf),
1000);
kfree(hconf);
if (rc < 0) {
dev_err(&intf->dev, "Couldn't send data format (err=%d)\n",
rc);
return rc;
}
dconf = kmalloc(sizeof(*dconf), GFP_KERNEL);
if (!dconf)
return -ENOMEM;
/* read device config */
rc = usb_control_msg(interface_to_usbdev(intf),
usb_rcvctrlpipe(interface_to_usbdev(intf), 0),
GS_USB_BREQ_DEVICE_CONFIG,
USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
1,
intf->altsetting[0].desc.bInterfaceNumber,
dconf,
sizeof(*dconf),
1000);
if (rc < 0) {
dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n",
rc);
kfree(dconf);
return rc;
}
icount = dconf->icount + 1;
dev_info(&intf->dev, "Configuring for %d interfaces\n", icount);
if (icount > GS_MAX_INTF) {
dev_err(&intf->dev,
"Driver cannot handle more that %d CAN interfaces\n",
GS_MAX_INTF);
kfree(dconf);
return -EINVAL;
}
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
kfree(dconf);
return -ENOMEM;
}
init_usb_anchor(&dev->rx_submitted);
atomic_set(&dev->active_channels, 0);
usb_set_intfdata(intf, dev);
dev->udev = interface_to_usbdev(intf);
for (i = 0; i < icount; i++) {
dev->canch[i] = gs_make_candev(i, intf, dconf);
if (IS_ERR_OR_NULL(dev->canch[i])) {
/* save error code to return later */
rc = PTR_ERR(dev->canch[i]);
/* on failure destroy previously created candevs */
icount = i;
for (i = 0; i < icount; i++)
gs_destroy_candev(dev->canch[i]);
usb_kill_anchored_urbs(&dev->rx_submitted);
kfree(dconf);
kfree(dev);
return rc;
}
dev->canch[i]->parent = dev;
}
kfree(dconf);
return 0;
}
| 168,220 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void enable_nmi_window(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
== HF_NMI_MASK)
return; /* IRET will cause a vm exit */
/*
* Something prevents NMI from been injected. Single step over possible
* problem (IRET or exception injection or interrupt shadow)
*/
svm->nmi_singlestep = true;
svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_bp_intercept(vcpu);
}
Commit Message: KVM: svm: unconditionally intercept #DB
This is needed to avoid the possibility that the guest triggers
an infinite stream of #DB exceptions (CVE-2015-8104).
VMX is not affected: because it does not save DR6 in the VMCS,
it already intercepts #DB unconditionally.
Reported-by: Jan Beulich <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399 | static void enable_nmi_window(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
== HF_NMI_MASK)
return; /* IRET will cause a vm exit */
/*
* Something prevents NMI from been injected. Single step over possible
* problem (IRET or exception injection or interrupt shadow)
*/
svm->nmi_singlestep = true;
svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
}
| 166,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunFwdTxfm(const int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
| 174,550 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppControllerImpl::BindRequest(mojom::AppControllerRequest request) {
bindings_.AddBinding(this, std::move(request));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void AppControllerImpl::BindRequest(mojom::AppControllerRequest request) {
void AppControllerService::BindRequest(mojom::AppControllerRequest request) {
bindings_.AddBinding(this, std::move(request));
}
| 172,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
Commit Message: Prevent invalid columnPos() call in formUpdateBuffer()
Bug-Debian: https://github.com/tats/w3m/issues/89
CWE ID: CWE-476 | formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (l == NULL)
break;
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
| 169,347 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<size_t> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | bool dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<unsigned> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
| 172,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: void VRDisplay::OnBlur() {
display_blurred_ = true;
vr_v_sync_provider_.reset();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayblur, true, false, this, ""));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::OnBlur() {
DVLOG(1) << __FUNCTION__;
display_blurred_ = true;
vr_v_sync_provider_.reset();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayblur, true, false, this, ""));
}
| 171,994 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext2_xattr_delete_inode(struct inode *inode)
{
struct buffer_head *bh = NULL;
struct mb_cache_entry *ce;
down_write(&EXT2_I(inode)->xattr_sem);
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: block %d read error", inode->i_ino,
EXT2_I(inode)->i_file_acl);
goto cleanup;
}
ea_bdebug(bh, "b_count=%d", atomic_read(&(bh->b_count)));
if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
HDR(bh)->h_blocks != cpu_to_le32(1)) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
goto cleanup;
}
ce = mb_cache_entry_get(ext2_xattr_cache, bh->b_bdev, bh->b_blocknr);
lock_buffer(bh);
if (HDR(bh)->h_refcount == cpu_to_le32(1)) {
if (ce)
mb_cache_entry_free(ce);
ext2_free_blocks(inode, EXT2_I(inode)->i_file_acl, 1);
get_bh(bh);
bforget(bh);
unlock_buffer(bh);
} else {
le32_add_cpu(&HDR(bh)->h_refcount, -1);
if (ce)
mb_cache_entry_release(ce);
ea_bdebug(bh, "refcount now=%d",
le32_to_cpu(HDR(bh)->h_refcount));
unlock_buffer(bh);
mark_buffer_dirty(bh);
if (IS_SYNC(inode))
sync_dirty_buffer(bh);
dquot_free_block_nodirty(inode, 1);
}
EXT2_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
up_write(&EXT2_I(inode)->xattr_sem);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext2_xattr_delete_inode(struct inode *inode)
{
struct buffer_head *bh = NULL;
down_write(&EXT2_I(inode)->xattr_sem);
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: block %d read error", inode->i_ino,
EXT2_I(inode)->i_file_acl);
goto cleanup;
}
ea_bdebug(bh, "b_count=%d", atomic_read(&(bh->b_count)));
if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
HDR(bh)->h_blocks != cpu_to_le32(1)) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
goto cleanup;
}
lock_buffer(bh);
if (HDR(bh)->h_refcount == cpu_to_le32(1)) {
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
/*
* This must happen under buffer lock for ext2_xattr_set2() to
* reliably detect freed block
*/
mb2_cache_entry_delete_block(EXT2_SB(inode->i_sb)->s_mb_cache,
hash, bh->b_blocknr);
ext2_free_blocks(inode, EXT2_I(inode)->i_file_acl, 1);
get_bh(bh);
bforget(bh);
unlock_buffer(bh);
} else {
le32_add_cpu(&HDR(bh)->h_refcount, -1);
ea_bdebug(bh, "refcount now=%d",
le32_to_cpu(HDR(bh)->h_refcount));
unlock_buffer(bh);
mark_buffer_dirty(bh);
if (IS_SYNC(inode))
sync_dirty_buffer(bh);
dquot_free_block_nodirty(inode, 1);
}
EXT2_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
up_write(&EXT2_I(inode)->xattr_sem);
}
| 169,979 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 do_mq_notify(mqd_t mqdes, const struct sigevent *notification)
{
int ret;
struct fd f;
struct sock *sock;
struct inode *inode;
struct mqueue_inode_info *info;
struct sk_buff *nc;
audit_mq_notify(mqdes, notification);
nc = NULL;
sock = NULL;
if (notification != NULL) {
if (unlikely(notification->sigev_notify != SIGEV_NONE &&
notification->sigev_notify != SIGEV_SIGNAL &&
notification->sigev_notify != SIGEV_THREAD))
return -EINVAL;
if (notification->sigev_notify == SIGEV_SIGNAL &&
!valid_signal(notification->sigev_signo)) {
return -EINVAL;
}
if (notification->sigev_notify == SIGEV_THREAD) {
long timeo;
/* create the notify skb */
nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);
if (!nc) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(nc->data,
notification->sigev_value.sival_ptr,
NOTIFY_COOKIE_LEN)) {
ret = -EFAULT;
goto out;
}
/* TODO: add a header? */
skb_put(nc, NOTIFY_COOKIE_LEN);
/* and attach it to the socket */
retry:
f = fdget(notification->sigev_signo);
if (!f.file) {
ret = -EBADF;
goto out;
}
sock = netlink_getsockbyfilp(f.file);
fdput(f);
if (IS_ERR(sock)) {
ret = PTR_ERR(sock);
sock = NULL;
goto out;
}
timeo = MAX_SCHEDULE_TIMEOUT;
ret = netlink_attachskb(sock, nc, &timeo, NULL);
if (ret == 1)
goto retry;
if (ret) {
sock = NULL;
nc = NULL;
goto out;
}
}
}
f = fdget(mqdes);
if (!f.file) {
ret = -EBADF;
goto out;
}
inode = file_inode(f.file);
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
ret = 0;
spin_lock(&info->lock);
if (notification == NULL) {
if (info->notify_owner == task_tgid(current)) {
remove_notification(info);
inode->i_atime = inode->i_ctime = current_time(inode);
}
} else if (info->notify_owner != NULL) {
ret = -EBUSY;
} else {
switch (notification->sigev_notify) {
case SIGEV_NONE:
info->notify.sigev_notify = SIGEV_NONE;
break;
case SIGEV_THREAD:
info->notify_sock = sock;
info->notify_cookie = nc;
sock = NULL;
nc = NULL;
info->notify.sigev_notify = SIGEV_THREAD;
break;
case SIGEV_SIGNAL:
info->notify.sigev_signo = notification->sigev_signo;
info->notify.sigev_value = notification->sigev_value;
info->notify.sigev_notify = SIGEV_SIGNAL;
break;
}
info->notify_owner = get_pid(task_tgid(current));
info->notify_user_ns = get_user_ns(current_user_ns());
inode->i_atime = inode->i_ctime = current_time(inode);
}
spin_unlock(&info->lock);
out_fput:
fdput(f);
out:
if (sock)
netlink_detachskb(sock, nc);
else if (nc)
dev_kfree_skb(nc);
return ret;
}
Commit Message: mqueue: fix a use-after-free in sys_mq_notify()
The retry logic for netlink_attachskb() inside sys_mq_notify()
is nasty and vulnerable:
1) The sock refcnt is already released when retry is needed
2) The fd is controllable by user-space because we already
release the file refcnt
so we when retry but the fd has been just closed by user-space
during this small window, we end up calling netlink_detachskb()
on the error path which releases the sock again, later when
the user-space closes this socket a use-after-free could be
triggered.
Setting 'sock' to NULL here should be sufficient to fix it.
Reported-by: GeneBlue <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification)
{
int ret;
struct fd f;
struct sock *sock;
struct inode *inode;
struct mqueue_inode_info *info;
struct sk_buff *nc;
audit_mq_notify(mqdes, notification);
nc = NULL;
sock = NULL;
if (notification != NULL) {
if (unlikely(notification->sigev_notify != SIGEV_NONE &&
notification->sigev_notify != SIGEV_SIGNAL &&
notification->sigev_notify != SIGEV_THREAD))
return -EINVAL;
if (notification->sigev_notify == SIGEV_SIGNAL &&
!valid_signal(notification->sigev_signo)) {
return -EINVAL;
}
if (notification->sigev_notify == SIGEV_THREAD) {
long timeo;
/* create the notify skb */
nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);
if (!nc) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(nc->data,
notification->sigev_value.sival_ptr,
NOTIFY_COOKIE_LEN)) {
ret = -EFAULT;
goto out;
}
/* TODO: add a header? */
skb_put(nc, NOTIFY_COOKIE_LEN);
/* and attach it to the socket */
retry:
f = fdget(notification->sigev_signo);
if (!f.file) {
ret = -EBADF;
goto out;
}
sock = netlink_getsockbyfilp(f.file);
fdput(f);
if (IS_ERR(sock)) {
ret = PTR_ERR(sock);
sock = NULL;
goto out;
}
timeo = MAX_SCHEDULE_TIMEOUT;
ret = netlink_attachskb(sock, nc, &timeo, NULL);
if (ret == 1) {
sock = NULL;
goto retry;
}
if (ret) {
sock = NULL;
nc = NULL;
goto out;
}
}
}
f = fdget(mqdes);
if (!f.file) {
ret = -EBADF;
goto out;
}
inode = file_inode(f.file);
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
ret = 0;
spin_lock(&info->lock);
if (notification == NULL) {
if (info->notify_owner == task_tgid(current)) {
remove_notification(info);
inode->i_atime = inode->i_ctime = current_time(inode);
}
} else if (info->notify_owner != NULL) {
ret = -EBUSY;
} else {
switch (notification->sigev_notify) {
case SIGEV_NONE:
info->notify.sigev_notify = SIGEV_NONE;
break;
case SIGEV_THREAD:
info->notify_sock = sock;
info->notify_cookie = nc;
sock = NULL;
nc = NULL;
info->notify.sigev_notify = SIGEV_THREAD;
break;
case SIGEV_SIGNAL:
info->notify.sigev_signo = notification->sigev_signo;
info->notify.sigev_value = notification->sigev_value;
info->notify.sigev_notify = SIGEV_SIGNAL;
break;
}
info->notify_owner = get_pid(task_tgid(current));
info->notify_user_ns = get_user_ns(current_user_ns());
inode->i_atime = inode->i_ctime = current_time(inode);
}
spin_unlock(&info->lock);
out_fput:
fdput(f);
out:
if (sock)
netlink_detachskb(sock, nc);
else if (nc)
dev_kfree_skb(nc);
return ret;
}
| 168,047 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (!n2size) {
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
Commit Message: Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)
Thanks to Mick Ayzenberg <[email protected]> for finding this!
CWE ID: CWE-119 | bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (n2size < 1)
{
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
| 169,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sanity_check_raw_super(struct f2fs_sb_info *sbi,
struct buffer_head *bh)
{
struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
(bh->b_data + F2FS_SUPER_OFFSET);
struct super_block *sb = sbi->sb;
unsigned int blocksize;
if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {
f2fs_msg(sb, KERN_INFO,
"Magic Mismatch, valid(0x%x) - read(0x%x)",
F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
return 1;
}
/* Currently, support only 4KB page cache size */
if (F2FS_BLKSIZE != PAGE_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid page_cache_size (%lu), supports only 4KB\n",
PAGE_SIZE);
return 1;
}
/* Currently, support only 4KB block size */
blocksize = 1 << le32_to_cpu(raw_super->log_blocksize);
if (blocksize != F2FS_BLKSIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid blocksize (%u), supports only 4KB\n",
blocksize);
return 1;
}
/* check log blocks per segment */
if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
f2fs_msg(sb, KERN_INFO,
"Invalid log blocks per segment (%u)\n",
le32_to_cpu(raw_super->log_blocks_per_seg));
return 1;
}
/* Currently, support 512/1024/2048/4096 bytes sector size */
if (le32_to_cpu(raw_super->log_sectorsize) >
F2FS_MAX_LOG_SECTOR_SIZE ||
le32_to_cpu(raw_super->log_sectorsize) <
F2FS_MIN_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)",
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
if (le32_to_cpu(raw_super->log_sectors_per_block) +
le32_to_cpu(raw_super->log_sectorsize) !=
F2FS_MAX_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid log sectors per block(%u) log sectorsize(%u)",
le32_to_cpu(raw_super->log_sectors_per_block),
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
/* check reserved ino info */
if (le32_to_cpu(raw_super->node_ino) != 1 ||
le32_to_cpu(raw_super->meta_ino) != 2 ||
le32_to_cpu(raw_super->root_ino) != 3) {
f2fs_msg(sb, KERN_INFO,
"Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
le32_to_cpu(raw_super->node_ino),
le32_to_cpu(raw_super->meta_ino),
le32_to_cpu(raw_super->root_ino));
return 1;
}
/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
if (sanity_check_area_boundary(sbi, bh))
return 1;
return 0;
}
Commit Message: f2fs: sanity check segment count
F2FS uses 4 bytes to represent block address. As a result, supported
size of disk is 16 TB and it equals to 16 * 1024 * 1024 / 2 segments.
Signed-off-by: Jin Qian <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: | static int sanity_check_raw_super(struct f2fs_sb_info *sbi,
struct buffer_head *bh)
{
struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
(bh->b_data + F2FS_SUPER_OFFSET);
struct super_block *sb = sbi->sb;
unsigned int blocksize;
if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {
f2fs_msg(sb, KERN_INFO,
"Magic Mismatch, valid(0x%x) - read(0x%x)",
F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
return 1;
}
/* Currently, support only 4KB page cache size */
if (F2FS_BLKSIZE != PAGE_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid page_cache_size (%lu), supports only 4KB\n",
PAGE_SIZE);
return 1;
}
/* Currently, support only 4KB block size */
blocksize = 1 << le32_to_cpu(raw_super->log_blocksize);
if (blocksize != F2FS_BLKSIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid blocksize (%u), supports only 4KB\n",
blocksize);
return 1;
}
/* check log blocks per segment */
if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
f2fs_msg(sb, KERN_INFO,
"Invalid log blocks per segment (%u)\n",
le32_to_cpu(raw_super->log_blocks_per_seg));
return 1;
}
/* Currently, support 512/1024/2048/4096 bytes sector size */
if (le32_to_cpu(raw_super->log_sectorsize) >
F2FS_MAX_LOG_SECTOR_SIZE ||
le32_to_cpu(raw_super->log_sectorsize) <
F2FS_MIN_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)",
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
if (le32_to_cpu(raw_super->log_sectors_per_block) +
le32_to_cpu(raw_super->log_sectorsize) !=
F2FS_MAX_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid log sectors per block(%u) log sectorsize(%u)",
le32_to_cpu(raw_super->log_sectors_per_block),
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
/* check reserved ino info */
if (le32_to_cpu(raw_super->node_ino) != 1 ||
le32_to_cpu(raw_super->meta_ino) != 2 ||
le32_to_cpu(raw_super->root_ino) != 3) {
f2fs_msg(sb, KERN_INFO,
"Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
le32_to_cpu(raw_super->node_ino),
le32_to_cpu(raw_super->meta_ino),
le32_to_cpu(raw_super->root_ino));
return 1;
}
if (le32_to_cpu(raw_super->segment_count) > F2FS_MAX_SEGMENT) {
f2fs_msg(sb, KERN_INFO,
"Invalid segment count (%u)",
le32_to_cpu(raw_super->segment_count));
return 1;
}
/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
if (sanity_check_area_boundary(sbi, bh))
return 1;
return 0;
}
| 168,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
v8::Local<v8::String> module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Object> global(context()->v8_context()->Global());
v8::Local<v8::Value> modules_value;
if (!GetPrivate(global, kModulesField, &modules_value) ||
modules_value->IsUndefined()) {
Warn(GetIsolate(), "Extension view no longer exists");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value));
v8::Local<v8::Value> exports;
if (!GetProperty(v8_context, modules, module_name, &exports) ||
!exports->IsUndefined())
return handle_scope.Escape(exports);
exports = LoadModule(*v8::String::Utf8Value(module_name));
SetProperty(v8_context, modules, module_name, exports);
return handle_scope.Escape(exports);
}
Commit Message: [Extensions] Harden against bindings interception
There's more we can do but this is a start.
BUG=590275
BUG=590118
Review URL: https://codereview.chromium.org/1748943002
Cr-Commit-Position: refs/heads/master@{#378621}
CWE ID: CWE-284 | v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
v8::Local<v8::String> module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Object> global(context()->v8_context()->Global());
v8::Local<v8::Value> modules_value;
if (!GetPrivate(global, kModulesField, &modules_value) ||
modules_value->IsUndefined()) {
Warn(GetIsolate(), "Extension view no longer exists");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value));
v8::Local<v8::Value> exports;
if (!GetPrivateProperty(v8_context, modules, module_name, &exports) ||
!exports->IsUndefined())
return handle_scope.Escape(exports);
exports = LoadModule(*v8::String::Utf8Value(module_name));
SetPrivateProperty(v8_context, modules, module_name, exports);
return handle_scope.Escape(exports);
}
| 173,268 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __init xfrm6_tunnel_init(void)
{
int rv;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto err;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto unreg;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto dereg6;
rv = xfrm6_tunnel_spi_init();
if (rv < 0)
goto dereg46;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto deregspi;
return 0;
deregspi:
xfrm6_tunnel_spi_fini();
dereg46:
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
dereg6:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
unreg:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
err:
return rv;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int __init xfrm6_tunnel_init(void)
{
int rv;
xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi",
sizeof(struct xfrm6_tunnel_spi),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!xfrm6_tunnel_spi_kmem)
return -ENOMEM;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto out_pernet;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto out_type;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto out_xfrm6;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto out_xfrm46;
return 0;
out_xfrm46:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
out_xfrm6:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
out_type:
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
out_pernet:
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
return rv;
}
| 165,880 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaStreamDispatcherHost::DoOpenDevice(
int32_t page_request_id,
const std::string& device_id,
MediaStreamType type,
OpenDeviceCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(false /* success */, std::string(),
MediaStreamDevice());
return;
}
media_stream_manager_->OpenDevice(
render_process_id_, render_frame_id_, page_request_id, device_id, type,
std::move(salt_and_origin), std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamDispatcherHost::DoOpenDevice(
int32_t page_request_id,
const std::string& device_id,
MediaStreamType type,
OpenDeviceCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(false /* success */, std::string(),
MediaStreamDevice());
return;
}
media_stream_manager_->OpenDevice(
render_process_id_, render_frame_id_, page_request_id, requester_id_,
device_id, type, std::move(salt_and_origin), std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()));
}
| 173,095 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DevToolsUI::DevToolsUI(content::WebUI* web_ui)
: WebUIController(web_ui),
bindings_(web_ui->GetWebContents()) {
web_ui->SetBindings(0);
Profile* profile = Profile::FromWebUI(web_ui);
content::URLDataSource::Add(
profile,
new DevToolsDataSource(profile->GetRequestContext()));
}
Commit Message: [DevTools] Move sanitize url to devtools_ui.cc.
Compatibility script is not reliable enough.
BUG=653134
Review-Url: https://codereview.chromium.org/2403633002
Cr-Commit-Position: refs/heads/master@{#425814}
CWE ID: CWE-200 | DevToolsUI::DevToolsUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
web_ui->SetBindings(0);
Profile* profile = Profile::FromWebUI(web_ui);
content::URLDataSource::Add(
profile,
new DevToolsDataSource(profile->GetRequestContext()));
GURL url = web_ui->GetWebContents()->GetVisibleURL();
if (url.spec() == SanitizeFrontendURL(url).spec())
bindings_.reset(new DevToolsUIBindings(web_ui->GetWebContents()));
}
| 172,510 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jas_memdump(FILE *out, void *data, size_t len)
{
size_t i;
size_t j;
uchar *dp;
dp = data;
for (i = 0; i < len; i += 16) {
fprintf(out, "%04zx:", i);
for (j = 0; j < 16; ++j) {
if (i + j < len) {
fprintf(out, " %02x", dp[i + j]);
}
}
fprintf(out, "\n");
}
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 | int jas_memdump(FILE *out, void *data, size_t len)
{
size_t i;
size_t j;
jas_uchar *dp;
dp = data;
for (i = 0; i < len; i += 16) {
fprintf(out, "%04zx:", i);
for (j = 0; j < 16; ++j) {
if (i + j < len) {
fprintf(out, " %02x", dp[i + j]);
}
}
fprintf(out, "\n");
}
return 0;
}
| 168,682 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
Commit Message: Fix #10091 - crash in AVR analysis
CWE ID: CWE-125 | INST_HANDLER (sts) { // STS k, Rr
if (len < 4) {
return;
}
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
| 169,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftVorbis::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioVorbis:
{
OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
vorbisParams->nBitRate = 0;
vorbisParams->nMinBitRate = 0;
vorbisParams->nMaxBitRate = 0;
vorbisParams->nAudioBandWidth = 0;
vorbisParams->nQuality = 3;
vorbisParams->bManaged = OMX_FALSE;
vorbisParams->bDownmix = OMX_FALSE;
if (!isConfigured()) {
vorbisParams->nChannels = 1;
vorbisParams->nSampleRate = 44100;
} else {
vorbisParams->nChannels = mVi->channels;
vorbisParams->nSampleRate = mVi->rate;
vorbisParams->nBitRate = mVi->bitrate_nominal;
vorbisParams->nMinBitRate = mVi->bitrate_lower;
vorbisParams->nMaxBitRate = mVi->bitrate_upper;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mVi->channels;
pcmParams->nSamplingRate = mVi->rate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftVorbis::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioVorbis:
{
OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (!isValidOMXParam(vorbisParams)) {
return OMX_ErrorBadParameter;
}
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
vorbisParams->nBitRate = 0;
vorbisParams->nMinBitRate = 0;
vorbisParams->nMaxBitRate = 0;
vorbisParams->nAudioBandWidth = 0;
vorbisParams->nQuality = 3;
vorbisParams->bManaged = OMX_FALSE;
vorbisParams->bDownmix = OMX_FALSE;
if (!isConfigured()) {
vorbisParams->nChannels = 1;
vorbisParams->nSampleRate = 44100;
} else {
vorbisParams->nChannels = mVi->channels;
vorbisParams->nSampleRate = mVi->rate;
vorbisParams->nBitRate = mVi->bitrate_nominal;
vorbisParams->nMinBitRate = mVi->bitrate_lower;
vorbisParams->nMaxBitRate = mVi->bitrate_upper;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mVi->channels;
pcmParams->nSamplingRate = mVi->rate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,220 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ColorChooserDialog::DidCloseDialog(bool chose_color,
SkColor color,
RunState run_state) {
if (!listener_)
return;
EndRun(run_state);
CopyCustomColors(custom_colors_, g_custom_colors);
if (chose_color)
listener_->OnColorChosen(color);
listener_->OnColorChooserDialogClosed();
}
Commit Message: ColorChooserWin::End should act like the dialog has closed
This is only a problem on Windows.
When the page closes itself while the color chooser dialog is open,
ColorChooserDialog::DidCloseDialog was called after the listener has been destroyed.
ColorChooserWin::End() will not actually close the color chooser dialog (because we can't) but act like it did so we can do the necessary cleanup.
BUG=279263
[email protected], [email protected]
Review URL: https://codereview.chromium.org/23785003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@220639 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ColorChooserDialog::DidCloseDialog(bool chose_color,
SkColor color,
RunState run_state) {
EndRun(run_state);
CopyCustomColors(custom_colors_, g_custom_colors);
if (listener_) {
if (chose_color)
listener_->OnColorChosen(color);
listener_->OnColorChooserDialogClosed();
}
}
| 171,187 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_write_GeneralString(struct asn1_data *data, const char *s)
{
asn1_push_tag(data, ASN1_GENERAL_STRING);
asn1_write_LDAPString(data, s);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399 | bool asn1_write_GeneralString(struct asn1_data *data, const char *s)
{
if (!asn1_push_tag(data, ASN1_GENERAL_STRING)) return false;
if (!asn1_write_LDAPString(data, s)) return false;
return asn1_pop_tag(data);
}
| 164,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DefragVlanQinQTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 1;
p1->vlan_id[1] = 1;
p2->vlan_id[1] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragVlanQinQTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 1;
p1->vlan_id[1] = 1;
p2->vlan_id[1] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
| 168,305 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn,
PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn,
PNG_CONST int interlace_typeIn,
PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn,
PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn,
PNG_CONST char *name,
PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In,
PNG_CONST int expand16In, PNG_CONST int do_backgroundIn,
PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
{
gamma_display d;
context(&pmIn->this, fault);
gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
palette_numberIn, interlace_typeIn, 0, 0, 0),
file_gammaIn, screen_gammaIn, sbitIn,
threshold_testIn, use_input_precisionIn, scale16In,
expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
Try
{
png_structp pp;
png_infop pi;
gama_modification gama_mod;
srgb_modification srgb_mod;
sbit_modification sbit_mod;
/* For the moment don't use the png_modifier support here. */
d.pm->encoding_counter = 0;
modifier_set_encoding(d.pm); /* Just resets everything */
d.pm->current_gamma = d.file_gamma;
/* Make an appropriate modifier to set the PNG file gamma to the
* given gamma value and the sBIT chunk to the given precision.
*/
d.pm->modifications = NULL;
gama_modification_init(&gama_mod, d.pm, d.file_gamma);
srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
if (d.sbit > 0)
sbit_modification_init(&sbit_mod, d.pm, d.sbit);
modification_reset(d.pm->modifications);
/* Get a png_struct for writing the image. */
pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
standard_palette_init(&d.this);
/* Introduce the correct read function. */
if (d.pm->this.progressive)
{
/* Share the row function with the standard implementation. */
png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
gamma_end);
/* Now feed data into the reader until we reach the end: */
modifier_progressive_read(d.pm, pp, pi);
}
else
{
/* modifier_read expects a png_modifier* */
png_set_read_fn(pp, d.pm, modifier_read);
/* Check the header values: */
png_read_info(pp, pi);
/* Process the 'info' requirements. Only one image is generated */
gamma_info_imp(&d, pp, pi);
sequential_row(&d.this, pp, pi, -1, 0);
if (!d.this.speed)
gamma_image_validate(&d, pp, pi);
else
d.this.ps->validated = 1;
}
modifier_reset(d.pm);
if (d.pm->log && !d.threshold_test && !d.this.speed)
fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
d.this.bit_depth, colour_types[d.this.colour_type], name,
d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
/* Log the summary values too. */
if (d.this.colour_type == 0 || d.this.colour_type == 4)
{
switch (d.this.bit_depth)
{
case 1:
break;
case 2:
if (d.maxerrout > d.pm->error_gray_2)
d.pm->error_gray_2 = d.maxerrout;
break;
case 4:
if (d.maxerrout > d.pm->error_gray_4)
d.pm->error_gray_4 = d.maxerrout;
break;
case 8:
if (d.maxerrout > d.pm->error_gray_8)
d.pm->error_gray_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_gray_16)
d.pm->error_gray_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 1)");
}
}
else if (d.this.colour_type == 2 || d.this.colour_type == 6)
{
switch (d.this.bit_depth)
{
case 8:
if (d.maxerrout > d.pm->error_color_8)
d.pm->error_color_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_color_16)
d.pm->error_color_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 2)");
}
}
else if (d.this.colour_type == 3)
{
if (d.maxerrout > d.pm->error_indexed)
d.pm->error_indexed = d.maxerrout;
}
}
Catch(fault)
modifier_reset(voidcast(png_modifier*,(void*)fault));
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn,
gamma_test(png_modifier *pmIn, const png_byte colour_typeIn,
const png_byte bit_depthIn, const int palette_numberIn,
const int interlace_typeIn,
const double file_gammaIn, const double screen_gammaIn,
const png_byte sbitIn, const int threshold_testIn,
const char *name,
const int use_input_precisionIn, const int scale16In,
const int expand16In, const int do_backgroundIn,
const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
{
gamma_display d;
context(&pmIn->this, fault);
gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
palette_numberIn, interlace_typeIn, 0, 0, 0),
file_gammaIn, screen_gammaIn, sbitIn,
threshold_testIn, use_input_precisionIn, scale16In,
expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
Try
{
png_structp pp;
png_infop pi;
gama_modification gama_mod;
srgb_modification srgb_mod;
sbit_modification sbit_mod;
/* For the moment don't use the png_modifier support here. */
d.pm->encoding_counter = 0;
modifier_set_encoding(d.pm); /* Just resets everything */
d.pm->current_gamma = d.file_gamma;
/* Make an appropriate modifier to set the PNG file gamma to the
* given gamma value and the sBIT chunk to the given precision.
*/
d.pm->modifications = NULL;
gama_modification_init(&gama_mod, d.pm, d.file_gamma);
srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
if (d.sbit > 0)
sbit_modification_init(&sbit_mod, d.pm, d.sbit);
modification_reset(d.pm->modifications);
/* Get a png_struct for reading the image. */
pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
standard_palette_init(&d.this);
/* Introduce the correct read function. */
if (d.pm->this.progressive)
{
/* Share the row function with the standard implementation. */
png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
gamma_end);
/* Now feed data into the reader until we reach the end: */
modifier_progressive_read(d.pm, pp, pi);
}
else
{
/* modifier_read expects a png_modifier* */
png_set_read_fn(pp, d.pm, modifier_read);
/* Check the header values: */
png_read_info(pp, pi);
/* Process the 'info' requirements. Only one image is generated */
gamma_info_imp(&d, pp, pi);
sequential_row(&d.this, pp, pi, -1, 0);
if (!d.this.speed)
gamma_image_validate(&d, pp, pi);
else
d.this.ps->validated = 1;
}
modifier_reset(d.pm);
if (d.pm->log && !d.threshold_test && !d.this.speed)
fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
d.this.bit_depth, colour_types[d.this.colour_type], name,
d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
/* Log the summary values too. */
if (d.this.colour_type == 0 || d.this.colour_type == 4)
{
switch (d.this.bit_depth)
{
case 1:
break;
case 2:
if (d.maxerrout > d.pm->error_gray_2)
d.pm->error_gray_2 = d.maxerrout;
break;
case 4:
if (d.maxerrout > d.pm->error_gray_4)
d.pm->error_gray_4 = d.maxerrout;
break;
case 8:
if (d.maxerrout > d.pm->error_gray_8)
d.pm->error_gray_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_gray_16)
d.pm->error_gray_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 1)");
}
}
else if (d.this.colour_type == 2 || d.this.colour_type == 6)
{
switch (d.this.bit_depth)
{
case 8:
if (d.maxerrout > d.pm->error_color_8)
d.pm->error_color_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_color_16)
d.pm->error_color_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 2)");
}
}
else if (d.this.colour_type == 3)
{
if (d.maxerrout > d.pm->error_indexed)
d.pm->error_indexed = d.maxerrout;
}
}
Catch(fault)
modifier_reset(voidcast(png_modifier*,(void*)fault));
}
| 173,614 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_stop_timecode);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const
| 174,357 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 pnm_validate(jas_stream_t *in)
{
uchar buf[2];
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, buf, 2)) < 0) {
return -1;
}
/* Put these characters back to the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < 2) {
return -1;
}
/* Is this the correct signature for a PNM file? */
if (buf[0] == 'P' && isdigit(buf[1])) {
return 0;
}
return -1;
}
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 | int pnm_validate(jas_stream_t *in)
{
jas_uchar buf[2];
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, buf, 2)) < 0) {
return -1;
}
/* Put these characters back to the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < 2) {
return -1;
}
/* Is this the correct signature for a PNM file? */
if (buf[0] == 'P' && isdigit(buf[1])) {
return 0;
}
return -1;
}
| 168,728 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ManifestManager::FetchManifest() {
manifest_url_ = render_frame()->GetWebFrame()->GetDocument().ManifestURL();
if (manifest_url_.is_empty()) {
ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_EMPTY_URL);
ResolveCallbacks(ResolveStateFailure);
return;
}
fetcher_.reset(new ManifestFetcher(manifest_url_));
fetcher_->Start(
render_frame()->GetWebFrame(),
render_frame()->GetWebFrame()->GetDocument().ManifestUseCredentials(),
base::Bind(&ManifestManager::OnManifestFetchComplete,
base::Unretained(this),
render_frame()->GetWebFrame()->GetDocument().Url()));
}
Commit Message: Fail the web app manifest fetch if the document is sandboxed.
This ensures that sandboxed pages are regarded as non-PWAs, and that
other features in the browser process which trust the web manifest do
not receive the manifest at all if the document itself cannot access the
manifest.
BUG=771709
Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4
Reviewed-on: https://chromium-review.googlesource.com/866529
Commit-Queue: Dominick Ng <[email protected]>
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531121}
CWE ID: | void ManifestManager::FetchManifest() {
if (!CanFetchManifest(render_frame())) {
ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_FROM_UNIQUE_ORIGIN);
ResolveCallbacks(ResolveStateFailure);
return;
}
manifest_url_ = render_frame()->GetWebFrame()->GetDocument().ManifestURL();
if (manifest_url_.is_empty()) {
ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_EMPTY_URL);
ResolveCallbacks(ResolveStateFailure);
return;
}
fetcher_.reset(new ManifestFetcher(manifest_url_));
fetcher_->Start(
render_frame()->GetWebFrame(),
render_frame()->GetWebFrame()->GetDocument().ManifestUseCredentials(),
base::Bind(&ManifestManager::OnManifestFetchComplete,
base::Unretained(this),
render_frame()->GetWebFrame()->GetDocument().Url()));
}
| 172,921 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool_t auth_gssapi_unwrap_data(
OM_uint32 *major,
OM_uint32 *minor,
gss_ctx_id_t context,
uint32_t seq_num,
XDR *in_xdrs,
bool_t (*xdr_func)(),
caddr_t xdr_ptr)
{
gss_buffer_desc in_buf, out_buf;
XDR temp_xdrs;
uint32_t verf_seq_num;
int conf, qop;
unsigned int length;
PRINTF(("gssapi_unwrap_data: starting\n"));
*major = GSS_S_COMPLETE;
*minor = 0; /* assumption */
in_buf.value = NULL;
out_buf.value = NULL;
if (! xdr_bytes(in_xdrs, (char **) &in_buf.value,
&length, (unsigned int) -1)) {
PRINTF(("gssapi_unwrap_data: deserializing encrypted data failed\n"));
temp_xdrs.x_op = XDR_FREE;
(void)xdr_bytes(&temp_xdrs, (char **) &in_buf.value, &length,
(unsigned int) -1);
return FALSE;
}
in_buf.length = length;
*major = gss_unseal(minor, context, &in_buf, &out_buf, &conf,
&qop);
free(in_buf.value);
if (*major != GSS_S_COMPLETE)
return FALSE;
PRINTF(("gssapi_unwrap_data: %llu bytes data, %llu bytes sealed\n",
(unsigned long long)out_buf.length,
(unsigned long long)in_buf.length));
xdrmem_create(&temp_xdrs, out_buf.value, out_buf.length, XDR_DECODE);
/* deserialize the sequence number */
if (! xdr_u_int32(&temp_xdrs, &verf_seq_num)) {
PRINTF(("gssapi_unwrap_data: deserializing verf_seq_num failed\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
if (verf_seq_num != seq_num) {
PRINTF(("gssapi_unwrap_data: seq %d specified, read %d\n",
seq_num, verf_seq_num));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
PRINTF(("gssapi_unwrap_data: unwrap seq_num %d okay\n", verf_seq_num));
/* deserialize the arguments into xdr_ptr */
if (! (*xdr_func)(&temp_xdrs, xdr_ptr)) {
PRINTF(("gssapi_unwrap_data: deserializing arguments failed\n"));
gss_release_buffer(minor, &out_buf);
xdr_free(xdr_func, xdr_ptr);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
PRINTF(("gssapi_unwrap_data: succeeding\n\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return TRUE;
}
Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421]
[MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free
partial deserialization results upon failure to deserialize. This
responsibility belongs to the callers, svctcp_getargs() and
svcudp_getargs(); doing it in the unwrap function results in freeing
the results twice.
In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers
we are freeing, as other XDR functions such as xdr_bytes() and
xdr_string().
ticket: 8056 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | bool_t auth_gssapi_unwrap_data(
OM_uint32 *major,
OM_uint32 *minor,
gss_ctx_id_t context,
uint32_t seq_num,
XDR *in_xdrs,
bool_t (*xdr_func)(),
caddr_t xdr_ptr)
{
gss_buffer_desc in_buf, out_buf;
XDR temp_xdrs;
uint32_t verf_seq_num;
int conf, qop;
unsigned int length;
PRINTF(("gssapi_unwrap_data: starting\n"));
*major = GSS_S_COMPLETE;
*minor = 0; /* assumption */
in_buf.value = NULL;
out_buf.value = NULL;
if (! xdr_bytes(in_xdrs, (char **) &in_buf.value,
&length, (unsigned int) -1)) {
PRINTF(("gssapi_unwrap_data: deserializing encrypted data failed\n"));
temp_xdrs.x_op = XDR_FREE;
(void)xdr_bytes(&temp_xdrs, (char **) &in_buf.value, &length,
(unsigned int) -1);
return FALSE;
}
in_buf.length = length;
*major = gss_unseal(minor, context, &in_buf, &out_buf, &conf,
&qop);
free(in_buf.value);
if (*major != GSS_S_COMPLETE)
return FALSE;
PRINTF(("gssapi_unwrap_data: %llu bytes data, %llu bytes sealed\n",
(unsigned long long)out_buf.length,
(unsigned long long)in_buf.length));
xdrmem_create(&temp_xdrs, out_buf.value, out_buf.length, XDR_DECODE);
/* deserialize the sequence number */
if (! xdr_u_int32(&temp_xdrs, &verf_seq_num)) {
PRINTF(("gssapi_unwrap_data: deserializing verf_seq_num failed\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
if (verf_seq_num != seq_num) {
PRINTF(("gssapi_unwrap_data: seq %d specified, read %d\n",
seq_num, verf_seq_num));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
PRINTF(("gssapi_unwrap_data: unwrap seq_num %d okay\n", verf_seq_num));
/* deserialize the arguments into xdr_ptr */
if (! (*xdr_func)(&temp_xdrs, xdr_ptr)) {
PRINTF(("gssapi_unwrap_data: deserializing arguments failed\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
PRINTF(("gssapi_unwrap_data: succeeding\n\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return TRUE;
}
| 166,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: StyleResolver::StyleResolver(Document& document)
: m_document(document)
, m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
, m_styleResourceLoader(document.fetcher())
, m_styleResolverStatsSequence(0)
, m_accessCount(0)
{
Element* root = document.documentElement();
m_fontSelector->registerForInvalidationCallbacks(this);
CSSDefaultStyleSheets::initDefaultStyle(root);
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
m_styleTree.clear();
initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
fontSelector()->addFontFaceRule((*it)->fontFaceRule());
}
#endif
document.styleEngine()->appendActiveAuthorStyleSheets(this);
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | StyleResolver::StyleResolver(Document& document)
: m_document(document)
, m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
, m_styleResourceLoader(document.fetcher())
, m_styleResolverStatsSequence(0)
, m_accessCount(0)
{
m_fontSelector->registerForInvalidationCallbacks(this);
// FIXME: Why do this here instead of as part of resolving style on the root?
CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary();
// Construct document root element default style. This is needed
// This is here instead of constructor because when constructor is run,
// Document doesn't have documentElement.
// NOTE: This assumes that element that gets passed to the styleForElement call
// is always from the document that owns the StyleResolver.
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
Element* root = document.documentElement();
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
m_styleTree.clear();
initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
fontSelector()->addFontFaceRule((*it)->fontFaceRule());
}
#endif
document.styleEngine()->appendActiveAuthorStyleSheets(this);
}
| 171,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: int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file && file->size > 0 ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
| 169,082 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
{
int mxsize, cmd_size, k;
int input_size, blocking;
unsigned char opcode;
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
struct sg_header old_hdr;
sg_io_hdr_t *hp;
unsigned char cmnd[SG_MAX_CDB_SIZE];
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_write: count=%d\n", (int) count));
if (atomic_read(&sdp->detaching))
return -ENODEV;
if (!((filp->f_flags & O_NONBLOCK) ||
scsi_block_when_processing_errors(sdp->device)))
return -ENXIO;
if (!access_ok(VERIFY_READ, buf, count))
return -EFAULT; /* protects following copy_from_user()s + get_user()s */
if (count < SZ_SG_HEADER)
return -EIO;
if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))
return -EFAULT;
blocking = !(filp->f_flags & O_NONBLOCK);
if (old_hdr.reply_len < 0)
return sg_new_write(sfp, filp, buf, count,
blocking, 0, 0, NULL);
if (count < (SZ_SG_HEADER + 6))
return -EIO; /* The minimum scsi command length is 6 bytes. */
if (!(srp = sg_add_request(sfp))) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,
"sg_write: queue full\n"));
return -EDOM;
}
buf += SZ_SG_HEADER;
__get_user(opcode, buf);
if (sfp->next_cmd_len > 0) {
cmd_size = sfp->next_cmd_len;
sfp->next_cmd_len = 0; /* reset so only this write() effected */
} else {
cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */
if ((opcode >= 0xc0) && old_hdr.twelve_byte)
cmd_size = 12;
}
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
"sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size));
/* Determine buffer size. */
input_size = count - cmd_size;
mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;
mxsize -= SZ_SG_HEADER;
input_size -= SZ_SG_HEADER;
if (input_size < 0) {
sg_remove_request(sfp, srp);
return -EIO; /* User did not pass enough bytes for this command. */
}
hp = &srp->header;
hp->interface_id = '\0'; /* indicator of old interface tunnelled */
hp->cmd_len = (unsigned char) cmd_size;
hp->iovec_count = 0;
hp->mx_sb_len = 0;
if (input_size > 0)
hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?
SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
else
hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;
hp->dxfer_len = mxsize;
if ((hp->dxfer_direction == SG_DXFER_TO_DEV) ||
(hp->dxfer_direction == SG_DXFER_TO_FROM_DEV))
hp->dxferp = (char __user *)buf + cmd_size;
else
hp->dxferp = NULL;
hp->sbp = NULL;
hp->timeout = old_hdr.reply_len; /* structure abuse ... */
hp->flags = input_size; /* structure abuse ... */
hp->pack_id = old_hdr.pack_id;
hp->usr_ptr = NULL;
if (__copy_from_user(cmnd, buf, cmd_size))
return -EFAULT;
/*
* SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,
* but is is possible that the app intended SG_DXFER_TO_DEV, because there
* is a non-zero input_size, so emit a warning.
*/
if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {
static char cmd[TASK_COMM_LEN];
if (strcmp(current->comm, cmd)) {
printk_ratelimited(KERN_WARNING
"sg_write: data in/out %d/%d bytes "
"for SCSI command 0x%x-- guessing "
"data in;\n program %s not setting "
"count and/or reply_len properly\n",
old_hdr.reply_len - (int)SZ_SG_HEADER,
input_size, (unsigned int) cmnd[0],
current->comm);
strcpy(cmd, current->comm);
}
}
k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
return (k < 0) ? k : count;
}
Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS
Both damn things interpret userland pointers embedded into the payload;
worse, they are actually traversing those. Leaving aside the bad
API design, this is very much _not_ safe to call with KERNEL_DS.
Bail out early if that happens.
Cc: [email protected]
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-416 | sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
{
int mxsize, cmd_size, k;
int input_size, blocking;
unsigned char opcode;
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
struct sg_header old_hdr;
sg_io_hdr_t *hp;
unsigned char cmnd[SG_MAX_CDB_SIZE];
if (unlikely(segment_eq(get_fs(), KERNEL_DS)))
return -EINVAL;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_write: count=%d\n", (int) count));
if (atomic_read(&sdp->detaching))
return -ENODEV;
if (!((filp->f_flags & O_NONBLOCK) ||
scsi_block_when_processing_errors(sdp->device)))
return -ENXIO;
if (!access_ok(VERIFY_READ, buf, count))
return -EFAULT; /* protects following copy_from_user()s + get_user()s */
if (count < SZ_SG_HEADER)
return -EIO;
if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))
return -EFAULT;
blocking = !(filp->f_flags & O_NONBLOCK);
if (old_hdr.reply_len < 0)
return sg_new_write(sfp, filp, buf, count,
blocking, 0, 0, NULL);
if (count < (SZ_SG_HEADER + 6))
return -EIO; /* The minimum scsi command length is 6 bytes. */
if (!(srp = sg_add_request(sfp))) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,
"sg_write: queue full\n"));
return -EDOM;
}
buf += SZ_SG_HEADER;
__get_user(opcode, buf);
if (sfp->next_cmd_len > 0) {
cmd_size = sfp->next_cmd_len;
sfp->next_cmd_len = 0; /* reset so only this write() effected */
} else {
cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */
if ((opcode >= 0xc0) && old_hdr.twelve_byte)
cmd_size = 12;
}
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
"sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size));
/* Determine buffer size. */
input_size = count - cmd_size;
mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;
mxsize -= SZ_SG_HEADER;
input_size -= SZ_SG_HEADER;
if (input_size < 0) {
sg_remove_request(sfp, srp);
return -EIO; /* User did not pass enough bytes for this command. */
}
hp = &srp->header;
hp->interface_id = '\0'; /* indicator of old interface tunnelled */
hp->cmd_len = (unsigned char) cmd_size;
hp->iovec_count = 0;
hp->mx_sb_len = 0;
if (input_size > 0)
hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?
SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
else
hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;
hp->dxfer_len = mxsize;
if ((hp->dxfer_direction == SG_DXFER_TO_DEV) ||
(hp->dxfer_direction == SG_DXFER_TO_FROM_DEV))
hp->dxferp = (char __user *)buf + cmd_size;
else
hp->dxferp = NULL;
hp->sbp = NULL;
hp->timeout = old_hdr.reply_len; /* structure abuse ... */
hp->flags = input_size; /* structure abuse ... */
hp->pack_id = old_hdr.pack_id;
hp->usr_ptr = NULL;
if (__copy_from_user(cmnd, buf, cmd_size))
return -EFAULT;
/*
* SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,
* but is is possible that the app intended SG_DXFER_TO_DEV, because there
* is a non-zero input_size, so emit a warning.
*/
if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {
static char cmd[TASK_COMM_LEN];
if (strcmp(current->comm, cmd)) {
printk_ratelimited(KERN_WARNING
"sg_write: data in/out %d/%d bytes "
"for SCSI command 0x%x-- guessing "
"data in;\n program %s not setting "
"count and/or reply_len properly\n",
old_hdr.reply_len - (int)SZ_SG_HEADER,
input_size, (unsigned int) cmnd[0],
current->comm);
strcpy(cmd, current->comm);
}
}
k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
return (k < 0) ? k : count;
}
| 166,841 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Adding Error Check for f_code Parameters
In MPEG1, the valid range for the forward and backward f_code parameters
is [1, 7]. Adding a check to enforce this. Without the check, the value
could be 0. We read (f_code - 1) bits from the stream and reading a
negative number of bits from the stream is undefined.
Bug: 64550583
Test: monitored temp ALOGD() output
Change-Id: Ia452cd43a28e9d566401f515947164635361782f
(cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689)
CWE ID: CWE-200 | IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
if (ps_dec->u2_forw_f_code < 1 || ps_dec->u2_forw_f_code > 7 ||
ps_dec->u2_back_f_code < 1 || ps_dec->u2_back_f_code > 7)
{
return IMPEG2D_UNKNOWN_ERROR;
}
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 174,103 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int find_high_bit(unsigned int x)
{
int i;
for(i=31;i>=0;i--) {
if(x&(1<<i)) return i;
}
return 0;
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682 | static int find_high_bit(unsigned int x)
{
int i;
for(i=31;i>=0;i--) {
if(x&(1U<<(unsigned int)i)) return i;
}
return 0;
}
| 168,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
}
Commit Message: avcodec/apedec: Fix integer overflow
Fixes: out of array access
Fixes: PoC.ape and others
Found-by: Bingchang, Liu@VARAS of IIE
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
uint64_t decoded_buffer_size;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
av_assert0(decoded_buffer_size <= INT_MAX);
av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
}
| 168,038 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const net::HttpRequestHeaders& request_headers() const {
return request_headers_;
}
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: | const net::HttpRequestHeaders& request_headers() const {
| 172,583 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DelegatedFrameHost::ClearDelegatedFrame() {
EvictDelegatedFrame();
}
Commit Message: mac: Make RWHVMac::ClearCompositorFrame clear locks
Ensure that the BrowserCompositorMac not hold on to a compositor lock
when requested to clear its compositor frame. This lock may be held
indefinitely (if the renderer hangs) and so the frame will never be
cleared.
Bug: 739621
Change-Id: I15d0e82bdf632f3379a48e959f198afb8a4ac218
Reviewed-on: https://chromium-review.googlesource.com/608239
Commit-Queue: ccameron chromium <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#493563}
CWE ID: CWE-20 | void DelegatedFrameHost::ClearDelegatedFrame() {
// Ensure that we are able to swap in a new blank frame to replace any old
// content. This will result in a white flash if we switch back to this
// content.
// https://crbug.com/739621
released_front_lock_.reset();
EvictDelegatedFrame();
}
| 172,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t driver_override_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
return sprintf(buf, "%s\n", pdev->driver_override);
}
Commit Message: driver core: platform: fix race condition with driver_override
The driver_override implementation is susceptible to race condition when
different threads are reading vs storing a different driver override.
Add locking to avoid race condition.
Fixes: 3d713e0e382e ("driver core: platform: add device binding path 'driver_override'")
Cc: [email protected]
Signed-off-by: Adrian Salido <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-362 | static ssize_t driver_override_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
ssize_t len;
device_lock(dev);
len = sprintf(buf, "%s\n", pdev->driver_override);
device_unlock(dev);
return len;
}
| 167,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 TestFlashMessageLoop::RunTests(const std::string& filter) {
RUN_TEST(Basics, filter);
RUN_TEST(RunWithoutQuit, filter);
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264 | void TestFlashMessageLoop::RunTests(const std::string& filter) {
RUN_TEST(Basics, filter);
RUN_TEST(RunWithoutQuit, filter);
RUN_TEST(SuspendScriptCallbackWhileRunning, filter);
}
void TestFlashMessageLoop::DidRunScriptCallback() {
// Script callbacks are not supposed to run while the Flash message loop is
// running.
if (message_loop_)
suspend_script_callback_result_ = false;
}
pp::deprecated::ScriptableObject* TestFlashMessageLoop::CreateTestObject() {
if (!instance_so_)
instance_so_ = new InstanceSO(this);
return instance_so_;
}
| 172,125 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 reference_32x32_dct_1d(const double in[32], double out[32], int stride) {
const double kInvSqrt2 = 0.707106781186547524400844362104;
for (int k = 0; k < 32; k++) {
out[k] = 0.0;
for (int n = 0; n < 32; n++)
out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 64.0);
if (k == 0)
out[k] = out[k] * kInvSqrt2;
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void reference_32x32_dct_1d(const double in[32], double out[32], int stride) {
void reference_32x32_dct_1d(const double in[32], double out[32]) {
const double kInvSqrt2 = 0.707106781186547524400844362104;
for (int k = 0; k < 32; k++) {
out[k] = 0.0;
for (int n = 0; n < 32; n++)
out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 64.0);
if (k == 0)
out[k] = out[k] * kInvSqrt2;
}
}
| 174,532 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
/* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
* configuration option is set. From 1.5.4 the flag is never set and the
* 'scale' API (above) must be used.
*/
# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
# if PNG_LIBPNG_VER >= 10504
# error PNG_READ_ACCURATE_SCALE should not be set
# endif
/* The strip 16 algorithm drops the low 8 bits rather than calculating
* 1/257, so we need to adjust the permitted errors appropriately:
* Notice that this is only relevant prior to the addition of the
* png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
*/
{
PNG_CONST double d = (255-128.5)/65535;
that->rede += d;
that->greene += d;
that->bluee += d;
that->alphae += d;
}
# endif
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
image_transform_png_set_strip_16_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
/* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
* configuration option is set. From 1.5.4 the flag is never set and the
* 'scale' API (above) must be used.
*/
# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
# if PNG_LIBPNG_VER >= 10504
# error PNG_READ_ACCURATE_SCALE should not be set
# endif
/* The strip 16 algorithm drops the low 8 bits rather than calculating
* 1/257, so we need to adjust the permitted errors appropriately:
* Notice that this is only relevant prior to the addition of the
* png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
*/
{
const double d = (255-128.5)/65535;
that->rede += d;
that->greene += d;
that->bluee += d;
that->alphae += d;
}
# endif
}
this->next->mod(this->next, that, pp, display);
}
| 173,649 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: datum_to_json(Datum val, bool is_null, StringInfo result,
JsonTypeCategory tcategory, Oid outfuncoid,
bool key_scalar)
{
char *outputstr;
text *jsontext;
/* callers are expected to ensure that null keys are not passed in */
char *outputstr;
text *jsontext;
/* callers are expected to ensure that null keys are not passed in */
Assert(!(key_scalar && is_null));
if (key_scalar &&
(tcategory == JSONTYPE_ARRAY ||
tcategory == JSONTYPE_COMPOSITE ||
tcategory == JSONTYPE_JSON ||
tcategory == JSONTYPE_CAST))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("key value must be scalar, not array, composite, or json")));
switch (tcategory)
{
case JSONTYPE_ARRAY:
array_to_json_internal(val, result, false);
break;
case JSONTYPE_COMPOSITE:
composite_to_json(val, result, false);
break;
case JSONTYPE_BOOL:
outputstr = DatumGetBool(val) ? "true" : "false";
if (key_scalar)
escape_json(result, outputstr);
else
appendStringInfoString(result, outputstr);
break;
case JSONTYPE_NUMERIC:
outputstr = OidOutputFunctionCall(outfuncoid, val);
/*
* Don't call escape_json for a non-key if it's a valid JSON
* number.
*/
if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
appendStringInfoString(result, outputstr);
else
escape_json(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_DATE:
{
DateADT date;
struct pg_tm tm;
char buf[MAXDATELEN + 1];
date = DatumGetDateADT(val);
if (DATE_NOT_FINITE(date))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else
{
j2date(date + POSTGRES_EPOCH_JDATE,
&(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
EncodeDateOnly(&tm, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
}
break;
case JSONTYPE_TIMESTAMP:
{
Timestamp timestamp;
struct pg_tm tm;
fsec_t fsec;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
{
EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_TIMESTAMPTZ:
{
TimestampTz timestamp;
struct pg_tm tm;
int tz;
fsec_t fsec;
const char *tzn = NULL;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
{
EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_JSON:
/* JSON and JSONB output will already be escaped */
outputstr = OidOutputFunctionCall(outfuncoid, val);
appendStringInfoString(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_CAST:
/* outfuncoid refers to a cast function, not an output function */
jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
outputstr = text_to_cstring(jsontext);
appendStringInfoString(result, outputstr);
pfree(outputstr);
pfree(jsontext);
break;
default:
outputstr = OidOutputFunctionCall(outfuncoid, val);
escape_json(result, outputstr);
pfree(outputstr);
break;
}
}
Commit Message:
CWE ID: CWE-119 | datum_to_json(Datum val, bool is_null, StringInfo result,
JsonTypeCategory tcategory, Oid outfuncoid,
bool key_scalar)
{
char *outputstr;
text *jsontext;
/* callers are expected to ensure that null keys are not passed in */
char *outputstr;
text *jsontext;
check_stack_depth();
/* callers are expected to ensure that null keys are not passed in */
Assert(!(key_scalar && is_null));
if (key_scalar &&
(tcategory == JSONTYPE_ARRAY ||
tcategory == JSONTYPE_COMPOSITE ||
tcategory == JSONTYPE_JSON ||
tcategory == JSONTYPE_CAST))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("key value must be scalar, not array, composite, or json")));
switch (tcategory)
{
case JSONTYPE_ARRAY:
array_to_json_internal(val, result, false);
break;
case JSONTYPE_COMPOSITE:
composite_to_json(val, result, false);
break;
case JSONTYPE_BOOL:
outputstr = DatumGetBool(val) ? "true" : "false";
if (key_scalar)
escape_json(result, outputstr);
else
appendStringInfoString(result, outputstr);
break;
case JSONTYPE_NUMERIC:
outputstr = OidOutputFunctionCall(outfuncoid, val);
/*
* Don't call escape_json for a non-key if it's a valid JSON
* number.
*/
if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
appendStringInfoString(result, outputstr);
else
escape_json(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_DATE:
{
DateADT date;
struct pg_tm tm;
char buf[MAXDATELEN + 1];
date = DatumGetDateADT(val);
if (DATE_NOT_FINITE(date))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else
{
j2date(date + POSTGRES_EPOCH_JDATE,
&(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
EncodeDateOnly(&tm, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
}
break;
case JSONTYPE_TIMESTAMP:
{
Timestamp timestamp;
struct pg_tm tm;
fsec_t fsec;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
{
EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_TIMESTAMPTZ:
{
TimestampTz timestamp;
struct pg_tm tm;
int tz;
fsec_t fsec;
const char *tzn = NULL;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
{
EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_JSON:
/* JSON and JSONB output will already be escaped */
outputstr = OidOutputFunctionCall(outfuncoid, val);
appendStringInfoString(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_CAST:
/* outfuncoid refers to a cast function, not an output function */
jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
outputstr = text_to_cstring(jsontext);
appendStringInfoString(result, outputstr);
pfree(outputstr);
pfree(jsontext);
break;
default:
outputstr = OidOutputFunctionCall(outfuncoid, val);
escape_json(result, outputstr);
pfree(outputstr);
break;
}
}
| 164,678 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: queryin(char *buf)
{
QPRS_STATE state;
int32 i;
ltxtquery *query;
int32 commonlen;
ITEM *ptr;
NODE *tmp;
int32 pos = 0;
#ifdef BS_DEBUG
char pbuf[16384],
*cur;
#endif
/* init state */
state.buf = buf;
state.state = WAITOPERAND;
state.count = 0;
state.num = 0;
state.str = NULL;
/* init list of operand */
state.sumlen = 0;
state.lenop = 64;
state.curop = state.op = (char *) palloc(state.lenop);
*(state.curop) = '\0';
/* parse query & make polish notation (postfix, but in reverse order) */
makepol(&state);
if (!state.num)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("syntax error"),
errdetail("Empty query.")));
/* make finish struct */
commonlen = COMPUTESIZE(state.num, state.sumlen);
query = (ltxtquery *) palloc(commonlen);
SET_VARSIZE(query, commonlen);
query->size = state.num;
ptr = GETQUERY(query);
/* set item in polish notation */
for (i = 0; i < state.num; i++)
{
ptr[i].type = state.str->type;
ptr[i].val = state.str->val;
ptr[i].distance = state.str->distance;
ptr[i].length = state.str->length;
ptr[i].flag = state.str->flag;
tmp = state.str->next;
pfree(state.str);
state.str = tmp;
}
/* set user friendly-operand view */
memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);
pfree(state.op);
/* set left operand's position for every operator */
pos = 0;
findoprnd(ptr, &pos);
return query;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | queryin(char *buf)
{
QPRS_STATE state;
int32 i;
ltxtquery *query;
int32 commonlen;
ITEM *ptr;
NODE *tmp;
int32 pos = 0;
#ifdef BS_DEBUG
char pbuf[16384],
*cur;
#endif
/* init state */
state.buf = buf;
state.state = WAITOPERAND;
state.count = 0;
state.num = 0;
state.str = NULL;
/* init list of operand */
state.sumlen = 0;
state.lenop = 64;
state.curop = state.op = (char *) palloc(state.lenop);
*(state.curop) = '\0';
/* parse query & make polish notation (postfix, but in reverse order) */
makepol(&state);
if (!state.num)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("syntax error"),
errdetail("Empty query.")));
if (LTXTQUERY_TOO_BIG(state.num, state.sumlen))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("ltxtquery is too large")));
commonlen = COMPUTESIZE(state.num, state.sumlen);
query = (ltxtquery *) palloc(commonlen);
SET_VARSIZE(query, commonlen);
query->size = state.num;
ptr = GETQUERY(query);
/* set item in polish notation */
for (i = 0; i < state.num; i++)
{
ptr[i].type = state.str->type;
ptr[i].val = state.str->val;
ptr[i].distance = state.str->distance;
ptr[i].length = state.str->length;
ptr[i].flag = state.str->flag;
tmp = state.str->next;
pfree(state.str);
state.str = tmp;
}
/* set user friendly-operand view */
memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);
pfree(state.op);
/* set left operand's position for every operator */
pos = 0;
findoprnd(ptr, &pos);
return query;
}
| 166,408 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len,
gx_io_device *iodev, const char *permitgroup)
{
long i;
ref *permitlist = NULL;
/* an empty string (first character == 0) if '\' character is */
/* recognized as a file name separator as on DOS & Windows */
const char *win_sep2 = "\\";
bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1);
uint plen = gp_file_name_parents(fname, len);
/* we're protecting arbitrary file system accesses, not Postscript device accesses.
* Although, note that %pipe% is explicitly checked for and disallowed elsewhere
*/
if (iodev != iodev_default(imemory)) {
return 0;
}
/* Assuming a reduced file name. */
if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0)
return 0; /* if Permissions not found, just allow access */
for (i=0; i<r_size(permitlist); i++) {
ref permitstring;
const string_match_params win_filename_params = {
'*', '?', '\\', true, true /* ignore case & '/' == '\\' */
};
const byte *permstr;
uint permlen;
int cwd_len = 0;
if (array_get(imemory, permitlist, i, &permitstring) < 0 ||
r_type(&permitstring) != t_string
)
break; /* any problem, just fail */
permstr = permitstring.value.bytes;
permlen = r_size(&permitstring);
/*
* Check if any file name is permitted with "*".
*/
if (permlen == 1 && permstr[0] == '*')
return 0; /* success */
/*
* If the filename starts with parent references,
* the permission element must start with same number of parent references.
*/
if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen))
continue;
cwd_len = gp_file_name_cwds((const char *)permstr, permlen);
/*
* If the permission starts with "./", absolute paths
* are not permitted.
*/
if (cwd_len > 0 && gp_file_name_is_absolute(fname, len))
continue;
/*
* If the permission starts with "./", relative paths
* with no "./" are allowed as well as with "./".
* 'fname' has no "./" because it is reduced.
*/
if (string_match( (const unsigned char*) fname, len,
permstr + cwd_len, permlen - cwd_len,
use_windows_pathsep ? &win_filename_params : NULL))
return 0; /* success */
}
/* not found */
return gs_error_invalidfileaccess;
}
Commit Message:
CWE ID: | check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len,
gx_io_device *iodev, const char *permitgroup)
{
long i;
ref *permitlist = NULL;
/* an empty string (first character == 0) if '\' character is */
/* recognized as a file name separator as on DOS & Windows */
const char *win_sep2 = "\\";
bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1);
uint plen = gp_file_name_parents(fname, len);
/* we're protecting arbitrary file system accesses, not Postscript device accesses.
* Although, note that %pipe% is explicitly checked for and disallowed elsewhere
*/
if (iodev && iodev != iodev_default(imemory)) {
return 0;
}
/* Assuming a reduced file name. */
if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0)
return 0; /* if Permissions not found, just allow access */
for (i=0; i<r_size(permitlist); i++) {
ref permitstring;
const string_match_params win_filename_params = {
'*', '?', '\\', true, true /* ignore case & '/' == '\\' */
};
const byte *permstr;
uint permlen;
int cwd_len = 0;
if (array_get(imemory, permitlist, i, &permitstring) < 0 ||
r_type(&permitstring) != t_string
)
break; /* any problem, just fail */
permstr = permitstring.value.bytes;
permlen = r_size(&permitstring);
/*
* Check if any file name is permitted with "*".
*/
if (permlen == 1 && permstr[0] == '*')
return 0; /* success */
/*
* If the filename starts with parent references,
* the permission element must start with same number of parent references.
*/
if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen))
continue;
cwd_len = gp_file_name_cwds((const char *)permstr, permlen);
/*
* If the permission starts with "./", absolute paths
* are not permitted.
*/
if (cwd_len > 0 && gp_file_name_is_absolute(fname, len))
continue;
/*
* If the permission starts with "./", relative paths
* with no "./" are allowed as well as with "./".
* 'fname' has no "./" because it is reduced.
*/
if (string_match( (const unsigned char*) fname, len,
permstr + cwd_len, permlen - cwd_len,
use_windows_pathsep ? &win_filename_params : NULL))
return 0; /* success */
}
/* not found */
return gs_error_invalidfileaccess;
}
| 164,708 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void aes_crypt_ecb( aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] )
{
int i;
unsigned long *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;
#if defined(XYSSL_PADLOCK_C) && defined(XYSSL_HAVE_X86)
if( padlock_supports( PADLOCK_ACE ) )
{
if( padlock_xcryptecb( ctx, mode, input, output ) == 0 )
return;
}
#endif
RK = ctx->rk;
GET_ULONG_LE( X0, input, 0 ); X0 ^= *RK++;
if( mode == AES_DECRYPT )
{
for( i = (ctx->nr >> 1) - 1; i > 0; i-- )
{
AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
}
AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
X0 = *RK++ ^ ( RSb[ ( Y0 ) & 0xFF ] ) ^
( RSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y1 >> 24 ) & 0xFF ]) << 24 );
X1 = *RK++ ^ ( RSb[ ( Y1 ) & 0xFF ] ) ^
( RSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y2 >> 24 ) & 0xFF ]) << 24 );
X2 = *RK++ ^ ( RSb[ ( Y2 ) & 0xFF ] ) ^
( RSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y3 >> 24 ) & 0xFF ]) << 24 );
X3 = *RK++ ^ ( RSb[ ( Y3 ) & 0xFF ] ) ^
( RSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y0 >> 24 ) & 0xFF ]) << 24 );
}
else /* AES_ENCRYPT */
{
for( i = (ctx->nr >> 1) - 1; i > 0; i-- )
{
AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
}
AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
X0 = *RK++ ^ ( FSb[ ( Y0 ) & 0xFF ] ) ^
( FSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y3 >> 24 ) & 0xFF ]) << 24 );
X1 = *RK++ ^ ( FSb[ ( Y1 ) & 0xFF ] ) ^
( FSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y0 >> 24 ) & 0xFF ]) << 24 );
X2 = *RK++ ^ ( FSb[ ( Y2 ) & 0xFF ] ) ^
( FSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y1 >> 24 ) & 0xFF ]) << 24 );
X3 = *RK++ ^ ( FSb[ ( Y3 ) & 0xFF ] ) ^
( FSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y2 >> 24 ) & 0xFF ]) << 24 );
}
PUT_ULONG_LE( X0, output, 0 );
PUT_ULONG_LE( X1, output, 4 );
PUT_ULONG_LE( X2, output, 8 );
PUT_ULONG_LE( X3, output, 12 );
}
Commit Message:
CWE ID: CWE-119 | void aes_crypt_ecb( aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] )
{
int i;
unsigned long *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;
#if defined(XYSSL_PADLOCK_C) && defined(XYSSL_HAVE_X86)
if( padlock_supports( PADLOCK_ACE ) )
{
if( padlock_xcryptecb( ctx, mode, input, output ) == 0 )
return;
}
#endif
if (ctx == NULL || ctx->rk == NULL)
return;
RK = ctx->rk;
GET_ULONG_LE( X0, input, 0 ); X0 ^= *RK++;
if( mode == AES_DECRYPT )
{
for( i = (ctx->nr >> 1) - 1; i > 0; i-- )
{
AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
}
AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
X0 = *RK++ ^ ( RSb[ ( Y0 ) & 0xFF ] ) ^
( RSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y1 >> 24 ) & 0xFF ]) << 24 );
X1 = *RK++ ^ ( RSb[ ( Y1 ) & 0xFF ] ) ^
( RSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y2 >> 24 ) & 0xFF ]) << 24 );
X2 = *RK++ ^ ( RSb[ ( Y2 ) & 0xFF ] ) ^
( RSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y3 >> 24 ) & 0xFF ]) << 24 );
X3 = *RK++ ^ ( RSb[ ( Y3 ) & 0xFF ] ) ^
( RSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^
( RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)RSb[ ( Y0 >> 24 ) & 0xFF ]) << 24 );
}
else /* AES_ENCRYPT */
{
for( i = (ctx->nr >> 1) - 1; i > 0; i-- )
{
AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
}
AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
X0 = *RK++ ^ ( FSb[ ( Y0 ) & 0xFF ] ) ^
( FSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y3 >> 24 ) & 0xFF ]) << 24 );
X1 = *RK++ ^ ( FSb[ ( Y1 ) & 0xFF ] ) ^
( FSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y0 >> 24 ) & 0xFF ]) << 24 );
X2 = *RK++ ^ ( FSb[ ( Y2 ) & 0xFF ] ) ^
( FSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y1 >> 24 ) & 0xFF ]) << 24 );
X3 = *RK++ ^ ( FSb[ ( Y3 ) & 0xFF ] ) ^
( FSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^
( FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
( ((unsigned int)FSb[ ( Y2 >> 24 ) & 0xFF ]) << 24 );
}
PUT_ULONG_LE( X0, output, 0 );
PUT_ULONG_LE( X1, output, 4 );
PUT_ULONG_LE( X2, output, 8 );
PUT_ULONG_LE( X3, output, 12 );
}
| 164,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SplitString(const std::wstring& str,
wchar_t c,
std::vector<std::wstring>* r) {
SplitStringT(str, c, true, r);
}
Commit Message: wstring: remove wstring version of SplitString
Retry of r84336.
BUG=23581
Review URL: http://codereview.chromium.org/6930047
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void SplitString(const std::wstring& str,
| 170,555 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::ProcessHandle StartProcessWithAccess(CommandLine* cmd_line,
const FilePath& exposed_dir) {
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
content::ProcessType type;
std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
if (type_str == switches::kRendererProcess) {
type = content::PROCESS_TYPE_RENDERER;
} else if (type_str == switches::kPluginProcess) {
type = content::PROCESS_TYPE_PLUGIN;
} else if (type_str == switches::kWorkerProcess) {
type = content::PROCESS_TYPE_WORKER;
} else if (type_str == switches::kNaClLoaderProcess) {
type = content::PROCESS_TYPE_NACL_LOADER;
} else if (type_str == switches::kUtilityProcess) {
type = content::PROCESS_TYPE_UTILITY;
} else if (type_str == switches::kNaClBrokerProcess) {
type = content::PROCESS_TYPE_NACL_BROKER;
} else if (type_str == switches::kGpuProcess) {
type = content::PROCESS_TYPE_GPU;
} else if (type_str == switches::kPpapiPluginProcess) {
type = content::PROCESS_TYPE_PPAPI_PLUGIN;
} else if (type_str == switches::kPpapiBrokerProcess) {
type = content::PROCESS_TYPE_PPAPI_BROKER;
} else {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
bool in_sandbox =
(type != content::PROCESS_TYPE_NACL_BROKER) &&
(type != content::PROCESS_TYPE_PLUGIN) &&
(type != content::PROCESS_TYPE_PPAPI_BROKER);
if ((type == content::PROCESS_TYPE_GPU) &&
(cmd_line->HasSwitch(switches::kDisableGpuSandbox))) {
in_sandbox = false;
DVLOG(1) << "GPU sandbox is disabled";
}
if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
cmd_line->HasSwitch(switches::kNoSandbox)) {
in_sandbox = false;
}
#if !defined (GOOGLE_CHROME_BUILD)
if (browser_command_line.HasSwitch(switches::kInProcessPlugins)) {
in_sandbox = false;
}
#endif
if (!browser_command_line.HasSwitch(switches::kDisable3DAPIs) &&
!browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
browser_command_line.HasSwitch(switches::kInProcessWebGL)) {
in_sandbox = false;
}
if (browser_command_line.HasSwitch(switches::kChromeFrame)) {
if (!cmd_line->HasSwitch(switches::kChromeFrame)) {
cmd_line->AppendSwitch(switches::kChromeFrame);
}
}
bool child_needs_help =
DebugFlags::ProcessDebugFlags(cmd_line, type, in_sandbox);
cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", type));
sandbox::ResultCode result;
base::win::ScopedProcessInformation target;
sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (type == content::PROCESS_TYPE_PLUGIN &&
!browser_command_line.HasSwitch(switches::kNoSandbox) &&
content::GetContentClient()->SandboxPlugin(cmd_line, policy)) {
in_sandbox = true;
}
#endif
if (!in_sandbox) {
policy->Release();
base::ProcessHandle process = 0;
base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
return process;
}
if (type == content::PROCESS_TYPE_PLUGIN) {
AddGenericDllEvictionPolicy(policy);
AddPluginDllEvictionPolicy(policy);
} else if (type == content::PROCESS_TYPE_GPU) {
if (!AddPolicyForGPU(cmd_line, policy))
return 0;
} else {
if (!AddPolicyForRenderer(policy))
return 0;
if (type == content::PROCESS_TYPE_RENDERER ||
type == content::PROCESS_TYPE_WORKER) {
AddBaseHandleClosePolicy(policy);
} else if (type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
if (!AddPolicyForPepperPlugin(policy))
return 0;
}
if (type_str != switches::kRendererProcess) {
cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
}
}
if (!exposed_dir.empty()) {
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_dir.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
FilePath exposed_files = exposed_dir.AppendASCII("*");
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_files.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
}
if (!AddGenericPolicy(policy)) {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
result = g_broker_services->SpawnTarget(
cmd_line->GetProgram().value().c_str(),
cmd_line->GetCommandLineString().c_str(),
policy, target.Receive());
policy->Release();
TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
if (sandbox::SBOX_ALL_OK != result) {
DLOG(ERROR) << "Failed to launch process. Error: " << result;
return 0;
}
if (type == content::PROCESS_TYPE_NACL_LOADER &&
(base::win::OSInfo::GetInstance()->wow64_status() ==
base::win::OSInfo::WOW64_DISABLED)) {
const SIZE_T kOneGigabyte = 1 << 30;
void* nacl_mem = VirtualAllocEx(target.process_handle(),
NULL,
kOneGigabyte,
MEM_RESERVE,
PAGE_NOACCESS);
if (!nacl_mem) {
DLOG(WARNING) << "Failed to reserve address space for Native Client";
}
}
ResumeThread(target.thread_handle());
if (child_needs_help)
base::debug::SpawnDebuggerOnProcess(target.process_id());
return target.TakeProcessHandle();
}
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: | base::ProcessHandle StartProcessWithAccess(CommandLine* cmd_line,
const FilePath& exposed_dir) {
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
content::ProcessType type;
std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
if (type_str == switches::kRendererProcess) {
type = content::PROCESS_TYPE_RENDERER;
} else if (type_str == switches::kPluginProcess) {
type = content::PROCESS_TYPE_PLUGIN;
} else if (type_str == switches::kWorkerProcess) {
type = content::PROCESS_TYPE_WORKER;
} else if (type_str == switches::kNaClLoaderProcess) {
type = content::PROCESS_TYPE_NACL_LOADER;
} else if (type_str == switches::kUtilityProcess) {
type = content::PROCESS_TYPE_UTILITY;
} else if (type_str == switches::kNaClBrokerProcess) {
type = content::PROCESS_TYPE_NACL_BROKER;
} else if (type_str == switches::kGpuProcess) {
type = content::PROCESS_TYPE_GPU;
} else if (type_str == switches::kPpapiPluginProcess) {
type = content::PROCESS_TYPE_PPAPI_PLUGIN;
} else if (type_str == switches::kPpapiBrokerProcess) {
type = content::PROCESS_TYPE_PPAPI_BROKER;
} else {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
bool in_sandbox =
(type != content::PROCESS_TYPE_NACL_BROKER) &&
(type != content::PROCESS_TYPE_PLUGIN) &&
(type != content::PROCESS_TYPE_PPAPI_BROKER);
if ((type == content::PROCESS_TYPE_GPU) &&
(cmd_line->HasSwitch(switches::kDisableGpuSandbox))) {
in_sandbox = false;
DVLOG(1) << "GPU sandbox is disabled";
}
if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
cmd_line->HasSwitch(switches::kNoSandbox)) {
in_sandbox = false;
}
#if !defined (GOOGLE_CHROME_BUILD)
if (browser_command_line.HasSwitch(switches::kInProcessPlugins)) {
in_sandbox = false;
}
#endif
if (!browser_command_line.HasSwitch(switches::kDisable3DAPIs) &&
!browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
browser_command_line.HasSwitch(switches::kInProcessWebGL)) {
in_sandbox = false;
}
if (browser_command_line.HasSwitch(switches::kChromeFrame)) {
if (!cmd_line->HasSwitch(switches::kChromeFrame)) {
cmd_line->AppendSwitch(switches::kChromeFrame);
}
}
bool child_needs_help =
DebugFlags::ProcessDebugFlags(cmd_line, type, in_sandbox);
cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", type));
sandbox::ResultCode result;
base::win::ScopedProcessInformation target;
sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (type == content::PROCESS_TYPE_PLUGIN &&
!browser_command_line.HasSwitch(switches::kNoSandbox) &&
content::GetContentClient()->SandboxPlugin(cmd_line, policy)) {
in_sandbox = true;
}
#endif
if (!in_sandbox) {
policy->Release();
base::ProcessHandle process = 0;
base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
g_broker_services->AddTargetPeer(process);
return process;
}
if (type == content::PROCESS_TYPE_PLUGIN) {
AddGenericDllEvictionPolicy(policy);
AddPluginDllEvictionPolicy(policy);
} else if (type == content::PROCESS_TYPE_GPU) {
if (!AddPolicyForGPU(cmd_line, policy))
return 0;
} else {
if (!AddPolicyForRenderer(policy))
return 0;
if (type == content::PROCESS_TYPE_RENDERER ||
type == content::PROCESS_TYPE_WORKER) {
AddBaseHandleClosePolicy(policy);
} else if (type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
if (!AddPolicyForPepperPlugin(policy))
return 0;
}
if (type_str != switches::kRendererProcess) {
cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
}
}
if (!exposed_dir.empty()) {
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_dir.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
FilePath exposed_files = exposed_dir.AppendASCII("*");
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_files.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
}
if (!AddGenericPolicy(policy)) {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
result = g_broker_services->SpawnTarget(
cmd_line->GetProgram().value().c_str(),
cmd_line->GetCommandLineString().c_str(),
policy, target.Receive());
policy->Release();
TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
if (sandbox::SBOX_ALL_OK != result) {
DLOG(ERROR) << "Failed to launch process. Error: " << result;
return 0;
}
if (type == content::PROCESS_TYPE_NACL_LOADER &&
(base::win::OSInfo::GetInstance()->wow64_status() ==
base::win::OSInfo::WOW64_DISABLED)) {
const SIZE_T kOneGigabyte = 1 << 30;
void* nacl_mem = VirtualAllocEx(target.process_handle(),
NULL,
kOneGigabyte,
MEM_RESERVE,
PAGE_NOACCESS);
if (!nacl_mem) {
DLOG(WARNING) << "Failed to reserve address space for Native Client";
}
}
ResumeThread(target.thread_handle());
if (child_needs_help)
base::debug::SpawnDebuggerOnProcess(target.process_id());
return target.TakeProcessHandle();
}
| 170,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority *authority,
PolkitSubject *caller,
PolkitSubject *subject,
const gchar *action_id,
PolkitDetails *details,
PolkitCheckAuthorizationFlags flags,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
PolkitBackendInteractiveAuthority *interactive_authority;
PolkitBackendInteractiveAuthorityPrivate *priv;
gchar *caller_str;
gchar *subject_str;
PolkitIdentity *user_of_caller;
PolkitIdentity *user_of_subject;
gchar *user_of_caller_str;
gchar *user_of_subject_str;
PolkitAuthorizationResult *result;
GError *error;
GSimpleAsyncResult *simple;
gboolean has_details;
gchar **detail_keys;
interactive_authority = POLKIT_BACKEND_INTERACTIVE_AUTHORITY (authority);
priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (interactive_authority);
error = NULL;
caller_str = NULL;
subject_str = NULL;
user_of_caller = NULL;
user_of_subject = NULL;
user_of_caller_str = NULL;
user_of_subject_str = NULL;
result = NULL;
simple = g_simple_async_result_new (G_OBJECT (authority),
callback,
user_data,
polkit_backend_interactive_authority_check_authorization);
/* handle being called from ourselves */
if (caller == NULL)
{
/* TODO: this is kind of a hack */
GDBusConnection *system_bus;
system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL);
caller = polkit_system_bus_name_new (g_dbus_connection_get_unique_name (system_bus));
g_object_unref (system_bus);
}
caller_str = polkit_subject_to_string (caller);
subject_str = polkit_subject_to_string (subject);
g_debug ("%s is inquiring whether %s is authorized for %s",
caller_str,
subject_str,
action_id);
action_id);
user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor,
caller,
&error);
if (error != NULL)
{
g_simple_async_result_complete (simple);
g_object_unref (simple);
g_error_free (error);
goto out;
}
user_of_caller_str = polkit_identity_to_string (user_of_caller);
g_debug (" user of caller is %s", user_of_caller_str);
g_debug (" user of caller is %s", user_of_caller_str);
user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor,
subject,
&error);
if (error != NULL)
{
g_simple_async_result_complete (simple);
g_object_unref (simple);
g_error_free (error);
goto out;
}
user_of_subject_str = polkit_identity_to_string (user_of_subject);
g_debug (" user of subject is %s", user_of_subject_str);
has_details = FALSE;
if (details != NULL)
{
detail_keys = polkit_details_get_keys (details);
if (detail_keys != NULL)
{
if (g_strv_length (detail_keys) > 0)
has_details = TRUE;
g_strfreev (detail_keys);
}
}
/* Not anyone is allowed to check that process XYZ is allowed to do ABC.
* We only allow this if, and only if,
* We only allow this if, and only if,
*
* - processes may check for another process owned by the *same* user but not
* if details are passed (otherwise you'd be able to spoof the dialog)
*
* - processes running as uid 0 may check anything and pass any details
*
if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details)
* then any uid referenced by that annotation is also allowed to check
* to check anything and pass any details
*/
if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details)
{
if (!may_identity_check_authorization (interactive_authority, action_id, user_of_caller))
{
"pass details");
}
else
{
g_simple_async_result_set_error (simple,
POLKIT_ERROR,
POLKIT_ERROR_NOT_AUTHORIZED,
"Only trusted callers (e.g. uid 0 or an action owner) can use CheckAuthorization() for "
"subjects belonging to other identities");
}
g_simple_async_result_complete (simple);
g_object_unref (simple);
goto out;
}
}
Commit Message:
CWE ID: CWE-200 | polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority *authority,
PolkitSubject *caller,
PolkitSubject *subject,
const gchar *action_id,
PolkitDetails *details,
PolkitCheckAuthorizationFlags flags,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
PolkitBackendInteractiveAuthority *interactive_authority;
PolkitBackendInteractiveAuthorityPrivate *priv;
gchar *caller_str;
gchar *subject_str;
PolkitIdentity *user_of_caller;
PolkitIdentity *user_of_subject;
gboolean user_of_subject_matches;
gchar *user_of_caller_str;
gchar *user_of_subject_str;
PolkitAuthorizationResult *result;
GError *error;
GSimpleAsyncResult *simple;
gboolean has_details;
gchar **detail_keys;
interactive_authority = POLKIT_BACKEND_INTERACTIVE_AUTHORITY (authority);
priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (interactive_authority);
error = NULL;
caller_str = NULL;
subject_str = NULL;
user_of_caller = NULL;
user_of_subject = NULL;
user_of_caller_str = NULL;
user_of_subject_str = NULL;
result = NULL;
simple = g_simple_async_result_new (G_OBJECT (authority),
callback,
user_data,
polkit_backend_interactive_authority_check_authorization);
/* handle being called from ourselves */
if (caller == NULL)
{
/* TODO: this is kind of a hack */
GDBusConnection *system_bus;
system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL);
caller = polkit_system_bus_name_new (g_dbus_connection_get_unique_name (system_bus));
g_object_unref (system_bus);
}
caller_str = polkit_subject_to_string (caller);
subject_str = polkit_subject_to_string (subject);
g_debug ("%s is inquiring whether %s is authorized for %s",
caller_str,
subject_str,
action_id);
action_id);
user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor,
caller, NULL,
&error);
if (error != NULL)
{
g_simple_async_result_complete (simple);
g_object_unref (simple);
g_error_free (error);
goto out;
}
user_of_caller_str = polkit_identity_to_string (user_of_caller);
g_debug (" user of caller is %s", user_of_caller_str);
g_debug (" user of caller is %s", user_of_caller_str);
user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor,
subject, &user_of_subject_matches,
&error);
if (error != NULL)
{
g_simple_async_result_complete (simple);
g_object_unref (simple);
g_error_free (error);
goto out;
}
user_of_subject_str = polkit_identity_to_string (user_of_subject);
g_debug (" user of subject is %s", user_of_subject_str);
has_details = FALSE;
if (details != NULL)
{
detail_keys = polkit_details_get_keys (details);
if (detail_keys != NULL)
{
if (g_strv_length (detail_keys) > 0)
has_details = TRUE;
g_strfreev (detail_keys);
}
}
/* Not anyone is allowed to check that process XYZ is allowed to do ABC.
* We only allow this if, and only if,
* We only allow this if, and only if,
*
* - processes may check for another process owned by the *same* user but not
* if details are passed (otherwise you'd be able to spoof the dialog);
* the caller supplies the user_of_subject value, so we additionally
* require it to match at least at one point in time (via
* user_of_subject_matches).
*
* - processes running as uid 0 may check anything and pass any details
*
if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details)
* then any uid referenced by that annotation is also allowed to check
* to check anything and pass any details
*/
if (!user_of_subject_matches
|| !polkit_identity_equal (user_of_caller, user_of_subject)
|| has_details)
{
if (!may_identity_check_authorization (interactive_authority, action_id, user_of_caller))
{
"pass details");
}
else
{
g_simple_async_result_set_error (simple,
POLKIT_ERROR,
POLKIT_ERROR_NOT_AUTHORIZED,
"Only trusted callers (e.g. uid 0 or an action owner) can use CheckAuthorization() for "
"subjects belonging to other identities");
}
g_simple_async_result_complete (simple);
g_object_unref (simple);
goto out;
}
}
| 165,288 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: create_filesystem_object(struct archive_write_disk *a)
{
/* Create the entry. */
const char *linkname;
mode_t final_mode, mode;
int r;
/* We identify hard/symlinks according to the link names. */
/* Since link(2) and symlink(2) don't handle modes, we're done here. */
linkname = archive_entry_hardlink(a->entry);
if (linkname != NULL) {
#if !HAVE_LINK
return (EPERM);
#else
r = link(linkname, a->name) ? errno : 0;
/*
* New cpio and pax formats allow hardlink entries
* to carry data, so we may have to open the file
* for hardlink entries.
*
* If the hardlink was successfully created and
* the archive doesn't have carry data for it,
* consider it to be non-authoritative for meta data.
* This is consistent with GNU tar and BSD pax.
* If the hardlink does carry data, let the last
* archive entry decide ownership.
*/
if (r == 0 && a->filesize <= 0) {
a->todo = 0;
a->deferred = 0;
} else if (r == 0 && a->filesize > 0) {
a->fd = open(a->name,
O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->fd);
if (a->fd < 0)
r = errno;
}
return (r);
#endif
}
linkname = archive_entry_symlink(a->entry);
if (linkname != NULL) {
#if HAVE_SYMLINK
return symlink(linkname, a->name) ? errno : 0;
#else
return (EPERM);
#endif
}
/*
* The remaining system calls all set permissions, so let's
* try to take advantage of that to avoid an extra chmod()
* call. (Recall that umask is set to zero right now!)
*/
/* Mode we want for the final restored object (w/o file type bits). */
final_mode = a->mode & 07777;
/*
* The mode that will actually be restored in this step. Note
* that SUID, SGID, etc, require additional work to ensure
* security, so we never restore them at this point.
*/
mode = final_mode & 0777 & ~a->user_umask;
switch (a->mode & AE_IFMT) {
default:
/* POSIX requires that we fall through here. */
/* FALLTHROUGH */
case AE_IFREG:
a->fd = open(a->name,
O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
__archive_ensure_cloexec_flag(a->fd);
r = (a->fd < 0);
break;
case AE_IFCHR:
#ifdef HAVE_MKNOD
/* Note: we use AE_IFCHR for the case label, and
* S_IFCHR for the mknod() call. This is correct. */
r = mknod(a->name, mode | S_IFCHR,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a char device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFBLK:
#ifdef HAVE_MKNOD
r = mknod(a->name, mode | S_IFBLK,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a block device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFDIR:
mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
r = mkdir(a->name, mode);
if (r == 0) {
/* Defer setting dir times. */
a->deferred |= (a->todo & TODO_TIMES);
a->todo &= ~TODO_TIMES;
/* Never use an immediate chmod(). */
/* We can't avoid the chmod() entirely if EXTRACT_PERM
* because of SysV SGID inheritance. */
if ((mode != final_mode)
|| (a->flags & ARCHIVE_EXTRACT_PERM))
a->deferred |= (a->todo & TODO_MODE);
a->todo &= ~TODO_MODE;
}
break;
case AE_IFIFO:
#ifdef HAVE_MKFIFO
r = mkfifo(a->name, mode);
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a fifo. */
return (EINVAL);
#endif /* HAVE_MKFIFO */
}
/* All the system calls above set errno on failure. */
if (r)
return (errno);
/* If we managed to set the final mode, we've avoided a chmod(). */
if (mode == final_mode)
a->todo &= ~TODO_MODE;
return (0);
}
Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert.
CWE ID: CWE-20 | create_filesystem_object(struct archive_write_disk *a)
{
/* Create the entry. */
const char *linkname;
mode_t final_mode, mode;
int r;
/* these for check_symlinks_fsobj */
char *linkname_copy; /* non-const copy of linkname */
struct archive_string error_string;
int error_number;
/* We identify hard/symlinks according to the link names. */
/* Since link(2) and symlink(2) don't handle modes, we're done here. */
linkname = archive_entry_hardlink(a->entry);
if (linkname != NULL) {
#if !HAVE_LINK
return (EPERM);
#else
archive_string_init(&error_string);
linkname_copy = strdup(linkname);
if (linkname_copy == NULL) {
return (EPERM);
}
/* TODO: consider using the cleaned-up path as the link target? */
r = cleanup_pathname_fsobj(linkname_copy, &error_number, &error_string, a->flags);
if (r != ARCHIVE_OK) {
archive_set_error(&a->archive, error_number, "%s", error_string.s);
free(linkname_copy);
/* EPERM is more appropriate than error_number for our callers */
return (EPERM);
}
r = check_symlinks_fsobj(linkname_copy, &error_number, &error_string, a->flags);
if (r != ARCHIVE_OK) {
archive_set_error(&a->archive, error_number, "%s", error_string.s);
free(linkname_copy);
/* EPERM is more appropriate than error_number for our callers */
return (EPERM);
}
free(linkname_copy);
r = link(linkname, a->name) ? errno : 0;
/*
* New cpio and pax formats allow hardlink entries
* to carry data, so we may have to open the file
* for hardlink entries.
*
* If the hardlink was successfully created and
* the archive doesn't have carry data for it,
* consider it to be non-authoritative for meta data.
* This is consistent with GNU tar and BSD pax.
* If the hardlink does carry data, let the last
* archive entry decide ownership.
*/
if (r == 0 && a->filesize <= 0) {
a->todo = 0;
a->deferred = 0;
} else if (r == 0 && a->filesize > 0) {
a->fd = open(a->name,
O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->fd);
if (a->fd < 0)
r = errno;
}
return (r);
#endif
}
linkname = archive_entry_symlink(a->entry);
if (linkname != NULL) {
#if HAVE_SYMLINK
return symlink(linkname, a->name) ? errno : 0;
#else
return (EPERM);
#endif
}
/*
* The remaining system calls all set permissions, so let's
* try to take advantage of that to avoid an extra chmod()
* call. (Recall that umask is set to zero right now!)
*/
/* Mode we want for the final restored object (w/o file type bits). */
final_mode = a->mode & 07777;
/*
* The mode that will actually be restored in this step. Note
* that SUID, SGID, etc, require additional work to ensure
* security, so we never restore them at this point.
*/
mode = final_mode & 0777 & ~a->user_umask;
switch (a->mode & AE_IFMT) {
default:
/* POSIX requires that we fall through here. */
/* FALLTHROUGH */
case AE_IFREG:
a->fd = open(a->name,
O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
__archive_ensure_cloexec_flag(a->fd);
r = (a->fd < 0);
break;
case AE_IFCHR:
#ifdef HAVE_MKNOD
/* Note: we use AE_IFCHR for the case label, and
* S_IFCHR for the mknod() call. This is correct. */
r = mknod(a->name, mode | S_IFCHR,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a char device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFBLK:
#ifdef HAVE_MKNOD
r = mknod(a->name, mode | S_IFBLK,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a block device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFDIR:
mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
r = mkdir(a->name, mode);
if (r == 0) {
/* Defer setting dir times. */
a->deferred |= (a->todo & TODO_TIMES);
a->todo &= ~TODO_TIMES;
/* Never use an immediate chmod(). */
/* We can't avoid the chmod() entirely if EXTRACT_PERM
* because of SysV SGID inheritance. */
if ((mode != final_mode)
|| (a->flags & ARCHIVE_EXTRACT_PERM))
a->deferred |= (a->todo & TODO_MODE);
a->todo &= ~TODO_MODE;
}
break;
case AE_IFIFO:
#ifdef HAVE_MKFIFO
r = mkfifo(a->name, mode);
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a fifo. */
return (EINVAL);
#endif /* HAVE_MKFIFO */
}
/* All the system calls above set errno on failure. */
if (r)
return (errno);
/* If we managed to set the final mode, we've avoided a chmod(). */
if (mode == final_mode)
a->todo &= ~TODO_MODE;
return (0);
}
| 167,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
{
struct rar *rar = (struct rar *)(a->format->data);
const void *h = __archive_read_ahead(a, min, avail);
int ret;
if (avail)
{
if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
*avail = a->archive.read_data_requested;
if (*avail > rar->bytes_remaining)
*avail = (ssize_t)rar->bytes_remaining;
if (*avail < 0)
return NULL;
else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
rar->file_flags & FHD_SPLIT_AFTER)
{
ret = archive_read_format_rar_read_header(a, a->entry);
if (ret == (ARCHIVE_EOF))
{
rar->has_endarc_header = 1;
ret = archive_read_format_rar_read_header(a, a->entry);
}
if (ret != (ARCHIVE_OK))
return NULL;
return rar_read_ahead(a, min, avail);
}
}
return h;
}
Commit Message: rar: file split across multi-part archives must match
Fuzzing uncovered some UAF and memory overrun bugs where a file in a
single file archive reported that it was split across multiple
volumes. This was caused by ppmd7 operations calling
rar_br_fillup. This would invoke rar_read_ahead, which would in some
situations invoke archive_read_format_rar_read_header. That would
check the new file name against the old file name, and if they didn't
match up it would free the ppmd7 buffer and allocate a new
one. However, because the ppmd7 decoder wasn't actually done with the
buffer, it would continue to used the freed buffer. Both reads and
writes to the freed region can be observed.
This is quite tricky to solve: once the buffer has been freed it is
too late, as the ppmd7 decoder functions almost universally assume
success - there's no way for ppmd_read to signal error, nor are there
good ways for functions like Range_Normalise to propagate them. So we
can't detect after the fact that we're in an invalid state - e.g. by
checking rar->cursor, we have to prevent ourselves from ever ending up
there. So, when we are in the dangerous part or rar_read_ahead that
assumes a valid split, we set a flag force read_header to either go
down the path for split files or bail. This means that the ppmd7
decoder keeps a valid buffer and just runs out of data.
Found with a combination of AFL, afl-rb and qsym.
CWE ID: CWE-416 | rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
{
struct rar *rar = (struct rar *)(a->format->data);
const void *h = __archive_read_ahead(a, min, avail);
int ret;
if (avail)
{
if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
*avail = a->archive.read_data_requested;
if (*avail > rar->bytes_remaining)
*avail = (ssize_t)rar->bytes_remaining;
if (*avail < 0)
return NULL;
else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
rar->file_flags & FHD_SPLIT_AFTER)
{
rar->filename_must_match = 1;
ret = archive_read_format_rar_read_header(a, a->entry);
if (ret == (ARCHIVE_EOF))
{
rar->has_endarc_header = 1;
ret = archive_read_format_rar_read_header(a, a->entry);
}
rar->filename_must_match = 0;
if (ret != (ARCHIVE_OK))
return NULL;
return rar_read_ahead(a, min, avail);
}
}
return h;
}
| 168,930 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev,
int type, u32 pid, u32 seq, u32 change,
unsigned int flags, u32 ext_filter_mask)
{
struct ifinfomsg *ifm;
struct nlmsghdr *nlh;
struct rtnl_link_stats64 temp;
const struct rtnl_link_stats64 *stats;
struct nlattr *attr, *af_spec;
struct rtnl_af_ops *af_ops;
struct net_device *upper_dev = netdev_master_upper_dev_get(dev);
ASSERT_RTNL();
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags);
if (nlh == NULL)
return -EMSGSIZE;
ifm = nlmsg_data(nlh);
ifm->ifi_family = AF_UNSPEC;
ifm->__ifi_pad = 0;
ifm->ifi_type = dev->type;
ifm->ifi_index = dev->ifindex;
ifm->ifi_flags = dev_get_flags(dev);
ifm->ifi_change = change;
if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) ||
nla_put_u8(skb, IFLA_OPERSTATE,
netif_running(dev) ? dev->operstate : IF_OPER_DOWN) ||
nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) ||
nla_put_u32(skb, IFLA_MTU, dev->mtu) ||
nla_put_u32(skb, IFLA_GROUP, dev->group) ||
nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) ||
nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) ||
#ifdef CONFIG_RPS
nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) ||
#endif
(dev->ifindex != dev->iflink &&
nla_put_u32(skb, IFLA_LINK, dev->iflink)) ||
(upper_dev &&
nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) ||
nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) ||
(dev->qdisc &&
nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) ||
(dev->ifalias &&
nla_put_string(skb, IFLA_IFALIAS, dev->ifalias)))
goto nla_put_failure;
if (1) {
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
goto nla_put_failure;
}
if (dev->addr_len) {
if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) ||
nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast))
goto nla_put_failure;
}
attr = nla_reserve(skb, IFLA_STATS,
sizeof(struct rtnl_link_stats));
if (attr == NULL)
goto nla_put_failure;
stats = dev_get_stats(dev, &temp);
copy_rtnl_link_stats(nla_data(attr), stats);
attr = nla_reserve(skb, IFLA_STATS64,
sizeof(struct rtnl_link_stats64));
if (attr == NULL)
goto nla_put_failure;
copy_rtnl_link_stats64(nla_data(attr), stats);
if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) &&
nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent)))
goto nla_put_failure;
if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent
&& (ext_filter_mask & RTEXT_FILTER_VF)) {
int i;
struct nlattr *vfinfo, *vf;
int num_vfs = dev_num_vf(dev->dev.parent);
vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST);
if (!vfinfo)
goto nla_put_failure;
for (i = 0; i < num_vfs; i++) {
struct ifla_vf_info ivi;
struct ifla_vf_mac vf_mac;
struct ifla_vf_vlan vf_vlan;
struct ifla_vf_tx_rate vf_tx_rate;
struct ifla_vf_spoofchk vf_spoofchk;
/*
* Not all SR-IOV capable drivers support the
* spoofcheck query. Preset to -1 so the user
* space tool can detect that the driver didn't
* report anything.
*/
ivi.spoofchk = -1;
if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi))
break;
vf_mac.vf =
vf_vlan.vf =
vf_tx_rate.vf =
vf_spoofchk.vf = ivi.vf;
memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac));
vf_vlan.vlan = ivi.vlan;
vf_vlan.qos = ivi.qos;
vf_tx_rate.rate = ivi.tx_rate;
vf_spoofchk.setting = ivi.spoofchk;
vf = nla_nest_start(skb, IFLA_VF_INFO);
if (!vf) {
nla_nest_cancel(skb, vfinfo);
goto nla_put_failure;
}
if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) ||
nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) ||
nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate),
&vf_tx_rate) ||
nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk),
&vf_spoofchk))
goto nla_put_failure;
nla_nest_end(skb, vf);
}
nla_nest_end(skb, vfinfo);
}
if (rtnl_port_fill(skb, dev))
goto nla_put_failure;
if (dev->rtnl_link_ops) {
if (rtnl_link_fill(skb, dev) < 0)
goto nla_put_failure;
}
if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC)))
goto nla_put_failure;
list_for_each_entry(af_ops, &rtnl_af_ops, list) {
if (af_ops->fill_link_af) {
struct nlattr *af;
int err;
if (!(af = nla_nest_start(skb, af_ops->family)))
goto nla_put_failure;
err = af_ops->fill_link_af(skb, dev);
/*
* Caller may return ENODATA to indicate that there
* was no data to be dumped. This is not an error, it
* means we should trim the attribute header and
* continue.
*/
if (err == -ENODATA)
nla_nest_cancel(skb, af);
else if (err < 0)
goto nla_put_failure;
nla_nest_end(skb, af);
}
}
nla_nest_end(skb, af_spec);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
Commit Message: rtnl: fix info leak on RTM_GETLINK request for VF devices
Initialize the mac address buffer with 0 as the driver specific function
will probably not fill the whole buffer. In fact, all in-kernel drivers
fill only ETH_ALEN of the MAX_ADDR_LEN bytes, i.e. 6 of the 32 possible
bytes. Therefore we currently leak 26 bytes of stack memory to userland
via the netlink interface.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev,
int type, u32 pid, u32 seq, u32 change,
unsigned int flags, u32 ext_filter_mask)
{
struct ifinfomsg *ifm;
struct nlmsghdr *nlh;
struct rtnl_link_stats64 temp;
const struct rtnl_link_stats64 *stats;
struct nlattr *attr, *af_spec;
struct rtnl_af_ops *af_ops;
struct net_device *upper_dev = netdev_master_upper_dev_get(dev);
ASSERT_RTNL();
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags);
if (nlh == NULL)
return -EMSGSIZE;
ifm = nlmsg_data(nlh);
ifm->ifi_family = AF_UNSPEC;
ifm->__ifi_pad = 0;
ifm->ifi_type = dev->type;
ifm->ifi_index = dev->ifindex;
ifm->ifi_flags = dev_get_flags(dev);
ifm->ifi_change = change;
if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) ||
nla_put_u8(skb, IFLA_OPERSTATE,
netif_running(dev) ? dev->operstate : IF_OPER_DOWN) ||
nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) ||
nla_put_u32(skb, IFLA_MTU, dev->mtu) ||
nla_put_u32(skb, IFLA_GROUP, dev->group) ||
nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) ||
nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) ||
#ifdef CONFIG_RPS
nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) ||
#endif
(dev->ifindex != dev->iflink &&
nla_put_u32(skb, IFLA_LINK, dev->iflink)) ||
(upper_dev &&
nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) ||
nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) ||
(dev->qdisc &&
nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) ||
(dev->ifalias &&
nla_put_string(skb, IFLA_IFALIAS, dev->ifalias)))
goto nla_put_failure;
if (1) {
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
goto nla_put_failure;
}
if (dev->addr_len) {
if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) ||
nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast))
goto nla_put_failure;
}
attr = nla_reserve(skb, IFLA_STATS,
sizeof(struct rtnl_link_stats));
if (attr == NULL)
goto nla_put_failure;
stats = dev_get_stats(dev, &temp);
copy_rtnl_link_stats(nla_data(attr), stats);
attr = nla_reserve(skb, IFLA_STATS64,
sizeof(struct rtnl_link_stats64));
if (attr == NULL)
goto nla_put_failure;
copy_rtnl_link_stats64(nla_data(attr), stats);
if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) &&
nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent)))
goto nla_put_failure;
if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent
&& (ext_filter_mask & RTEXT_FILTER_VF)) {
int i;
struct nlattr *vfinfo, *vf;
int num_vfs = dev_num_vf(dev->dev.parent);
vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST);
if (!vfinfo)
goto nla_put_failure;
for (i = 0; i < num_vfs; i++) {
struct ifla_vf_info ivi;
struct ifla_vf_mac vf_mac;
struct ifla_vf_vlan vf_vlan;
struct ifla_vf_tx_rate vf_tx_rate;
struct ifla_vf_spoofchk vf_spoofchk;
/*
* Not all SR-IOV capable drivers support the
* spoofcheck query. Preset to -1 so the user
* space tool can detect that the driver didn't
* report anything.
*/
ivi.spoofchk = -1;
memset(ivi.mac, 0, sizeof(ivi.mac));
if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi))
break;
vf_mac.vf =
vf_vlan.vf =
vf_tx_rate.vf =
vf_spoofchk.vf = ivi.vf;
memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac));
vf_vlan.vlan = ivi.vlan;
vf_vlan.qos = ivi.qos;
vf_tx_rate.rate = ivi.tx_rate;
vf_spoofchk.setting = ivi.spoofchk;
vf = nla_nest_start(skb, IFLA_VF_INFO);
if (!vf) {
nla_nest_cancel(skb, vfinfo);
goto nla_put_failure;
}
if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) ||
nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) ||
nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate),
&vf_tx_rate) ||
nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk),
&vf_spoofchk))
goto nla_put_failure;
nla_nest_end(skb, vf);
}
nla_nest_end(skb, vfinfo);
}
if (rtnl_port_fill(skb, dev))
goto nla_put_failure;
if (dev->rtnl_link_ops) {
if (rtnl_link_fill(skb, dev) < 0)
goto nla_put_failure;
}
if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC)))
goto nla_put_failure;
list_for_each_entry(af_ops, &rtnl_af_ops, list) {
if (af_ops->fill_link_af) {
struct nlattr *af;
int err;
if (!(af = nla_nest_start(skb, af_ops->family)))
goto nla_put_failure;
err = af_ops->fill_link_af(skb, dev);
/*
* Caller may return ENODATA to indicate that there
* was no data to be dumped. This is not an error, it
* means we should trim the attribute header and
* continue.
*/
if (err == -ENODATA)
nla_nest_cancel(skb, af);
else if (err < 0)
goto nla_put_failure;
nla_nest_end(skb, af);
}
}
nla_nest_end(skb, af_spec);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
| 166,056 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client)
: InspectorBaseAgent<InspectorResourceAgent>("Network")
, m_pageAgent(pageAgent)
, m_client(client)
, m_frontend(0)
, m_resourcesData(adoptPtr(new NetworkResourcesData()))
, m_isRecalculatingStyle(false)
{
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client)
InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent)
: InspectorBaseAgent<InspectorResourceAgent>("Network")
, m_pageAgent(pageAgent)
, m_frontend(0)
, m_resourcesData(adoptPtr(new NetworkResourcesData()))
, m_isRecalculatingStyle(false)
{
}
| 171,345 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
/* Throw away the key data */
if (key->type->destroy)
key->type->destroy(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
Commit Message: Merge branch 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs
Pull key handling fixes from David Howells:
"Here are two patches, the first of which at least should go upstream
immediately:
(1) Prevent a user-triggerable crash in the keyrings destructor when a
negatively instantiated keyring is garbage collected. I have also
seen this triggered for user type keys.
(2) Prevent the user from using requesting that a keyring be created
and instantiated through an upcall. Doing so is probably safe
since the keyring type ignores the arguments to its instantiation
function - but we probably shouldn't let keyrings be created in
this manner"
* 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs:
KEYS: Don't permit request_key() to construct a new keyring
KEYS: Fix crash when attempt to garbage collect an uninstantiated keyring
CWE ID: CWE-20 | static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
/* Throw away the key data if the key is instantiated */
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) &&
!test_bit(KEY_FLAG_NEGATIVE, &key->flags) &&
key->type->destroy)
key->type->destroy(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
| 166,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
name_link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (!skip_perm_check &&
key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
Commit Message: KEYS: prevent creating a different user's keyrings
It was possible for an unprivileged user to create the user and user
session keyrings for another user. For example:
sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u
keyctl add keyring _uid_ses.4000 "" @u
sleep 15' &
sleep 1
sudo -u '#4000' keyctl describe @u
sudo -u '#4000' keyctl describe @us
This is problematic because these "fake" keyrings won't have the right
permissions. In particular, the user who created them first will own
them and will have full access to them via the possessor permissions,
which can be used to compromise the security of a user's keys:
-4: alswrv-----v------------ 3000 0 keyring: _uid.4000
-5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000
Fix it by marking user and user session keyrings with a flag
KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session
keyring by name, skip all keyrings that don't have the flag set.
Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed")
Cc: <[email protected]> [v2.6.26+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: | struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
struct key *find_keyring_by_name(const char *name, bool uid_keyring)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
name_link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (uid_keyring) {
if (!test_bit(KEY_FLAG_UID_KEYRING,
&keyring->flags))
continue;
} else {
if (key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
}
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
| 169,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
int sx, sy;
int i;
int ncx, ncy, nc, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int vers, fmt;
t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */
int chunkNum = 0;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax = 0;
int bytesPerPixel;
char *compBuf = NULL; /* So we can gdFree it with impunity. */
gdImagePtr im;
/* Get the header */
im =
_gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
&chunkIdx);
if (im == NULL) {
/* No need to free chunkIdx as _gd2CreateFromFile does it for us. */
return 0;
}
bytesPerPixel = im->trueColor ? 4 : 1;
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
/* Allocate buffers */
chunkMax = cs * bytesPerPixel * cs;
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail;
}
GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
};
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Read the data... */
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk %d (%d, %d), y from %d to %d\n",
chunkNum, cx, cy, ylo, yhi));
if (gd2_compressed (fmt)) {
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
GD2_DBG (printf ("Error reading comproessed chunk\n"));
goto fail;
};
chunkPos = 0;
};
for (y = ylo; (y < yhi); y++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
/*GD2_DBG(printf("y=%d: ",y)); */
if (!gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
if (!gdGetInt (&im->tpixels[y][x], in)) {
/*printf("EOF while reading\n"); */
/*gdImageDestroy(im); */
/*return 0; */
im->tpixels[y][x] = 0;
}
} else {
int ch;
if (!gdGetByte (&ch, in)) {
/*printf("EOF while reading\n"); */
/*gdImageDestroy(im); */
/*return 0; */
ch = 0;
}
im->pixels[y][x] = ch;
}
}
} else {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
/* 2.0.1: work around a gcc bug by being verbose.
TBB */
int a = chunkBuf[chunkPos++] << 24;
int r = chunkBuf[chunkPos++] << 16;
int g = chunkBuf[chunkPos++] << 8;
int b = chunkBuf[chunkPos++];
/* 2.0.11: tpixels */
im->tpixels[y][x] = a + r + g + b;
} else {
im->pixels[y][x] = chunkBuf[chunkPos++];
}
};
};
/*GD2_DBG(printf("\n")); */
};
chunkNum++;
};
};
GD2_DBG (printf ("Freeing memory\n"));
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
GD2_DBG (printf ("Done\n"));
return im;
fail:
gdImageDestroy (im);
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
Commit Message: Fix DOS vulnerability in gdImageCreateFromGd2Ctx()
We must not pretend that there are image data if there are none. Instead
we fail reading the image file gracefully.
CWE ID: CWE-20 | BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
int sx, sy;
int i;
int ncx, ncy, nc, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int vers, fmt;
t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */
int chunkNum = 0;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax = 0;
int bytesPerPixel;
char *compBuf = NULL; /* So we can gdFree it with impunity. */
gdImagePtr im;
/* Get the header */
im =
_gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
&chunkIdx);
if (im == NULL) {
/* No need to free chunkIdx as _gd2CreateFromFile does it for us. */
return 0;
}
bytesPerPixel = im->trueColor ? 4 : 1;
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
/* Allocate buffers */
chunkMax = cs * bytesPerPixel * cs;
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail;
}
GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
};
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Read the data... */
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk %d (%d, %d), y from %d to %d\n",
chunkNum, cx, cy, ylo, yhi));
if (gd2_compressed (fmt)) {
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
GD2_DBG (printf ("Error reading comproessed chunk\n"));
goto fail;
};
chunkPos = 0;
};
for (y = ylo; (y < yhi); y++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
/*GD2_DBG(printf("y=%d: ",y)); */
if (!gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
if (!gdGetInt (&im->tpixels[y][x], in)) {
gd_error("gd2: EOF while reading\n");
gdImageDestroy(im);
return NULL;
}
} else {
int ch;
if (!gdGetByte (&ch, in)) {
gd_error("gd2: EOF while reading\n");
gdImageDestroy(im);
return NULL;
}
im->pixels[y][x] = ch;
}
}
} else {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
/* 2.0.1: work around a gcc bug by being verbose.
TBB */
int a = chunkBuf[chunkPos++] << 24;
int r = chunkBuf[chunkPos++] << 16;
int g = chunkBuf[chunkPos++] << 8;
int b = chunkBuf[chunkPos++];
/* 2.0.11: tpixels */
im->tpixels[y][x] = a + r + g + b;
} else {
im->pixels[y][x] = chunkBuf[chunkPos++];
}
};
};
/*GD2_DBG(printf("\n")); */
};
chunkNum++;
};
};
GD2_DBG (printf ("Freeing memory\n"));
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
GD2_DBG (printf ("Done\n"));
return im;
fail:
gdImageDestroy (im);
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
| 168,510 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
int width, int height, int bandpos)
{
int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
int clnpass_cnt = 0;
int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
for (y = 0; y < height; y++)
memset(t1->data[y], 0, width * sizeof(**t1->data));
/* If code-block contains no compressed data: nothing to do. */
if (!cblk->length)
return 0;
for (y = 0; y < height + 2; y++)
memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
cblk->data[cblk->length] = 0xff;
cblk->data[cblk->length+1] = 0xff;
ff_mqc_initdec(&t1->mqc, cblk->data);
while (passno--) {
switch(pass_t) {
case 0:
decode_sigpass(t1, width, height, bpno + 1, bandpos,
bpass_csty_symbol && (clnpass_cnt >= 4),
vert_causal_ctx_csty_symbol);
break;
case 1:
decode_refpass(t1, width, height, bpno + 1);
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
case 2:
decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
vert_causal_ctx_csty_symbol);
clnpass_cnt = clnpass_cnt + 1;
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
}
pass_t++;
if (pass_t == 3) {
bpno--;
pass_t = 0;
}
}
return 0;
}
Commit Message: jpeg2000: check log2_cblk dimensions
Fixes out of array access
Fixes Ticket2895
Found-by: Piotr Bandurski <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
int width, int height, int bandpos)
{
int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
int clnpass_cnt = 0;
int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
av_assert0(width <= JPEG2000_MAX_CBLKW);
av_assert0(height <= JPEG2000_MAX_CBLKH);
for (y = 0; y < height; y++)
memset(t1->data[y], 0, width * sizeof(**t1->data));
/* If code-block contains no compressed data: nothing to do. */
if (!cblk->length)
return 0;
for (y = 0; y < height + 2; y++)
memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
cblk->data[cblk->length] = 0xff;
cblk->data[cblk->length+1] = 0xff;
ff_mqc_initdec(&t1->mqc, cblk->data);
while (passno--) {
switch(pass_t) {
case 0:
decode_sigpass(t1, width, height, bpno + 1, bandpos,
bpass_csty_symbol && (clnpass_cnt >= 4),
vert_causal_ctx_csty_symbol);
break;
case 1:
decode_refpass(t1, width, height, bpno + 1);
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
case 2:
decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
vert_causal_ctx_csty_symbol);
clnpass_cnt = clnpass_cnt + 1;
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
}
pass_t++;
if (pass_t == 3) {
bpno--;
pass_t = 0;
}
}
return 0;
}
| 165,919 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::ConfirmPairing() {
if (!agent_.get() || confirmation_callback_.is_null())
return;
confirmation_callback_.Run(SUCCESS);
confirmation_callback_.Reset();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::ConfirmPairing() {
if (!pairing_context_.get())
return;
pairing_context_->ConfirmPairing();
}
| 171,220 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sock *unix_create1(struct net *net, struct socket *sock, int kern)
{
struct sock *sk = NULL;
struct unix_sock *u;
atomic_long_inc(&unix_nr_socks);
if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
goto out;
sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
lockdep_set_class(&sk->sk_receive_queue.lock,
&af_unix_sk_receive_queue_lock_key);
sk->sk_write_space = unix_write_space;
sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
sk->sk_destruct = unix_sock_destructor;
u = unix_sk(sk);
u->path.dentry = NULL;
u->path.mnt = NULL;
spin_lock_init(&u->lock);
atomic_long_set(&u->inflight, 0);
INIT_LIST_HEAD(&u->link);
mutex_init(&u->readlock); /* single task reading lock */
init_waitqueue_head(&u->peer_wait);
unix_insert_socket(unix_sockets_unbound(sk), sk);
out:
if (sk == NULL)
atomic_long_dec(&unix_nr_socks);
else {
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
local_bh_enable();
}
return sk;
}
Commit Message: unix: avoid use-after-free in ep_remove_wait_queue
Rainer Weikusat <[email protected]> writes:
An AF_UNIX datagram socket being the client in an n:1 association with
some server socket is only allowed to send messages to the server if the
receive queue of this socket contains at most sk_max_ack_backlog
datagrams. This implies that prospective writers might be forced to go
to sleep despite none of the message presently enqueued on the server
receive queue were sent by them. In order to ensure that these will be
woken up once space becomes again available, the present unix_dgram_poll
routine does a second sock_poll_wait call with the peer_wait wait queue
of the server socket as queue argument (unix_dgram_recvmsg does a wake
up on this queue after a datagram was received). This is inherently
problematic because the server socket is only guaranteed to remain alive
for as long as the client still holds a reference to it. In case the
connection is dissolved via connect or by the dead peer detection logic
in unix_dgram_sendmsg, the server socket may be freed despite "the
polling mechanism" (in particular, epoll) still has a pointer to the
corresponding peer_wait queue. There's no way to forcibly deregister a
wait queue with epoll.
Based on an idea by Jason Baron, the patch below changes the code such
that a wait_queue_t belonging to the client socket is enqueued on the
peer_wait queue of the server whenever the peer receive queue full
condition is detected by either a sendmsg or a poll. A wake up on the
peer queue is then relayed to the ordinary wait queue of the client
socket via wake function. The connection to the peer wait queue is again
dissolved if either a wake up is about to be relayed or the client
socket reconnects or a dead peer is detected or the client socket is
itself closed. This enables removing the second sock_poll_wait from
unix_dgram_poll, thus avoiding the use-after-free, while still ensuring
that no blocked writer sleeps forever.
Signed-off-by: Rainer Weikusat <[email protected]>
Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets")
Reviewed-by: Jason Baron <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static struct sock *unix_create1(struct net *net, struct socket *sock, int kern)
{
struct sock *sk = NULL;
struct unix_sock *u;
atomic_long_inc(&unix_nr_socks);
if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
goto out;
sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
lockdep_set_class(&sk->sk_receive_queue.lock,
&af_unix_sk_receive_queue_lock_key);
sk->sk_write_space = unix_write_space;
sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
sk->sk_destruct = unix_sock_destructor;
u = unix_sk(sk);
u->path.dentry = NULL;
u->path.mnt = NULL;
spin_lock_init(&u->lock);
atomic_long_set(&u->inflight, 0);
INIT_LIST_HEAD(&u->link);
mutex_init(&u->readlock); /* single task reading lock */
init_waitqueue_head(&u->peer_wait);
init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay);
unix_insert_socket(unix_sockets_unbound(sk), sk);
out:
if (sk == NULL)
atomic_long_dec(&unix_nr_socks);
else {
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
local_bh_enable();
}
return sk;
}
| 166,833 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
| 167,948 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nalm_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
Bool rle, large_size;
u32 entry_count;
if (!data) {
fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n");
fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n");
fprintf(trace, "</NALUMap>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size);
while (entry_count) {
u32 ID;
fprintf(trace, "<NALUMapEntry ");
if (rle) {
u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "NALU_startNumber=\"%d\" ", start_num);
}
ID = gf_bs_read_u16(bs);
fprintf(trace, "groupID=\"%d\"/>\n", ID);
entry_count--;
}
gf_bs_del(bs);
fprintf(trace, "</NALUMap>\n");
return;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | static void nalm_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
Bool rle, large_size;
u32 entry_count;
if (!data) {
fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n");
fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n");
fprintf(trace, "</NALUMap>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size);
while (entry_count) {
u32 ID;
fprintf(trace, "<NALUMapEntry ");
if (rle) {
u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "NALU_startNumber=\"%d\" ", start_num);
}
ID = gf_bs_read_u16(bs);
fprintf(trace, "groupID=\"%d\"/>\n", ID);
entry_count--;
}
gf_bs_del(bs);
fprintf(trace, "</NALUMap>\n");
return;
}
| 169,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_write_BOOLEAN(struct asn1_data *data, bool v)
{
asn1_push_tag(data, ASN1_BOOLEAN);
asn1_write_uint8(data, v ? 0xFF : 0);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399 | bool asn1_write_BOOLEAN(struct asn1_data *data, bool v)
{
if (!asn1_push_tag(data, ASN1_BOOLEAN)) return false;
if (!asn1_write_uint8(data, v ? 0xFF : 0)) return false;
return asn1_pop_tag(data);
}
| 164,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return 0;
if ( c->prev )
c->prev->next = c->next;
if ( c->next ) c->next->prev = c->prev;
if ( c == array->child )
array->child = c->next;
c->prev = c->next = 0;
return c;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
| 167,284 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nl80211_start_sched_scan(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_sched_scan_request *request;
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
u32 interval;
enum ieee80211_band band;
size_t ie_len;
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) ||
!rdev->ops->sched_scan_start)
return -EOPNOTSUPP;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (rdev->sched_scan_req)
return -EINPROGRESS;
if (!info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL])
return -EINVAL;
interval = nla_get_u32(info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL]);
if (interval == 0)
return -EINVAL;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES],
tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp) {
if (request->ssids[i].ssid_len >
IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->ssids[i].ssid, nla_data(attr),
nla_len(attr));
request->ssids[i].ssid_len = nla_len(attr);
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
request->interval = interval;
err = rdev->ops->sched_scan_start(&rdev->wiphy, dev, request);
if (!err) {
rdev->sched_scan_req = request;
nl80211_send_sched_scan(rdev, dev,
NL80211_CMD_START_SCHED_SCAN);
goto out;
}
out_free:
kfree(request);
out:
return err;
}
Commit Message: nl80211: fix check for valid SSID size in scan operations
In both trigger_scan and sched_scan operations, we were checking for
the SSID length before assigning the value correctly. Since the
memory was just kzalloc'ed, the check was always failing and SSID with
over 32 characters were allowed to go through.
This was causing a buffer overflow when copying the actual SSID to the
proper place.
This bug has been there since 2.6.29-rc4.
Cc: [email protected]
Signed-off-by: Luciano Coelho <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-119 | static int nl80211_start_sched_scan(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_sched_scan_request *request;
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
u32 interval;
enum ieee80211_band band;
size_t ie_len;
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) ||
!rdev->ops->sched_scan_start)
return -EOPNOTSUPP;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (rdev->sched_scan_req)
return -EINPROGRESS;
if (!info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL])
return -EINVAL;
interval = nla_get_u32(info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL]);
if (interval == 0)
return -EINVAL;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES],
tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp) {
request->ssids[i].ssid_len = nla_len(attr);
if (request->ssids[i].ssid_len >
IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->ssids[i].ssid, nla_data(attr),
nla_len(attr));
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
request->interval = interval;
err = rdev->ops->sched_scan_start(&rdev->wiphy, dev, request);
if (!err) {
rdev->sched_scan_req = request;
nl80211_send_sched_scan(rdev, dev,
NL80211_CMD_START_SCHED_SCAN);
goto out;
}
out_free:
kfree(request);
out:
return err;
}
| 165,857 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
entry = entry->next();
if (!to_doom->InUse())
to_doom->Doom();
}
}
Commit Message: [MemCache] Fix bug while iterating LRU list in eviction
It was possible to reanalyze a previously doomed entry.
Bug: 827492
Change-Id: I5d34d2ae87c96e0d2099e926e6eb2c1b30b01d63
Reviewed-on: https://chromium-review.googlesource.com/987919
Commit-Queue: Josh Karlin <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547236}
CWE ID: CWE-416 | void MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
do {
entry = entry->next();
// It's possible that entry now points to a child of to_doom, and the
// parent is about to be deleted. Skip past any child entries.
} while (entry != lru_list_.end() && entry->value()->parent() == to_doom);
if (!to_doom->InUse())
to_doom->Doom();
}
}
| 172,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_inquire_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
OM_uint32 ret = GSS_S_COMPLETE;
ret = gss_inquire_context(minor_status,
context_handle,
src_name,
targ_name,
lifetime_rec,
mech_type,
ctx_flags,
locally_initiated,
opened);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_inquire_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
OM_uint32 ret = GSS_S_COMPLETE;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (targ_name != NULL)
*targ_name = GSS_C_NO_NAME;
if (lifetime_rec != NULL)
*lifetime_rec = 0;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_spnego;
if (ctx_flags != NULL)
*ctx_flags = 0;
if (locally_initiated != NULL)
*locally_initiated = sc->initiate;
if (opened != NULL)
*opened = sc->opened;
if (sc->ctx_handle != GSS_C_NO_CONTEXT) {
ret = gss_inquire_context(minor_status, sc->ctx_handle,
src_name, targ_name, lifetime_rec,
mech_type, ctx_flags, NULL, NULL);
}
if (!sc->opened) {
/*
* We are still doing SPNEGO negotiation, so report SPNEGO as
* the OID. After negotiation is complete we will report the
* underlying mechanism OID.
*/
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_spnego;
/*
* Remove flags we don't support with partially-established
* contexts. (Change this to keep GSS_C_TRANS_FLAG if we add
* support for exporting partial SPNEGO contexts.)
*/
if (ctx_flags != NULL) {
*ctx_flags &= ~GSS_C_PROT_READY_FLAG;
*ctx_flags &= ~GSS_C_TRANS_FLAG;
}
}
return (ret);
}
| 166,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: int snmp_version(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
if (*(unsigned char *)data > 1)
return -ENOTSUPP;
return 1;
}
Commit Message: netfilter: nf_nat_snmp_basic: add missing length checks in ASN.1 cbs
The generic ASN.1 decoder infrastructure doesn't guarantee that callbacks
will get as much data as they expect; callbacks have to check the `datalen`
parameter before looking at `data`. Make sure that snmp_version() and
snmp_helper() don't read/write beyond the end of the packet data.
(Also move the assignment to `pdata` down below the check to make it clear
that it isn't necessarily a pointer we can use before the `datalen` check.)
Fixes: cc2d58634e0f ("netfilter: nf_nat_snmp_basic: use asn1 decoder library")
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-129 | int snmp_version(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
if (datalen != 1)
return -EINVAL;
if (*(unsigned char *)data > 1)
return -ENOTSUPP;
return 1;
}
| 169,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t socket_bytes_available(const socket_t *socket) {
assert(socket != NULL);
int size = 0;
if (ioctl(socket->fd, FIONREAD, &size) == -1)
return -1;
return size;
}
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 | ssize_t socket_bytes_available(const socket_t *socket) {
assert(socket != NULL);
int size = 0;
if (TEMP_FAILURE_RETRY(ioctl(socket->fd, FIONREAD, &size)) == -1)
return -1;
return size;
}
| 173,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: std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin(
Profile* profile,
const url::Origin& origin) {
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
EXPECT_TRUE(data_store);
std::unique_ptr<SiteCharacteristicsDataReader> reader =
data_store->GetReaderForOrigin(origin);
internal::LocalSiteCharacteristicsDataImpl* impl =
static_cast<LocalSiteCharacteristicsDataReader*>(reader.get())
->impl_for_testing()
.get();
while (!impl->site_characteristics_for_testing().IsInitialized())
base::RunLoop().RunUntilIdle();
return reader;
}
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: | std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin(
Profile* profile,
const url::Origin& origin) {
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
EXPECT_TRUE(data_store);
std::unique_ptr<SiteCharacteristicsDataReader> reader =
data_store->GetReaderForOrigin(origin);
const internal::LocalSiteCharacteristicsDataImpl* impl =
static_cast<LocalSiteCharacteristicsDataReader*>(reader.get())
->impl_for_testing();
while (!impl->site_characteristics_for_testing().IsInitialized())
base::RunLoop().RunUntilIdle();
return reader;
}
| 172,215 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __u32 dccp_v6_init_sequence(struct sk_buff *skb)
{
return secure_dccpv6_sequence_number(ipv6_hdr(skb)->daddr.s6_addr32,
ipv6_hdr(skb)->saddr.s6_addr32,
dccp_hdr(skb)->dccph_dport,
dccp_hdr(skb)->dccph_sport );
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static inline __u32 dccp_v6_init_sequence(struct sk_buff *skb)
static inline __u64 dccp_v6_init_sequence(struct sk_buff *skb)
{
return secure_dccpv6_sequence_number(ipv6_hdr(skb)->daddr.s6_addr32,
ipv6_hdr(skb)->saddr.s6_addr32,
dccp_hdr(skb)->dccph_dport,
dccp_hdr(skb)->dccph_sport );
}
| 165,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 struct mobj *alloc_ta_mem(size_t size)
{
#ifdef CFG_PAGED_USER_TA
return mobj_paged_alloc(size);
#else
struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);
if (mobj)
memset(mobj_get_va(mobj, 0), 0, size);
return mobj;
#endif
}
Commit Message: core: clear the entire TA area
Previously we cleared (memset to zero) the size corresponding to code
and data segments, however the allocation for the TA is made on the
granularity of the memory pool, meaning that we did not clear all memory
and because of that we could potentially leak code and data of a
previous loaded TA.
Fixes: OP-TEE-2018-0006: "Potential disclosure of previously loaded TA
code and data"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Suggested-by: Jens Wiklander <[email protected]>
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-189 | static struct mobj *alloc_ta_mem(size_t size)
{
#ifdef CFG_PAGED_USER_TA
return mobj_paged_alloc(size);
#else
struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);
if (mobj) {
size_t granularity = BIT(tee_mm_sec_ddr.shift);
/* Round up to allocation granularity size */
memset(mobj_get_va(mobj, 0), 0, ROUNDUP(size, granularity));
}
return mobj;
#endif
}
| 169,472 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SecureProxyChecker::CheckIfSecureProxyIsAllowed(
SecureProxyCheckerCallback fetcher_callback) {
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation(
"data_reduction_proxy_secure_proxy_check", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Sends a request to the Data Reduction Proxy server. Proceeds "
"with using a secure connection to the proxy only if the "
"response is not blocked or modified by an intermediary."
trigger:
"A request can be sent whenever the browser is determining how "
"to configure its connection to the data reduction proxy. This "
"happens on startup and network changes."
data: "A specific URL, not related to user data."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via the 'Data Saver' "
"setting. Data Saver is not available on iOS, and on desktop "
"it is enabled by installing the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = params::GetSecureProxyCheckURL();
resource_request->load_flags =
net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY;
resource_request->allow_credentials = false;
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE |
network::SimpleURLLoader::RETRY_ON_5XX);
url_loader_->SetOnRedirectCallback(base::BindRepeating(
&SecureProxyChecker::OnURLLoaderRedirect, base::Unretained(this)));
fetcher_callback_ = fetcher_callback;
secure_proxy_check_start_time_ = base::Time::Now();
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&SecureProxyChecker::OnURLLoadComplete,
base::Unretained(this)));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | void SecureProxyChecker::CheckIfSecureProxyIsAllowed(
SecureProxyCheckerCallback fetcher_callback) {
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation(
"data_reduction_proxy_secure_proxy_check", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Sends a request to the Data Reduction Proxy server. Proceeds "
"with using a secure connection to the proxy only if the "
"response is not blocked or modified by an intermediary."
trigger:
"A request can be sent whenever the browser is determining how "
"to configure its connection to the data reduction proxy. This "
"happens on startup and network changes."
data: "A specific URL, not related to user data."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via the 'Data Saver' "
"setting. Data Saver is not available on iOS, and on desktop "
"it is enabled by installing the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = params::GetSecureProxyCheckURL();
resource_request->load_flags =
net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY;
resource_request->allow_credentials = false;
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE |
network::SimpleURLLoader::RETRY_ON_5XX);
url_loader_->SetOnRedirectCallback(base::BindRepeating(
&SecureProxyChecker::OnURLLoaderRedirect, base::Unretained(this)));
fetcher_callback_ = fetcher_callback;
secure_proxy_check_start_time_ = base::Time::Now();
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&SecureProxyChecker::OnURLLoadComplete,
base::Unretained(this)));
}
| 172,422 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
if( profile == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
*flags = 0;
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
Commit Message: Improve behaviour on fatal errors
If we didn't walk the whole chain, then there may be any kind of errors in the
part of the chain we didn't check, so setting all flags looks like the safe
thing to do.
CWE ID: CWE-287 | int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
*flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
}
exit:
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
| 167,783 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Edition::ExpandAtomsArray()
{
if (m_atoms_size > m_atoms_count)
return true; // nothing else to do
const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size;
Atom* const atoms = new (std::nothrow) Atom[size];
if (atoms == NULL)
return false;
for (int idx = 0; idx < m_atoms_count; ++idx)
{
m_atoms[idx].ShallowCopy(atoms[idx]);
}
delete[] m_atoms;
m_atoms = atoms;
m_atoms_size = size;
return true;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool Chapters::Edition::ExpandAtomsArray()
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
| 174,274 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) {
if (buffer == 0) {
return NULL;
}
Mutex::Autolock autoLock(mBufferIDLock);
ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer);
if (index < 0) {
CLOGW("findBufferHeader: buffer %u not found", buffer);
return NULL;
}
return mBufferIDToBufferHeader.valueAt(index);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) {
OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(
OMX::buffer_id buffer, OMX_U32 portIndex) {
if (buffer == 0) {
return NULL;
}
Mutex::Autolock autoLock(mBufferIDLock);
ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer);
if (index < 0) {
CLOGW("findBufferHeader: buffer %u not found", buffer);
return NULL;
}
OMX_BUFFERHEADERTYPE *header = mBufferIDToBufferHeader.valueAt(index);
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
if (buffer_meta->getPortIndex() != portIndex) {
CLOGW("findBufferHeader: buffer %u found but with incorrect port index.", buffer);
android_errorWriteLog(0x534e4554, "28816827");
return NULL;
}
return header;
}
| 173,528 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mojom::AppPtr AppControllerImpl::CreateAppPtr(const apps::AppUpdate& update) {
auto app = chromeos::kiosk_next_home::mojom::App::New();
app->app_id = update.AppId();
app->type = update.AppType();
app->display_name = update.Name();
app->readiness = update.Readiness();
if (app->type == apps::mojom::AppType::kArc) {
app->android_package_name = MaybeGetAndroidPackageName(app->app_id);
}
return app;
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | mojom::AppPtr AppControllerImpl::CreateAppPtr(const apps::AppUpdate& update) {
mojom::AppPtr AppControllerService::CreateAppPtr(
const apps::AppUpdate& update) {
auto app = chromeos::kiosk_next_home::mojom::App::New();
app->app_id = update.AppId();
app->type = update.AppType();
app->display_name = update.Name();
app->readiness = update.Readiness();
if (app->type == apps::mojom::AppType::kArc) {
app->android_package_name = MaybeGetAndroidPackageName(app->app_id);
}
return app;
}
| 172,081 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Edition::Clear()
{
while (m_atoms_count > 0)
{
Atom& a = m_atoms[--m_atoms_count];
a.Clear();
}
delete[] m_atoms;
m_atoms = NULL;
m_atoms_size = 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Chapters::Edition::Clear()
while (m_displays_count > 0) {
Display& d = m_displays[--m_displays_count];
d.Clear();
}
delete[] m_displays;
m_displays = NULL;
m_displays_size = 0;
}
long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) { // Display ID
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
} else if (id == 0x1654) { // StringUID ID
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
} else if (id == 0x33C4) { // UID ID
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (val < 0) // error
return status;
m_uid = static_cast<unsigned long long>(val);
} else if (id == 0x11) { // TimeStart ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
} else if (id == 0x12) { // TimeEnd ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
| 174,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
{
struct session_state *state = ssh->state;
struct sshbuf *b;
int r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if (state->compression_in_started) {
if ((r = sshbuf_put_string(b, &state->compression_in_stream,
sizeof(state->compression_in_stream))) != 0)
goto out;
} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
goto out;
if (state->compression_out_started) {
if ((r = sshbuf_put_string(b, &state->compression_out_stream,
sizeof(state->compression_out_stream))) != 0)
goto out;
} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
| 168,652 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
Commit Message: * libtiff/tif_pixarlog.c: fix potential buffer write overrun in
PixarLogDecode() on corrupted/unexpected images (reported by Mathias Svensson)
CWE ID: CWE-787 | PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
/* Check that we will not fill more than what was allocated */
if (sp->stream.avail_out > sp->tbuf_size)
{
TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
| 169,449 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaStreamManager::OpenDevice(int render_process_id,
int render_frame_id,
int page_request_id,
const std::string& device_id,
MediaStreamType type,
MediaDeviceSaltAndOrigin salt_and_origin,
OpenDeviceCallback open_device_cb,
DeviceStoppedCallback device_stopped_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
DVLOG(1) << "OpenDevice ({page_request_id = " << page_request_id << "})";
StreamControls controls;
if (IsAudioInputMediaType(type)) {
controls.audio.requested = true;
controls.audio.stream_type = type;
controls.audio.device_id = device_id;
} else if (IsVideoInputMediaType(type)) {
controls.video.requested = true;
controls.video.stream_type = type;
controls.video.device_id = device_id;
} else {
NOTREACHED();
}
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id,
false /* user gesture */, MEDIA_OPEN_DEVICE_PEPPER_ONLY, controls,
std::move(salt_and_origin), std::move(device_stopped_cb));
const std::string& label = AddRequest(request);
request->open_device_cb = std::move(open_device_cb);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamManager::OpenDevice(int render_process_id,
int render_frame_id,
int requester_id,
int page_request_id,
const std::string& device_id,
MediaStreamType type,
MediaDeviceSaltAndOrigin salt_and_origin,
OpenDeviceCallback open_device_cb,
DeviceStoppedCallback device_stopped_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
DVLOG(1) << "OpenDevice ({page_request_id = " << page_request_id << "})";
StreamControls controls;
if (IsAudioInputMediaType(type)) {
controls.audio.requested = true;
controls.audio.stream_type = type;
controls.audio.device_id = device_id;
} else if (IsVideoInputMediaType(type)) {
controls.video.requested = true;
controls.video.stream_type = type;
controls.video.device_id = device_id;
} else {
NOTREACHED();
}
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, requester_id, page_request_id,
false /* user gesture */, MEDIA_OPEN_DEVICE_PEPPER_ONLY, controls,
std::move(salt_and_origin), std::move(device_stopped_cb));
const std::string& label = AddRequest(request);
request->open_device_cb = std::move(open_device_cb);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
}
| 173,105 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HTMLFormControlElement::isAutofocusable() const
{
if (!fastHasAttribute(autofocusAttr))
return false;
if (hasTagName(inputTag))
return !toHTMLInputElement(this)->isInputTypeHidden();
if (hasTagName(selectTag))
return true;
if (hasTagName(keygenTag))
return true;
if (hasTagName(buttonTag))
return true;
if (hasTagName(textareaTag))
return true;
return false;
}
Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment.
This virtual function should return true if the form control can hanlde
'autofocucs' attribute if it is specified.
Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent
because interactiveness is required for autofocus capability.
BUG=none
TEST=none; no behavior changes.
Review URL: https://codereview.chromium.org/143343003
git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | bool HTMLFormControlElement::isAutofocusable() const
bool HTMLFormControlElement::supportsAutofocus() const
{
return false;
}
| 171,343 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fwnet_receive_broadcast(struct fw_iso_context *context,
u32 cycle, size_t header_length, void *header, void *data)
{
struct fwnet_device *dev;
struct fw_iso_packet packet;
__be16 *hdr_ptr;
__be32 *buf_ptr;
int retval;
u32 length;
u16 source_node_id;
u32 specifier_id;
u32 ver;
unsigned long offset;
unsigned long flags;
dev = data;
hdr_ptr = header;
length = be16_to_cpup(hdr_ptr);
spin_lock_irqsave(&dev->lock, flags);
offset = dev->rcv_buffer_size * dev->broadcast_rcv_next_ptr;
buf_ptr = dev->broadcast_rcv_buffer_ptrs[dev->broadcast_rcv_next_ptr++];
if (dev->broadcast_rcv_next_ptr == dev->num_broadcast_rcv_ptrs)
dev->broadcast_rcv_next_ptr = 0;
spin_unlock_irqrestore(&dev->lock, flags);
specifier_id = (be32_to_cpu(buf_ptr[0]) & 0xffff) << 8
| (be32_to_cpu(buf_ptr[1]) & 0xff000000) >> 24;
ver = be32_to_cpu(buf_ptr[1]) & 0xffffff;
source_node_id = be32_to_cpu(buf_ptr[0]) >> 16;
if (specifier_id == IANA_SPECIFIER_ID &&
(ver == RFC2734_SW_VERSION
#if IS_ENABLED(CONFIG_IPV6)
|| ver == RFC3146_SW_VERSION
#endif
)) {
buf_ptr += 2;
length -= IEEE1394_GASP_HDR_SIZE;
fwnet_incoming_packet(dev, buf_ptr, length, source_node_id,
context->card->generation, true);
}
packet.payload_length = dev->rcv_buffer_size;
packet.interrupt = 1;
packet.skip = 0;
packet.tag = 3;
packet.sy = 0;
packet.header_length = IEEE1394_GASP_HDR_SIZE;
spin_lock_irqsave(&dev->lock, flags);
retval = fw_iso_context_queue(dev->broadcast_rcv_context, &packet,
&dev->broadcast_rcv_buffer, offset);
spin_unlock_irqrestore(&dev->lock, flags);
if (retval >= 0)
fw_iso_context_queue_flush(dev->broadcast_rcv_context);
else
dev_err(&dev->netdev->dev, "requeue failed\n");
}
Commit Message: firewire: net: guard against rx buffer overflows
The IP-over-1394 driver firewire-net lacked input validation when
handling incoming fragmented datagrams. A maliciously formed fragment
with a respectively large datagram_offset would cause a memcpy past the
datagram buffer.
So, drop any packets carrying a fragment with offset + length larger
than datagram_size.
In addition, ensure that
- GASP header, unfragmented encapsulation header, or fragment
encapsulation header actually exists before we access it,
- the encapsulated datagram or fragment is of nonzero size.
Reported-by: Eyal Itkin <[email protected]>
Reviewed-by: Eyal Itkin <[email protected]>
Fixes: CVE 2016-8633
Cc: [email protected]
Signed-off-by: Stefan Richter <[email protected]>
CWE ID: CWE-119 | static void fwnet_receive_broadcast(struct fw_iso_context *context,
u32 cycle, size_t header_length, void *header, void *data)
{
struct fwnet_device *dev;
struct fw_iso_packet packet;
__be16 *hdr_ptr;
__be32 *buf_ptr;
int retval;
u32 length;
unsigned long offset;
unsigned long flags;
dev = data;
hdr_ptr = header;
length = be16_to_cpup(hdr_ptr);
spin_lock_irqsave(&dev->lock, flags);
offset = dev->rcv_buffer_size * dev->broadcast_rcv_next_ptr;
buf_ptr = dev->broadcast_rcv_buffer_ptrs[dev->broadcast_rcv_next_ptr++];
if (dev->broadcast_rcv_next_ptr == dev->num_broadcast_rcv_ptrs)
dev->broadcast_rcv_next_ptr = 0;
spin_unlock_irqrestore(&dev->lock, flags);
if (length > IEEE1394_GASP_HDR_SIZE &&
gasp_specifier_id(buf_ptr) == IANA_SPECIFIER_ID &&
(gasp_version(buf_ptr) == RFC2734_SW_VERSION
#if IS_ENABLED(CONFIG_IPV6)
|| gasp_version(buf_ptr) == RFC3146_SW_VERSION
#endif
))
fwnet_incoming_packet(dev, buf_ptr + 2,
length - IEEE1394_GASP_HDR_SIZE,
gasp_source_id(buf_ptr),
context->card->generation, true);
packet.payload_length = dev->rcv_buffer_size;
packet.interrupt = 1;
packet.skip = 0;
packet.tag = 3;
packet.sy = 0;
packet.header_length = IEEE1394_GASP_HDR_SIZE;
spin_lock_irqsave(&dev->lock, flags);
retval = fw_iso_context_queue(dev->broadcast_rcv_context, &packet,
&dev->broadcast_rcv_buffer, offset);
spin_unlock_irqrestore(&dev->lock, flags);
if (retval >= 0)
fw_iso_context_queue_flush(dev->broadcast_rcv_context);
else
dev_err(&dev->netdev->dev, "requeue failed\n");
}
| 166,917 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebGLRenderingContextBase::ValidateHTMLImageElement(
const SecurityOrigin* security_origin,
const char* function_name,
HTMLImageElement* image,
ExceptionState& exception_state) {
if (!image || !image->CachedImage()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image");
return false;
}
const KURL& url = image->CachedImage()->GetResponse().Url();
if (url.IsNull() || url.IsEmpty() || !url.IsValid()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image");
return false;
}
if (WouldTaintOrigin(image, security_origin)) {
exception_state.ThrowSecurityError("The cross-origin image at " +
url.ElidedString() +
" may not be loaded.");
return false;
}
return true;
}
Commit Message: Simplify WebGL error message
The WebGL exception message text contains the full URL of a blocked
cross-origin resource. It should instead contain only a generic notice.
Bug: 799847
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I3a7f00462a4643c41882f2ee7e7767e6d631557e
Reviewed-on: https://chromium-review.googlesource.com/854986
Reviewed-by: Brandon Jones <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528458}
CWE ID: CWE-20 | bool WebGLRenderingContextBase::ValidateHTMLImageElement(
const SecurityOrigin* security_origin,
const char* function_name,
HTMLImageElement* image,
ExceptionState& exception_state) {
if (!image || !image->CachedImage()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image");
return false;
}
const KURL& url = image->CachedImage()->GetResponse().Url();
if (url.IsNull() || url.IsEmpty() || !url.IsValid()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image");
return false;
}
if (WouldTaintOrigin(image, security_origin)) {
exception_state.ThrowSecurityError(
"The image element contains cross-origin data, and may not be loaded.");
return false;
}
return true;
}
| 172,690 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileInfo, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int path_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
if (path_len && path_len < intern->file_name_len) {
RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1);
} else {
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileInfo, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int path_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
if (path_len && path_len < intern->file_name_len) {
RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1);
} else {
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
}
| 167,032 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_)
{
register const struct ip6_rthdr *dp;
register const struct ip6_rthdr0 *dp0;
register const u_char *ep;
int i, len;
register const struct in6_addr *addr;
dp = (const struct ip6_rthdr *)bp;
len = dp->ip6r_len;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->ip6r_segleft);
ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/
ND_PRINT((ndo, ", type=%d", dp->ip6r_type));
ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft));
switch (dp->ip6r_type) {
case IPV6_RTHDR_TYPE_0:
case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */
dp0 = (const struct ip6_rthdr0 *)dp;
ND_TCHECK(dp0->ip6r0_reserved);
if (dp0->ip6r0_reserved || ndo->ndo_vflag) {
ND_PRINT((ndo, ", rsv=0x%0x",
EXTRACT_32BITS(&dp0->ip6r0_reserved)));
}
if (len % 2 == 1)
goto trunc;
len >>= 1;
addr = &dp0->ip6r0_addr[0];
for (i = 0; i < len; i++) {
if ((const u_char *)(addr + 1) > ep)
goto trunc;
ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr)));
addr++;
}
/*(*/
ND_PRINT((ndo, ") "));
return((dp0->ip6r0_len + 1) << 3);
break;
default:
goto trunc;
break;
}
trunc:
ND_PRINT((ndo, "[|srcrt]"));
return -1;
}
Commit Message: CVE-2017-13725/IPv6 R.H.: Check for the existence of all fields before fetching them.
Don't fetch the length field from the header until after we've checked
for the existence of a field at or after that field.
(Found by code inspection, not by a capture.)
CWE ID: CWE-125 | rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_)
{
register const struct ip6_rthdr *dp;
register const struct ip6_rthdr0 *dp0;
register const u_char *ep;
int i, len;
register const struct in6_addr *addr;
dp = (const struct ip6_rthdr *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->ip6r_segleft);
len = dp->ip6r_len;
ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/
ND_PRINT((ndo, ", type=%d", dp->ip6r_type));
ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft));
switch (dp->ip6r_type) {
case IPV6_RTHDR_TYPE_0:
case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */
dp0 = (const struct ip6_rthdr0 *)dp;
ND_TCHECK(dp0->ip6r0_reserved);
if (dp0->ip6r0_reserved || ndo->ndo_vflag) {
ND_PRINT((ndo, ", rsv=0x%0x",
EXTRACT_32BITS(&dp0->ip6r0_reserved)));
}
if (len % 2 == 1)
goto trunc;
len >>= 1;
addr = &dp0->ip6r0_addr[0];
for (i = 0; i < len; i++) {
if ((const u_char *)(addr + 1) > ep)
goto trunc;
ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr)));
addr++;
}
/*(*/
ND_PRINT((ndo, ") "));
return((dp0->ip6r0_len + 1) << 3);
break;
default:
goto trunc;
break;
}
trunc:
ND_PRINT((ndo, "[|srcrt]"));
return -1;
}
| 167,784 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType ConcatenateImages(int argc,char **argv,
ExceptionInfo *exception )
{
FILE
*input,
*output;
int
c;
register ssize_t
i;
if (ExpandFilenames(&argc,&argv) == MagickFalse)
ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
output=fopen_utf8(argv[argc-1],"wb");
if (output == (FILE *) NULL) {
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]);
return(MagickFalse);
}
for (i=2; i < (ssize_t) (argc-1); i++) {
#if 0
fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]);
#endif
input=fopen_utf8(argv[i],"rb");
if (input == (FILE *) NULL) {
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
continue;
}
for (c=fgetc(input); c != EOF; c=fgetc(input))
(void) fputc((char) c,output);
(void) fclose(input);
(void) remove_utf8(argv[i]);
}
(void) fclose(output);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/196
CWE ID: CWE-20 | static MagickBooleanType ConcatenateImages(int argc,char **argv,
ExceptionInfo *exception )
{
FILE
*input,
*output;
MagickBooleanType
status;
int
c;
register ssize_t
i;
if (ExpandFilenames(&argc,&argv) == MagickFalse)
ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
output=fopen_utf8(argv[argc-1],"wb");
if (output == (FILE *) NULL)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
argv[argc-1]);
return(MagickFalse);
}
status=MagickTrue;
for (i=2; i < (ssize_t) (argc-1); i++)
{
input=fopen_utf8(argv[i],"rb");
if (input == (FILE *) NULL)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
continue;
}
for (c=fgetc(input); c != EOF; c=fgetc(input))
if (fputc((char) c,output) != c)
status=MagickFalse;
(void) fclose(input);
(void) remove_utf8(argv[i]);
}
(void) fclose(output);
return(status);
}
| 168,628 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintPreviewDataService::GetDataEntry(
const std::string& preview_ui_addr_str,
int index,
scoped_refptr<base::RefCountedBytes>* data_bytes) {
*data_bytes = NULL;
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it != data_store_map_.end())
it->second->GetPreviewDataForIndex(index, data_bytes);
}
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 PrintPreviewDataService::GetDataEntry(
int32 preview_ui_id,
int index,
scoped_refptr<base::RefCountedBytes>* data_bytes) {
*data_bytes = NULL;
PreviewDataStoreMap::const_iterator it = data_store_map_.find(preview_ui_id);
if (it != data_store_map_.end())
it->second->GetPreviewDataForIndex(index, data_bytes);
}
| 170,821 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mif_validate(jas_stream_t *in)
{
uchar buf[MIF_MAGICLEN];
uint_fast32_t magic;
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Was enough data read? */
if (n < MIF_MAGICLEN) {
return -1;
}
/* Compute the signature value. */
magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |
(JAS_CAST(uint_fast32_t, buf[1]) << 16) |
(JAS_CAST(uint_fast32_t, buf[2]) << 8) |
buf[3];
/* Ensure that the signature is correct for this format. */
if (magic != MIF_MAGIC) {
return -1;
}
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 | int mif_validate(jas_stream_t *in)
{
jas_uchar buf[MIF_MAGICLEN];
uint_fast32_t magic;
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Was enough data read? */
if (n < MIF_MAGICLEN) {
return -1;
}
/* Compute the signature value. */
magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |
(JAS_CAST(uint_fast32_t, buf[1]) << 16) |
(JAS_CAST(uint_fast32_t, buf[2]) << 8) |
buf[3];
/* Ensure that the signature is correct for this format. */
if (magic != MIF_MAGIC) {
return -1;
}
return 0;
}
| 168,725 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeDownloadManagerDelegate::IsDangerousFile(
const DownloadItem& download,
const FilePath& suggested_path,
bool visited_referrer_before) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (download.GetTransitionType() & content::PAGE_TRANSITION_FROM_ADDRESS_BAR)
return false;
if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() &&
download_crx_util::IsExtensionDownload(download) &&
!extensions::WebstoreInstaller::GetAssociatedApproval(download)) {
return true;
}
if (ShouldOpenFileBasedOnExtension(suggested_path) &&
download.HasUserGesture())
return false;
download_util::DownloadDangerLevel danger_level =
download_util::GetFileDangerLevel(suggested_path.BaseName());
if (danger_level == download_util::AllowOnUserGesture)
return !download.HasUserGesture() || !visited_referrer_before;
return danger_level == download_util::Dangerous;
}
Commit Message: For "Dangerous" file type, no user gesture will bypass the download warning.
BUG=170569
Review URL: https://codereview.chromium.org/12039015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178072 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ChromeDownloadManagerDelegate::IsDangerousFile(
const DownloadItem& download,
const FilePath& suggested_path,
bool visited_referrer_before) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() &&
download_crx_util::IsExtensionDownload(download) &&
!extensions::WebstoreInstaller::GetAssociatedApproval(download)) {
return true;
}
if (ShouldOpenFileBasedOnExtension(suggested_path) &&
download.HasUserGesture())
return false;
download_util::DownloadDangerLevel danger_level =
download_util::GetFileDangerLevel(suggested_path.BaseName());
if (danger_level == download_util::AllowOnUserGesture) {
if (download.GetTransitionType() &
content::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
return false;
}
return !download.HasUserGesture() || !visited_referrer_before;
}
return danger_level == download_util::Dangerous;
}
| 171,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(navigation_handle);
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
first_time_title_set_ = false;
first_time_favicon_set_ = false;
if (!navigation_handle->HasCommitted())
return;
const url::Origin new_origin =
url::Origin::Create(navigation_handle->GetURL());
if (writer_ && new_origin == writer_origin_)
return;
writer_.reset();
writer_origin_ = url::Origin();
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return;
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
DCHECK(profile);
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
DCHECK(data_store);
writer_ = data_store->GetWriterForOrigin(
new_origin,
ContentVisibilityToRCVisibility(web_contents()->GetVisibility()));
if (TabLoadTracker::Get()->GetLoadingState(web_contents()) ==
LoadingState::LOADED) {
writer_->NotifySiteLoaded();
}
writer_origin_ = new_origin;
}
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 LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(navigation_handle);
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
first_time_title_set_ = false;
first_time_favicon_set_ = false;
if (!navigation_handle->HasCommitted())
return;
const url::Origin new_origin =
url::Origin::Create(navigation_handle->GetURL());
if (writer_ && new_origin == writer_origin_)
return;
writer_.reset();
writer_origin_ = url::Origin();
if (!URLShouldBeStoredInLocalDatabase(navigation_handle->GetURL()))
return;
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
DCHECK(profile);
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
DCHECK(data_store);
writer_ = data_store->GetWriterForOrigin(
new_origin,
ContentVisibilityToRCVisibility(web_contents()->GetVisibility()));
if (TabLoadTracker::Get()->GetLoadingState(web_contents()) ==
LoadingState::LOADED) {
writer_->NotifySiteLoaded();
}
writer_origin_ = new_origin;
}
| 172,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void InputMethodChangedHandler(
void* object,
const chromeos::InputMethodDescriptor& current_input_method) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ChangeCurrentInputMethod(current_input_method);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | static void InputMethodChangedHandler(
// IBusController override.
virtual void OnCurrentInputMethodChanged(
const input_method::InputMethodDescriptor& current_input_method) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
ChangeCurrentInputMethod(current_input_method);
}
| 170,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderViewImpl::OnSwapOut(const ViewMsg_SwapOut_Params& params) {
OnStop();
if (!is_swapped_out_) {
SyncNavigationState();
webview()->dispatchUnloadEvent();
SetSwappedOut(true);
WebURLRequest request(GURL("about:swappedout"));
webview()->mainFrame()->loadRequest(request);
}
Send(new ViewHostMsg_SwapOut_ACK(routing_id_, params));
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderViewImpl::OnSwapOut(const ViewMsg_SwapOut_Params& params) {
OnStop();
if (!is_swapped_out_) {
SyncNavigationState();
webview()->dispatchUnloadEvent();
SetSwappedOut(true);
// to chrome::kSwappedOutURL. If that happens to be to the page we had been
GURL swappedOutURL(chrome::kSwappedOutURL);
WebURLRequest request(swappedOutURL);
webview()->mainFrame()->loadRequest(request);
}
Send(new ViewHostMsg_SwapOut_ACK(routing_id_, params));
}
| 171,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 484 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 835 "ext/standard/var_unserializer.re"
{ return 0; }
#line 546 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
goto yy3;
yy14:
++YYCURSOR;
#line 829 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 595 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
goto yy20;
}
Commit Message:
CWE ID: | PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 487 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 838 "ext/standard/var_unserializer.re"
{ return 0; }
#line 549 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
goto yy3;
yy14:
++YYCURSOR;
#line 832 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 598 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
goto yy20;
}
| 164,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Segment::ParseHeaders() {
long long total, available;
const int status = m_pReader->Length(&total, &available);
if (status < 0) // error
return status;
assert((total < 0) || (available <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
assert((segment_stop < 0) || (total < 0) || (segment_stop <= total));
assert((segment_stop < 0) || (m_pos <= segment_stop));
for (;;) {
if ((total >= 0) && (m_pos >= total))
break;
if ((segment_stop >= 0) && (m_pos >= segment_stop))
break;
long long pos = m_pos;
const long long element_start = pos;
if ((pos + 1) > available)
return (pos + 1);
long len;
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) // underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) // error
return id;
if (id == 0x0F43B675) // Cluster ID
break;
pos += len; // consume ID
if ((pos + 1) > available)
return (pos + 1);
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) // underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long element_size = size + pos - element_start;
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
if (id == 0x0549A966) { // Segment Info ID
if (m_pInfo)
return E_FILE_FORMAT_INVALID;
m_pInfo = new (std::nothrow)
SegmentInfo(this, pos, size, element_start, element_size);
if (m_pInfo == NULL)
return -1;
const long status = m_pInfo->Parse();
if (status)
return status;
} else if (id == 0x0654AE6B) { // Tracks ID
if (m_pTracks)
return E_FILE_FORMAT_INVALID;
m_pTracks = new (std::nothrow)
Tracks(this, pos, size, element_start, element_size);
if (m_pTracks == NULL)
return -1;
const long status = m_pTracks->Parse();
if (status)
return status;
} else if (id == 0x0C53BB6B) { // Cues ID
if (m_pCues == NULL) {
m_pCues = new (std::nothrow)
Cues(this, pos, size, element_start, element_size);
if (m_pCues == NULL)
return -1;
}
} else if (id == 0x014D9B74) { // SeekHead ID
if (m_pSeekHead == NULL) {
m_pSeekHead = new (std::nothrow)
SeekHead(this, pos, size, element_start, element_size);
if (m_pSeekHead == NULL)
return -1;
const long status = m_pSeekHead->Parse();
if (status)
return status;
}
} else if (id == 0x0043A770) { // Chapters ID
if (m_pChapters == NULL) {
m_pChapters = new (std::nothrow)
Chapters(this, pos, size, element_start, element_size);
if (m_pChapters == NULL)
return -1;
const long status = m_pChapters->Parse();
if (status)
return status;
}
}
m_pos = pos + size; // consume payload
}
assert((segment_stop < 0) || (m_pos <= segment_stop));
if (m_pInfo == NULL) // TODO: liberalize this behavior
return E_FILE_FORMAT_INVALID;
if (m_pTracks == NULL)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long long Segment::ParseHeaders() {
long long total, available;
const int status = m_pReader->Length(&total, &available);
if (status < 0) // error
return status;
if (total > 0 && available > total)
return E_FILE_FORMAT_INVALID;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((segment_stop >= 0 && total >= 0 && segment_stop > total) ||
(segment_stop >= 0 && m_pos > segment_stop)) {
return E_FILE_FORMAT_INVALID;
}
for (;;) {
if ((total >= 0) && (m_pos >= total))
break;
if ((segment_stop >= 0) && (m_pos >= segment_stop))
break;
long long pos = m_pos;
const long long element_start = pos;
// Avoid rolling over pos when very close to LONG_LONG_MAX.
unsigned long long rollover_check = pos + 1ULL;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > available)
return (pos + 1);
long len;
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) {
// MkvReader doesn't have enough data to satisfy this read attempt.
return (pos + 1);
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadID(m_pReader, idpos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
if (id == 0x0F43B675) // Cluster ID
break;
pos += len; // consume ID
if ((pos + 1) > available)
return (pos + 1);
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) {
// MkvReader doesn't have enough data to satisfy this read attempt.
return (pos + 1);
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
// TODO(tomfinegan): ReadUInt should return an error when len is < 1 or
// len > 8 is true instead of checking this _everywhere_.
return size;
}
pos += len; // consume length of size of element
// Avoid rolling over pos when very close to LONG_LONG_MAX.
rollover_check = static_cast<unsigned long long>(pos) + size;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
const long long element_size = size + pos - element_start;
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
if (id == 0x0549A966) { // Segment Info ID
if (m_pInfo)
return E_FILE_FORMAT_INVALID;
m_pInfo = new (std::nothrow)
SegmentInfo(this, pos, size, element_start, element_size);
if (m_pInfo == NULL)
return -1;
const long status = m_pInfo->Parse();
if (status)
return status;
} else if (id == 0x0654AE6B) { // Tracks ID
if (m_pTracks)
return E_FILE_FORMAT_INVALID;
m_pTracks = new (std::nothrow)
Tracks(this, pos, size, element_start, element_size);
if (m_pTracks == NULL)
return -1;
const long status = m_pTracks->Parse();
if (status)
return status;
} else if (id == 0x0C53BB6B) { // Cues ID
if (m_pCues == NULL) {
m_pCues = new (std::nothrow)
Cues(this, pos, size, element_start, element_size);
if (m_pCues == NULL)
return -1;
}
} else if (id == 0x014D9B74) { // SeekHead ID
if (m_pSeekHead == NULL) {
m_pSeekHead = new (std::nothrow)
SeekHead(this, pos, size, element_start, element_size);
if (m_pSeekHead == NULL)
return -1;
const long status = m_pSeekHead->Parse();
if (status)
return status;
}
} else if (id == 0x0043A770) { // Chapters ID
if (m_pChapters == NULL) {
m_pChapters = new (std::nothrow)
Chapters(this, pos, size, element_start, element_size);
if (m_pChapters == NULL)
return -1;
const long status = m_pChapters->Parse();
if (status)
return status;
}
} else if (id == 0x0254C367) { // Tags ID
if (m_pTags == NULL) {
m_pTags = new (std::nothrow)
Tags(this, pos, size, element_start, element_size);
if (m_pTags == NULL)
return -1;
const long status = m_pTags->Parse();
if (status)
return status;
}
}
m_pos = pos + size; // consume payload
}
if (segment_stop >= 0 && m_pos > segment_stop)
return E_FILE_FORMAT_INVALID;
if (m_pInfo == NULL) // TODO: liberalize this behavior
return E_FILE_FORMAT_INVALID;
if (m_pTracks == NULL)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 173,856 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399 | static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
put_fid(pdu, oldfidp);
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
| 164,907 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xen_netbk_tx_build_gops(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;
struct sk_buff *skb;
int ret;
while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&
!list_empty(&netbk->net_schedule_list)) {
struct xenvif *vif;
struct xen_netif_tx_request txreq;
struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS];
struct page *page;
struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
u16 pending_idx;
RING_IDX idx;
int work_to_do;
unsigned int data_len;
pending_ring_idx_t index;
/* Get a netif from the list with work to do. */
vif = poll_net_schedule_list(netbk);
if (!vif)
continue;
RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);
if (!work_to_do) {
xenvif_put(vif);
continue;
}
idx = vif->tx.req_cons;
rmb(); /* Ensure that we see the request before we copy it. */
memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
/* Credit-based scheduling. */
if (txreq.size > vif->remaining_credit &&
tx_credit_exceeded(vif, txreq.size)) {
xenvif_put(vif);
continue;
}
vif->remaining_credit -= txreq.size;
work_to_do--;
vif->tx.req_cons = ++idx;
memset(extras, 0, sizeof(extras));
if (txreq.flags & XEN_NETTXF_extra_info) {
work_to_do = xen_netbk_get_extras(vif, extras,
work_to_do);
idx = vif->tx.req_cons;
if (unlikely(work_to_do < 0)) {
netbk_tx_err(vif, &txreq, idx);
continue;
}
}
ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);
if (unlikely(ret < 0)) {
netbk_tx_err(vif, &txreq, idx - ret);
continue;
}
idx += ret;
if (unlikely(txreq.size < ETH_HLEN)) {
netdev_dbg(vif->dev,
"Bad packet size: %d\n", txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
/* No crossing a page as the payload mustn't fragment. */
if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
netdev_dbg(vif->dev,
"txreq.offset: %x, size: %u, end: %lu\n",
txreq.offset, txreq.size,
(txreq.offset&~PAGE_MASK) + txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
index = pending_index(netbk->pending_cons);
pending_idx = netbk->pending_ring[index];
data_len = (txreq.size > PKT_PROT_LEN &&
ret < MAX_SKB_FRAGS) ?
PKT_PROT_LEN : txreq.size;
skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,
GFP_ATOMIC | __GFP_NOWARN);
if (unlikely(skb == NULL)) {
netdev_dbg(vif->dev,
"Can't allocate a skb in start_xmit.\n");
netbk_tx_err(vif, &txreq, idx);
break;
}
/* Packets passed to netif_rx() must have some headroom. */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
struct xen_netif_extra_info *gso;
gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
if (netbk_set_skb_gso(vif, skb, gso)) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
}
/* XXX could copy straight to head */
page = xen_netbk_alloc_page(netbk, skb, pending_idx);
if (!page) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop->source.u.ref = txreq.gref;
gop->source.domid = vif->domid;
gop->source.offset = txreq.offset;
gop->dest.u.gmfn = virt_to_mfn(page_address(page));
gop->dest.domid = DOMID_SELF;
gop->dest.offset = txreq.offset;
gop->len = txreq.size;
gop->flags = GNTCOPY_source_gref;
gop++;
memcpy(&netbk->pending_tx_info[pending_idx].req,
&txreq, sizeof(txreq));
netbk->pending_tx_info[pending_idx].vif = vif;
*((u16 *)skb->data) = pending_idx;
__skb_put(skb, data_len);
skb_shinfo(skb)->nr_frags = ret;
if (data_len < txreq.size) {
skb_shinfo(skb)->nr_frags++;
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
pending_idx);
} else {
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
INVALID_PENDING_IDX);
}
netbk->pending_cons++;
request_gop = xen_netbk_get_requests(netbk, vif,
skb, txfrags, gop);
if (request_gop == NULL) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop = request_gop;
__skb_queue_tail(&netbk->tx_queue, skb);
vif->tx.req_cons = idx;
xen_netbk_check_rx_xenvif(vif);
if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))
break;
}
return gop - netbk->tx_copy_ops;
}
Commit Message: xen/netback: shutdown the ring if it contains garbage.
A buggy or malicious frontend should not be able to confuse netback.
If we spot anything which is not as it should be then shutdown the
device and don't try to continue with the ring in a potentially
hostile state. Well behaved and non-hostile frontends will not be
penalised.
As well as making the existing checks for such errors fatal also add a
new check that ensures that there isn't an insane number of requests
on the ring (i.e. more than would fit in the ring). If the ring
contains garbage then previously is was possible to loop over this
insane number, getting an error each time and therefore not generating
any more pending requests and therefore not exiting the loop in
xen_netbk_tx_build_gops for an externded period.
Also turn various netdev_dbg calls which no precipitate a fatal error
into netdev_err, they are rate limited because the device is shutdown
afterwards.
This fixes at least one known DoS/softlockup of the backend domain.
Signed-off-by: Ian Campbell <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;
struct sk_buff *skb;
int ret;
while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&
!list_empty(&netbk->net_schedule_list)) {
struct xenvif *vif;
struct xen_netif_tx_request txreq;
struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS];
struct page *page;
struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
u16 pending_idx;
RING_IDX idx;
int work_to_do;
unsigned int data_len;
pending_ring_idx_t index;
/* Get a netif from the list with work to do. */
vif = poll_net_schedule_list(netbk);
/* This can sometimes happen because the test of
* list_empty(net_schedule_list) at the top of the
* loop is unlocked. Just go back and have another
* look.
*/
if (!vif)
continue;
if (vif->tx.sring->req_prod - vif->tx.req_cons >
XEN_NETIF_TX_RING_SIZE) {
netdev_err(vif->dev,
"Impossible number of requests. "
"req_prod %d, req_cons %d, size %ld\n",
vif->tx.sring->req_prod, vif->tx.req_cons,
XEN_NETIF_TX_RING_SIZE);
netbk_fatal_tx_err(vif);
continue;
}
RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);
if (!work_to_do) {
xenvif_put(vif);
continue;
}
idx = vif->tx.req_cons;
rmb(); /* Ensure that we see the request before we copy it. */
memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
/* Credit-based scheduling. */
if (txreq.size > vif->remaining_credit &&
tx_credit_exceeded(vif, txreq.size)) {
xenvif_put(vif);
continue;
}
vif->remaining_credit -= txreq.size;
work_to_do--;
vif->tx.req_cons = ++idx;
memset(extras, 0, sizeof(extras));
if (txreq.flags & XEN_NETTXF_extra_info) {
work_to_do = xen_netbk_get_extras(vif, extras,
work_to_do);
idx = vif->tx.req_cons;
if (unlikely(work_to_do < 0))
continue;
}
ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);
if (unlikely(ret < 0))
continue;
idx += ret;
if (unlikely(txreq.size < ETH_HLEN)) {
netdev_dbg(vif->dev,
"Bad packet size: %d\n", txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
/* No crossing a page as the payload mustn't fragment. */
if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
netdev_err(vif->dev,
"txreq.offset: %x, size: %u, end: %lu\n",
txreq.offset, txreq.size,
(txreq.offset&~PAGE_MASK) + txreq.size);
netbk_fatal_tx_err(vif);
continue;
}
index = pending_index(netbk->pending_cons);
pending_idx = netbk->pending_ring[index];
data_len = (txreq.size > PKT_PROT_LEN &&
ret < MAX_SKB_FRAGS) ?
PKT_PROT_LEN : txreq.size;
skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,
GFP_ATOMIC | __GFP_NOWARN);
if (unlikely(skb == NULL)) {
netdev_dbg(vif->dev,
"Can't allocate a skb in start_xmit.\n");
netbk_tx_err(vif, &txreq, idx);
break;
}
/* Packets passed to netif_rx() must have some headroom. */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
struct xen_netif_extra_info *gso;
gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
if (netbk_set_skb_gso(vif, skb, gso)) {
/* Failure in netbk_set_skb_gso is fatal. */
kfree_skb(skb);
continue;
}
}
/* XXX could copy straight to head */
page = xen_netbk_alloc_page(netbk, skb, pending_idx);
if (!page) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop->source.u.ref = txreq.gref;
gop->source.domid = vif->domid;
gop->source.offset = txreq.offset;
gop->dest.u.gmfn = virt_to_mfn(page_address(page));
gop->dest.domid = DOMID_SELF;
gop->dest.offset = txreq.offset;
gop->len = txreq.size;
gop->flags = GNTCOPY_source_gref;
gop++;
memcpy(&netbk->pending_tx_info[pending_idx].req,
&txreq, sizeof(txreq));
netbk->pending_tx_info[pending_idx].vif = vif;
*((u16 *)skb->data) = pending_idx;
__skb_put(skb, data_len);
skb_shinfo(skb)->nr_frags = ret;
if (data_len < txreq.size) {
skb_shinfo(skb)->nr_frags++;
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
pending_idx);
} else {
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
INVALID_PENDING_IDX);
}
netbk->pending_cons++;
request_gop = xen_netbk_get_requests(netbk, vif,
skb, txfrags, gop);
if (request_gop == NULL) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop = request_gop;
__skb_queue_tail(&netbk->tx_queue, skb);
vif->tx.req_cons = idx;
xen_netbk_check_rx_xenvif(vif);
if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))
break;
}
return gop - netbk->tx_copy_ops;
}
| 166,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) ALIGN16(u2_width);
}
}
else
{
if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
return SET_IVD_FATAL_ERROR(e_error);
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Check for Valid Frame Rate in Header
Bug: 34093952
Change-Id: I9f009edda84555e8d14b138684a38114fb888bf8
(cherry picked from commit 3f068a4e66cc972cf798c79a196099bd7d3bfceb)
CWE ID: CWE-200 | IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) ALIGN16(u2_width);
}
}
else
{
if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
return SET_IVD_FATAL_ERROR(e_error);
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE)
{
return IMPEG2D_FRM_HDR_DECODE_ERR;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 174,036 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.