instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int pit_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int ret, count;
struct kvm_kpit_channel_state *s;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
addr &= KVM_PIT_CHANNEL_MASK;
s = &pit_state->channels[addr];
mutex_lock(&pit_state->lock);
if (s->status_latched) {
s->status_latched = 0;
ret = s->status;
} else if (s->count_latched) {
switch (s->count_latched) {
default:
case RW_STATE_LSB:
ret = s->latched_count & 0xff;
s->count_latched = 0;
break;
case RW_STATE_MSB:
ret = s->latched_count >> 8;
s->count_latched = 0;
break;
case RW_STATE_WORD0:
ret = s->latched_count & 0xff;
s->count_latched = RW_STATE_MSB;
break;
}
} else {
switch (s->read_state) {
default:
case RW_STATE_LSB:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
break;
case RW_STATE_MSB:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
break;
case RW_STATE_WORD0:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
s->read_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
s->read_state = RW_STATE_WORD0;
break;
}
}
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
Commit Message: KVM: PIT: control word is write-only
PIT control word (address 0x43) is write-only, reads are undefined.
Cc: [email protected]
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID: CWE-119 | static int pit_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int ret, count;
struct kvm_kpit_channel_state *s;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
addr &= KVM_PIT_CHANNEL_MASK;
if (addr == 3)
return 0;
s = &pit_state->channels[addr];
mutex_lock(&pit_state->lock);
if (s->status_latched) {
s->status_latched = 0;
ret = s->status;
} else if (s->count_latched) {
switch (s->count_latched) {
default:
case RW_STATE_LSB:
ret = s->latched_count & 0xff;
s->count_latched = 0;
break;
case RW_STATE_MSB:
ret = s->latched_count >> 8;
s->count_latched = 0;
break;
case RW_STATE_WORD0:
ret = s->latched_count & 0xff;
s->count_latched = RW_STATE_MSB;
break;
}
} else {
switch (s->read_state) {
default:
case RW_STATE_LSB:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
break;
case RW_STATE_MSB:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
break;
case RW_STATE_WORD0:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
s->read_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
s->read_state = RW_STATE_WORD0;
break;
}
}
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
| 166,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunInvAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED_ARRAY(16, int16_t, in, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, coeff, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
double out_r[kNumCoeffs];
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
in[j] = src[j] - dst[j];
}
reference_16x16_dct_2d(in, out_r);
for (int j = 0; j < kNumCoeffs; ++j)
coeff[j] = round(out_r[j]);
REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, 16));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
EXPECT_GE(1u, error)
<< "Error: 16x16 IDCT has error " << error
<< " at index " << j;
}
}
}
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 RunInvAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]);
DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]);
#endif // CONFIG_VP9_HIGHBITDEPTH
for (int i = 0; i < count_test_block; ++i) {
double out_r[kNumCoeffs];
for (int j = 0; j < kNumCoeffs; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
in[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
in[j] = src16[j] - dst16[j];
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
reference_16x16_dct_2d(in, out_r);
for (int j = 0; j < kNumCoeffs; ++j)
coeff[j] = static_cast<tran_low_t>(round(out_r[j]));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, 16));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16),
16));
#endif // CONFIG_VP9_HIGHBITDEPTH
}
for (int j = 0; j < kNumCoeffs; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const uint32_t diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
const uint32_t diff = dst[j] - src[j];
#endif // CONFIG_VP9_HIGHBITDEPTH
const uint32_t error = diff * diff;
EXPECT_GE(1u, error)
<< "Error: 16x16 IDCT has error " << error
<< " at index " << j;
}
}
}
| 174,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PlatformWebView::PlatformWebView(WKContextRef contextRef, WKPageGroupRef pageGroupRef)
: m_view(new QQuickWebView(contextRef, pageGroupRef))
, m_window(new WrapperWindow(m_view))
, m_windowIsKey(true)
, m_modalEventLoop(0)
{
QQuickWebViewExperimental experimental(m_view);
experimental.setRenderToOffscreenBuffer(true);
m_view->setAllowAnyHTTPSCertificateForLocalHost(true);
}
Commit Message: [Qt][WK2] There's no way to test the gesture tap on WTR
https://bugs.webkit.org/show_bug.cgi?id=92895
Reviewed by Kenneth Rohde Christiansen.
Source/WebKit2:
Add an instance of QtViewportHandler to QQuickWebViewPrivate, so it's
now available on mobile and desktop modes, as a side effect gesture tap
events can now be created and sent to WebCore.
This is needed to test tap gestures and to get tap gestures working
when you have a WebView (in desktop mode) on notebooks equipped with
touch screens.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::onComponentComplete):
(QQuickWebViewFlickablePrivate::onComponentComplete): Implementation
moved to QQuickWebViewPrivate::onComponentComplete.
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
(QQuickWebViewFlickablePrivate):
Tools:
WTR doesn't create the QQuickItem from C++, not from QML, so a call
to componentComplete() was added to mimic the QML behaviour.
* WebKitTestRunner/qt/PlatformWebViewQt.cpp:
(WTR::PlatformWebView::PlatformWebView):
git-svn-id: svn://svn.chromium.org/blink/trunk@124625 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | PlatformWebView::PlatformWebView(WKContextRef contextRef, WKPageGroupRef pageGroupRef)
: m_view(new QQuickWebView(contextRef, pageGroupRef))
, m_window(new WrapperWindow(m_view))
, m_windowIsKey(true)
, m_modalEventLoop(0)
{
QQuickWebViewExperimental experimental(m_view);
experimental.setRenderToOffscreenBuffer(true);
m_view->setAllowAnyHTTPSCertificateForLocalHost(true);
m_view->componentComplete();
}
| 170,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int genl_register_family(struct genl_family *family)
{
int err, i;
int start = GENL_START_ALLOC, end = GENL_MAX_ID;
err = genl_validate_ops(family);
if (err)
return err;
genl_lock_all();
if (genl_family_find_byname(family->name)) {
err = -EEXIST;
goto errout_locked;
}
/*
* Sadly, a few cases need to be special-cased
* due to them having previously abused the API
* and having used their family ID also as their
* multicast group ID, so we use reserved IDs
* for both to be sure we can do that mapping.
*/
if (family == &genl_ctrl) {
/* and this needs to be special for initial family lookups */
start = end = GENL_ID_CTRL;
} else if (strcmp(family->name, "pmcraid") == 0) {
start = end = GENL_ID_PMCRAID;
} else if (strcmp(family->name, "VFS_DQUOT") == 0) {
start = end = GENL_ID_VFS_DQUOT;
}
if (family->maxattr && !family->parallel_ops) {
family->attrbuf = kmalloc_array(family->maxattr + 1,
sizeof(struct nlattr *),
GFP_KERNEL);
if (family->attrbuf == NULL) {
err = -ENOMEM;
goto errout_locked;
}
} else
family->attrbuf = NULL;
family->id = idr_alloc(&genl_fam_idr, family,
start, end + 1, GFP_KERNEL);
if (family->id < 0) {
err = family->id;
goto errout_locked;
}
err = genl_validate_assign_mc_groups(family);
if (err)
goto errout_remove;
genl_unlock_all();
/* send all events */
genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0);
for (i = 0; i < family->n_mcgrps; i++)
genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family,
&family->mcgrps[i], family->mcgrp_offset + i);
return 0;
errout_remove:
idr_remove(&genl_fam_idr, family->id);
kfree(family->attrbuf);
errout_locked:
genl_unlock_all();
return err;
}
Commit Message: genetlink: Fix a memory leak on error path
In genl_register_family(), when idr_alloc() fails,
we forget to free the memory we possibly allocate for
family->attrbuf.
Reported-by: Hulk Robot <[email protected]>
Fixes: 2ae0f17df1cd ("genetlink: use idr to track families")
Signed-off-by: YueHaibing <[email protected]>
Reviewed-by: Kirill Tkhai <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | int genl_register_family(struct genl_family *family)
{
int err, i;
int start = GENL_START_ALLOC, end = GENL_MAX_ID;
err = genl_validate_ops(family);
if (err)
return err;
genl_lock_all();
if (genl_family_find_byname(family->name)) {
err = -EEXIST;
goto errout_locked;
}
/*
* Sadly, a few cases need to be special-cased
* due to them having previously abused the API
* and having used their family ID also as their
* multicast group ID, so we use reserved IDs
* for both to be sure we can do that mapping.
*/
if (family == &genl_ctrl) {
/* and this needs to be special for initial family lookups */
start = end = GENL_ID_CTRL;
} else if (strcmp(family->name, "pmcraid") == 0) {
start = end = GENL_ID_PMCRAID;
} else if (strcmp(family->name, "VFS_DQUOT") == 0) {
start = end = GENL_ID_VFS_DQUOT;
}
if (family->maxattr && !family->parallel_ops) {
family->attrbuf = kmalloc_array(family->maxattr + 1,
sizeof(struct nlattr *),
GFP_KERNEL);
if (family->attrbuf == NULL) {
err = -ENOMEM;
goto errout_locked;
}
} else
family->attrbuf = NULL;
family->id = idr_alloc(&genl_fam_idr, family,
start, end + 1, GFP_KERNEL);
if (family->id < 0) {
err = family->id;
goto errout_free;
}
err = genl_validate_assign_mc_groups(family);
if (err)
goto errout_remove;
genl_unlock_all();
/* send all events */
genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0);
for (i = 0; i < family->n_mcgrps; i++)
genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family,
&family->mcgrps[i], family->mcgrp_offset + i);
return 0;
errout_remove:
idr_remove(&genl_fam_idr, family->id);
errout_free:
kfree(family->attrbuf);
errout_locked:
genl_unlock_all();
return err;
}
| 169,524 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PlatformSensorProviderLinux::SensorDeviceFound(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const PlatformSensorProviderBase::CreateSensorCallback& callback,
const SensorInfoLinux* sensor_device) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(sensor_device);
if (!StartPollingThread()) {
callback.Run(nullptr);
return;
}
scoped_refptr<PlatformSensorLinux> sensor =
new PlatformSensorLinux(type, std::move(mapping), this, sensor_device,
polling_thread_->task_runner());
callback.Run(sensor);
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void PlatformSensorProviderLinux::SensorDeviceFound(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
const PlatformSensorProviderBase::CreateSensorCallback& callback,
const SensorInfoLinux* sensor_device) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(sensor_device);
if (!StartPollingThread()) {
callback.Run(nullptr);
return;
}
scoped_refptr<PlatformSensorLinux> sensor =
new PlatformSensorLinux(type, reading_buffer, this, sensor_device,
polling_thread_->task_runner());
callback.Run(sensor);
}
| 172,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void send(node_t *node, node_t *child, byte *fout) {
if (node->parent) {
send(node->parent, node, fout);
}
if (child) {
if (node->right == child) {
add_bit(1, fout);
} else {
add_bit(0, fout);
}
}
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
CWE ID: CWE-119 | static void send(node_t *node, node_t *child, byte *fout) {
static void send(node_t *node, node_t *child, byte *fout, int maxoffset) {
if (node->parent) {
send(node->parent, node, fout, maxoffset);
}
if (child) {
if (bloc >= maxoffset) {
bloc = maxoffset + 1;
return;
}
if (node->right == child) {
add_bit(1, fout);
} else {
add_bit(0, fout);
}
}
}
| 167,997 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FragmentPaintPropertyTreeBuilder::UpdateOverflowControlsClip() {
DCHECK(properties_);
if (!NeedsPaintPropertyUpdate())
return;
if (NeedsOverflowControlsClip()) {
properties_->UpdateOverflowControlsClip(
context_.current.clip,
ClipPaintPropertyNode::State{
context_.current.transform,
ToClipRect(LayoutRect(context_.current.paint_offset,
ToLayoutBox(object_).Size()))});
} else {
properties_->ClearOverflowControlsClip();
}
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void FragmentPaintPropertyTreeBuilder::UpdateOverflowControlsClip() {
DCHECK(properties_);
if (!NeedsPaintPropertyUpdate())
return;
if (NeedsOverflowControlsClip()) {
properties_->UpdateOverflowControlsClip(
*context_.current.clip,
ClipPaintPropertyNode::State{
context_.current.transform,
ToClipRect(LayoutRect(context_.current.paint_offset,
ToLayoutBox(object_).Size()))});
} else {
properties_->ClearOverflowControlsClip();
}
}
| 171,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfsreq_print_noaddr(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
register const uint32_t *dp;
nfs_type type;
int v3;
uint32_t proc;
uint32_t access_flags;
struct nfsv3_sattr sa3;
ND_PRINT((ndo, "%d", length));
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */
goto trunc;
v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3);
proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
case NFSPROC_SETATTR:
case NFSPROC_READLINK:
case NFSPROC_FSSTAT:
case NFSPROC_FSINFO:
case NFSPROC_PATHCONF:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefh(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_LOOKUP:
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefhn(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_ACCESS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[0]);
access_flags = EXTRACT_32BITS(&dp[0]);
if (access_flags & ~NFSV3ACCESS_FULL) {
/* NFSV3ACCESS definitions aren't up to date */
ND_PRINT((ndo, " %04x", access_flags));
} else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) {
ND_PRINT((ndo, " NFS_ACCESS_FULL"));
} else {
char separator = ' ';
if (access_flags & NFSV3ACCESS_READ) {
ND_PRINT((ndo, " NFS_ACCESS_READ"));
separator = '|';
}
if (access_flags & NFSV3ACCESS_LOOKUP) {
ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_MODIFY) {
ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXTEND) {
ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_DELETE) {
ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXECUTE)
ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator));
}
return;
}
break;
case NFSPROC_READ:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
} else {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes @ %u",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_WRITE:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
dp += 3;
ND_TCHECK(dp[0]);
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(dp))));
}
} else {
ND_TCHECK(dp[3]);
ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)",
EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_SYMLINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
if (parsefn(ndo, dp) == NULL)
break;
if (v3 && ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_MKNOD:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_TCHECK(*dp);
type = (nfs_type)EXTRACT_32BITS(dp);
dp++;
if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type)));
if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u/%u",
EXTRACT_32BITS(&dp[0]),
EXTRACT_32BITS(&dp[1])));
dp += 2;
}
if (ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_RENAME:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_LINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
/*
* We shouldn't really try to interpret the
* offset cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag)
ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3]));
} else {
ND_TCHECK(dp[1]);
/*
* Print the offset as signed, since -1 is
* common, but offsets > 2^31 aren't.
*/
ND_PRINT((ndo, " %u bytes @ %d",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_READDIRPLUS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[4]);
/*
* We don't try to interpret the offset
* cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_TCHECK(dp[5]);
ND_PRINT((ndo, " max %u verf %08x%08x",
EXTRACT_32BITS(&dp[5]), dp[2], dp[3]));
}
return;
}
break;
case NFSPROC_COMMIT:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
return;
}
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-12898/NFS: Fix bounds checking.
Fix the bounds checking for the NFSv3 WRITE procedure to check whether the
length of the opaque data being written is present in the captured data,
not just whether the byte count is present in the captured data.
furthest forward in the packet, not the item before it. (This also lets
us eliminate the check for the "stable" argument being present in the
captured data; rewrite the code to print that to make it a bit clearer.)
Check that the entire ar_stat field is present in the capture.
Note that parse_wcc_attr() is called after we've already checked whether
the wcc_data is present.
Check before fetching the "access" part of the NFSv3 ACCESS results.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Include a test for the "check before fetching the "access" part..." fix,
using the capture supplied by the reporter(s).
CWE ID: CWE-125 | nfsreq_print_noaddr(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
register const uint32_t *dp;
nfs_type type;
int v3;
uint32_t proc;
uint32_t access_flags;
struct nfsv3_sattr sa3;
ND_PRINT((ndo, "%d", length));
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */
goto trunc;
v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3);
proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
case NFSPROC_SETATTR:
case NFSPROC_READLINK:
case NFSPROC_FSSTAT:
case NFSPROC_FSINFO:
case NFSPROC_PATHCONF:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefh(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_LOOKUP:
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefhn(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_ACCESS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[0]);
access_flags = EXTRACT_32BITS(&dp[0]);
if (access_flags & ~NFSV3ACCESS_FULL) {
/* NFSV3ACCESS definitions aren't up to date */
ND_PRINT((ndo, " %04x", access_flags));
} else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) {
ND_PRINT((ndo, " NFS_ACCESS_FULL"));
} else {
char separator = ' ';
if (access_flags & NFSV3ACCESS_READ) {
ND_PRINT((ndo, " NFS_ACCESS_READ"));
separator = '|';
}
if (access_flags & NFSV3ACCESS_LOOKUP) {
ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_MODIFY) {
ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXTEND) {
ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_DELETE) {
ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXECUTE)
ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator));
}
return;
}
break;
case NFSPROC_READ:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
} else {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes @ %u",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_WRITE:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(&dp[3]))));
}
} else {
ND_TCHECK(dp[3]);
ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)",
EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_SYMLINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
if (parsefn(ndo, dp) == NULL)
break;
if (v3 && ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_MKNOD:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_TCHECK(*dp);
type = (nfs_type)EXTRACT_32BITS(dp);
dp++;
if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type)));
if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u/%u",
EXTRACT_32BITS(&dp[0]),
EXTRACT_32BITS(&dp[1])));
dp += 2;
}
if (ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_RENAME:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_LINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
/*
* We shouldn't really try to interpret the
* offset cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag)
ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3]));
} else {
ND_TCHECK(dp[1]);
/*
* Print the offset as signed, since -1 is
* common, but offsets > 2^31 aren't.
*/
ND_PRINT((ndo, " %u bytes @ %d",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_READDIRPLUS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[4]);
/*
* We don't try to interpret the offset
* cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_TCHECK(dp[5]);
ND_PRINT((ndo, " max %u verf %08x%08x",
EXTRACT_32BITS(&dp[5]), dp[2], dp[3]));
}
return;
}
break;
case NFSPROC_COMMIT:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
return;
}
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
| 167,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PlatformSensorProviderAndroid::CreateAbsoluteOrientationEulerAnglesSensor(
JNIEnv* env,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
if (static_cast<bool>(Java_PlatformSensorProvider_hasSensorType(
env, j_object_,
static_cast<jint>(
mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION)))) {
auto sensor_fusion_algorithm =
std::make_unique<OrientationEulerAnglesFusionAlgorithmUsingQuaternion>(
true /* absolute */);
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(sensor_fusion_algorithm), callback);
} else {
auto sensor_fusion_algorithm = std::make_unique<
AbsoluteOrientationEulerAnglesFusionAlgorithmUsingAccelerometerAndMagnetometer>();
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(sensor_fusion_algorithm), callback);
}
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void PlatformSensorProviderAndroid::CreateAbsoluteOrientationEulerAnglesSensor(
JNIEnv* env,
SensorReadingSharedBuffer* reading_buffer,
const CreateSensorCallback& callback) {
if (static_cast<bool>(Java_PlatformSensorProvider_hasSensorType(
env, j_object_,
static_cast<jint>(
mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION)))) {
auto sensor_fusion_algorithm =
std::make_unique<OrientationEulerAnglesFusionAlgorithmUsingQuaternion>(
true /* absolute */);
PlatformSensorFusion::Create(reading_buffer, this,
std::move(sensor_fusion_algorithm), callback);
} else {
auto sensor_fusion_algorithm = std::make_unique<
AbsoluteOrientationEulerAnglesFusionAlgorithmUsingAccelerometerAndMagnetometer>();
PlatformSensorFusion::Create(reading_buffer, this,
std::move(sensor_fusion_algorithm), callback);
}
}
| 172,834 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CheckSad(unsigned int max_sad) {
unsigned int reference_sad, exp_sad;
reference_sad = ReferenceSAD(max_sad);
exp_sad = SAD(max_sad);
if (reference_sad <= max_sad) {
ASSERT_EQ(exp_sad, reference_sad);
} else {
ASSERT_GE(exp_sad, reference_sad);
}
}
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 CheckSad(unsigned int max_sad) {
| 174,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BluetoothDeviceChromeOS::BluetoothDeviceChromeOS(
BluetoothAdapterChromeOS* adapter,
const dbus::ObjectPath& object_path)
: adapter_(adapter),
object_path_(object_path),
num_connecting_calls_(0),
pairing_delegate_(NULL),
pairing_delegate_used_(false),
weak_ptr_factory_(this) {
}
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: | BluetoothDeviceChromeOS::BluetoothDeviceChromeOS(
BluetoothAdapterChromeOS* adapter,
const dbus::ObjectPath& object_path)
: adapter_(adapter),
object_path_(object_path),
num_connecting_calls_(0),
weak_ptr_factory_(this) {
}
| 171,217 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
return follow_dotdot_rcu(nd);
} else
follow_dotdot(nd);
}
return 0;
}
Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root
In rare cases a directory can be renamed out from under a bind mount.
In those cases without special handling it becomes possible to walk up
the directory tree to the root dentry of the filesystem and down
from the root dentry to every other file or directory on the filesystem.
Like division by zero .. from an unconnected path can not be given
a useful semantic as there is no predicting at which path component
the code will realize it is unconnected. We certainly can not match
the current behavior as the current behavior is a security hole.
Therefore when encounting .. when following an unconnected path
return -ENOENT.
- Add a function path_connected to verify path->dentry is reachable
from path->mnt.mnt_root. AKA to validate that rename did not do
something nasty to the bind mount.
To avoid races path_connected must be called after following a path
component to it's next path component.
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-254 | static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
return follow_dotdot_rcu(nd);
} else
return follow_dotdot(nd);
}
return 0;
}
| 166,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
ND_PRINT((ndo," len=%d method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (1 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < len) {
if(!ike_show_somedata(ndo, authdata, ep)) goto trunc;
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835 | ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,926 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
{
int i;
int j;
if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
mat1->numcols_) {
return 1;
}
for (i = 0; i < mat0->numrows_; i++) {
for (j = 0; j < mat0->numcols_; j++) {
if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
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 jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
{
jas_matind_t i;
jas_matind_t j;
if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
mat1->numcols_) {
return 1;
}
for (i = 0; i < mat0->numrows_; i++) {
for (j = 0; j < mat0->numcols_; j++) {
if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
return 1;
}
}
}
return 0;
}
| 168,701 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer)
{
if (!createHarfBuzzRuns())
return false;
m_totalWidth = 0;
if (!shapeHarfBuzzRuns())
return false;
if (glyphBuffer && !fillGlyphBuffer(glyphBuffer))
return false;
return true;
}
Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape.
[email protected]
BUG=476647
Review URL: https://codereview.chromium.org/1108663003
git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer)
{
if (!createHarfBuzzRuns())
return false;
if (!shapeHarfBuzzRuns())
return false;
if (glyphBuffer && !fillGlyphBuffer(glyphBuffer))
return false;
return true;
}
| 172,005 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static PassRefPtr<CSSValue> getPositionOffsetValue(RenderStyle* style, CSSPropertyID propertyID, RenderView* renderView)
{
if (!style)
return 0;
Length l;
switch (propertyID) {
case CSSPropertyLeft:
l = style->left();
break;
case CSSPropertyRight:
l = style->right();
break;
case CSSPropertyTop:
l = style->top();
break;
case CSSPropertyBottom:
l = style->bottom();
break;
default:
return 0;
}
if (style->position() == AbsolutePosition || style->position() == FixedPosition) {
if (l.type() == WebCore::Fixed)
return zoomAdjustedPixelValue(l.value(), style);
else if (l.isViewportPercentage())
return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style);
return cssValuePool().createValue(l);
}
if (style->position() == RelativePosition)
return cssValuePool().createValue(l);
return cssValuePool().createIdentifierValue(CSSValueAuto);
}
Commit Message: Rename isPositioned to isOutOfFlowPositioned for clarity
https://bugs.webkit.org/show_bug.cgi?id=89836
Reviewed by Antti Koivisto.
RenderObject and RenderStyle had an isPositioned() method that was
confusing, because it excluded relative positioning. Rename to
isOutOfFlowPositioned(), which makes it clearer that it only applies
to absolute and fixed positioning.
Simple rename; no behavior change.
Source/WebCore:
* css/CSSComputedStyleDeclaration.cpp:
(WebCore::getPositionOffsetValue):
* css/StyleResolver.cpp:
(WebCore::StyleResolver::collectMatchingRulesForList):
* dom/Text.cpp:
(WebCore::Text::rendererIsNeeded):
* editing/DeleteButtonController.cpp:
(WebCore::isDeletableElement):
* editing/TextIterator.cpp:
(WebCore::shouldEmitNewlinesBeforeAndAfterNode):
* rendering/AutoTableLayout.cpp:
(WebCore::shouldScaleColumns):
* rendering/InlineFlowBox.cpp:
(WebCore::InlineFlowBox::addToLine):
(WebCore::InlineFlowBox::placeBoxesInInlineDirection):
(WebCore::InlineFlowBox::requiresIdeographicBaseline):
(WebCore::InlineFlowBox::adjustMaxAscentAndDescent):
(WebCore::InlineFlowBox::computeLogicalBoxHeights):
(WebCore::InlineFlowBox::placeBoxesInBlockDirection):
(WebCore::InlineFlowBox::flipLinesInBlockDirection):
(WebCore::InlineFlowBox::computeOverflow):
(WebCore::InlineFlowBox::computeOverAnnotationAdjustment):
(WebCore::InlineFlowBox::computeUnderAnnotationAdjustment):
* rendering/InlineIterator.h:
(WebCore::isIteratorTarget):
* rendering/LayoutState.cpp:
(WebCore::LayoutState::LayoutState):
* rendering/RenderBlock.cpp:
(WebCore::RenderBlock::MarginInfo::MarginInfo):
(WebCore::RenderBlock::styleWillChange):
(WebCore::RenderBlock::styleDidChange):
(WebCore::RenderBlock::addChildToContinuation):
(WebCore::RenderBlock::addChildToAnonymousColumnBlocks):
(WebCore::RenderBlock::containingColumnsBlock):
(WebCore::RenderBlock::columnsBlockForSpanningElement):
(WebCore::RenderBlock::addChildIgnoringAnonymousColumnBlocks):
(WebCore::getInlineRun):
(WebCore::RenderBlock::isSelfCollapsingBlock):
(WebCore::RenderBlock::layoutBlock):
(WebCore::RenderBlock::addOverflowFromBlockChildren):
(WebCore::RenderBlock::expandsToEncloseOverhangingFloats):
(WebCore::RenderBlock::handlePositionedChild):
(WebCore::RenderBlock::moveRunInUnderSiblingBlockIfNeeded):
(WebCore::RenderBlock::collapseMargins):
(WebCore::RenderBlock::clearFloatsIfNeeded):
(WebCore::RenderBlock::simplifiedNormalFlowLayout):
(WebCore::RenderBlock::isSelectionRoot):
(WebCore::RenderBlock::blockSelectionGaps):
(WebCore::RenderBlock::clearFloats):
(WebCore::RenderBlock::markAllDescendantsWithFloatsForLayout):
(WebCore::RenderBlock::markSiblingsWithFloatsForLayout):
(WebCore::isChildHitTestCandidate):
(WebCore::InlineMinMaxIterator::next):
(WebCore::RenderBlock::computeBlockPreferredLogicalWidths):
(WebCore::RenderBlock::firstLineBoxBaseline):
(WebCore::RenderBlock::lastLineBoxBaseline):
(WebCore::RenderBlock::updateFirstLetter):
(WebCore::shouldCheckLines):
(WebCore::getHeightForLineCount):
(WebCore::RenderBlock::adjustForBorderFit):
(WebCore::inNormalFlow):
(WebCore::RenderBlock::adjustLinePositionForPagination):
(WebCore::RenderBlock::adjustBlockChildForPagination):
(WebCore::RenderBlock::renderName):
* rendering/RenderBlock.h:
(WebCore::RenderBlock::shouldSkipCreatingRunsForObject):
* rendering/RenderBlockLineLayout.cpp:
(WebCore::RenderBlock::setMarginsForRubyRun):
(WebCore::RenderBlock::computeInlineDirectionPositionsForLine):
(WebCore::RenderBlock::computeBlockDirectionPositionsForLine):
(WebCore::RenderBlock::layoutInlineChildren):
(WebCore::requiresLineBox):
(WebCore::RenderBlock::LineBreaker::skipTrailingWhitespace):
(WebCore::RenderBlock::LineBreaker::skipLeadingWhitespace):
(WebCore::RenderBlock::LineBreaker::nextLineBreak):
* rendering/RenderBox.cpp:
(WebCore::RenderBox::removeFloatingOrPositionedChildFromBlockLists):
(WebCore::RenderBox::styleWillChange):
(WebCore::RenderBox::styleDidChange):
(WebCore::RenderBox::updateBoxModelInfoFromStyle):
(WebCore::RenderBox::offsetFromContainer):
(WebCore::RenderBox::positionLineBox):
(WebCore::RenderBox::computeRectForRepaint):
(WebCore::RenderBox::computeLogicalWidthInRegion):
(WebCore::RenderBox::renderBoxRegionInfo):
(WebCore::RenderBox::computeLogicalHeight):
(WebCore::RenderBox::computePercentageLogicalHeight):
(WebCore::RenderBox::computeReplacedLogicalWidthUsing):
(WebCore::RenderBox::computeReplacedLogicalHeightUsing):
(WebCore::RenderBox::availableLogicalHeightUsing):
(WebCore::percentageLogicalHeightIsResolvable):
* rendering/RenderBox.h:
(WebCore::RenderBox::stretchesToViewport):
(WebCore::RenderBox::isDeprecatedFlexItem):
* rendering/RenderBoxModelObject.cpp:
(WebCore::RenderBoxModelObject::adjustedPositionRelativeToOffsetParent):
(WebCore::RenderBoxModelObject::mapAbsoluteToLocalPoint):
* rendering/RenderBoxModelObject.h:
(WebCore::RenderBoxModelObject::requiresLayer):
* rendering/RenderDeprecatedFlexibleBox.cpp:
(WebCore::childDoesNotAffectWidthOrFlexing):
(WebCore::RenderDeprecatedFlexibleBox::layoutBlock):
(WebCore::RenderDeprecatedFlexibleBox::layoutHorizontalBox):
(WebCore::RenderDeprecatedFlexibleBox::layoutVerticalBox):
(WebCore::RenderDeprecatedFlexibleBox::renderName):
* rendering/RenderFieldset.cpp:
(WebCore::RenderFieldset::findLegend):
* rendering/RenderFlexibleBox.cpp:
(WebCore::RenderFlexibleBox::computePreferredLogicalWidths):
(WebCore::RenderFlexibleBox::autoMarginOffsetInMainAxis):
(WebCore::RenderFlexibleBox::availableAlignmentSpaceForChild):
(WebCore::RenderFlexibleBox::computeMainAxisPreferredSizes):
(WebCore::RenderFlexibleBox::computeNextFlexLine):
(WebCore::RenderFlexibleBox::resolveFlexibleLengths):
(WebCore::RenderFlexibleBox::prepareChildForPositionedLayout):
(WebCore::RenderFlexibleBox::layoutAndPlaceChildren):
(WebCore::RenderFlexibleBox::layoutColumnReverse):
(WebCore::RenderFlexibleBox::adjustAlignmentForChild):
(WebCore::RenderFlexibleBox::flipForRightToLeftColumn):
* rendering/RenderGrid.cpp:
(WebCore::RenderGrid::renderName):
* rendering/RenderImage.cpp:
(WebCore::RenderImage::computeIntrinsicRatioInformation):
* rendering/RenderInline.cpp:
(WebCore::RenderInline::addChildIgnoringContinuation):
(WebCore::RenderInline::addChildToContinuation):
(WebCore::RenderInline::generateCulledLineBoxRects):
(WebCore):
(WebCore::RenderInline::culledInlineFirstLineBox):
(WebCore::RenderInline::culledInlineLastLineBox):
(WebCore::RenderInline::culledInlineVisualOverflowBoundingBox):
(WebCore::RenderInline::computeRectForRepaint):
(WebCore::RenderInline::dirtyLineBoxes):
* rendering/RenderLayer.cpp:
(WebCore::checkContainingBlockChainForPagination):
(WebCore::RenderLayer::updateLayerPosition):
(WebCore::isPositionedContainer):
(WebCore::RenderLayer::calculateClipRects):
(WebCore::RenderLayer::shouldBeNormalFlowOnly):
* rendering/RenderLayerCompositor.cpp:
(WebCore::RenderLayerCompositor::requiresCompositingForPosition):
* rendering/RenderLineBoxList.cpp:
(WebCore::RenderLineBoxList::dirtyLinesFromChangedChild):
* rendering/RenderListItem.cpp:
(WebCore::getParentOfFirstLineBox):
* rendering/RenderMultiColumnBlock.cpp:
(WebCore::RenderMultiColumnBlock::renderName):
* rendering/RenderObject.cpp:
(WebCore::RenderObject::markContainingBlocksForLayout):
(WebCore::RenderObject::setPreferredLogicalWidthsDirty):
(WebCore::RenderObject::invalidateContainerPreferredLogicalWidths):
(WebCore::RenderObject::styleWillChange):
(WebCore::RenderObject::offsetParent):
* rendering/RenderObject.h:
(WebCore::RenderObject::isOutOfFlowPositioned):
(WebCore::RenderObject::isInFlowPositioned):
(WebCore::RenderObject::hasClip):
(WebCore::RenderObject::isFloatingOrOutOfFlowPositioned):
* rendering/RenderObjectChildList.cpp:
(WebCore::RenderObjectChildList::removeChildNode):
* rendering/RenderReplaced.cpp:
(WebCore::hasAutoHeightOrContainingBlockWithAutoHeight):
* rendering/RenderRubyRun.cpp:
(WebCore::RenderRubyRun::rubyText):
* rendering/RenderTable.cpp:
(WebCore::RenderTable::addChild):
(WebCore::RenderTable::computeLogicalWidth):
(WebCore::RenderTable::layout):
* rendering/style/RenderStyle.h:
Source/WebKit/blackberry:
* Api/WebPage.cpp:
(BlackBerry::WebKit::isPositionedContainer):
(BlackBerry::WebKit::isNonRenderViewFixedPositionedContainer):
(BlackBerry::WebKit::isFixedPositionedContainer):
Source/WebKit2:
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::updateOffsetFromViewportForSelf):
git-svn-id: svn://svn.chromium.org/blink/trunk@121123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | static PassRefPtr<CSSValue> getPositionOffsetValue(RenderStyle* style, CSSPropertyID propertyID, RenderView* renderView)
{
if (!style)
return 0;
Length l;
switch (propertyID) {
case CSSPropertyLeft:
l = style->left();
break;
case CSSPropertyRight:
l = style->right();
break;
case CSSPropertyTop:
l = style->top();
break;
case CSSPropertyBottom:
l = style->bottom();
break;
default:
return 0;
}
if (style->position() == AbsolutePosition || style->position() == FixedPosition) {
if (l.type() == WebCore::Fixed)
return zoomAdjustedPixelValue(l.value(), style);
else if (l.isViewportPercentage())
return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style);
return cssValuePool().createValue(l);
}
if (style->position() == RelativePosition) {
return cssValuePool().createValue(l);
}
return cssValuePool().createIdentifierValue(CSSValueAuto);
}
| 170,366 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: chrm_modification_init(chrm_modification *me, png_modifier *pm,
PNG_CONST color_encoding *encoding)
{
CIE_color white = white_point(encoding);
/* Original end points: */
me->encoding = encoding;
/* Chromaticities (in fixed point): */
me->wx = fix(chromaticity_x(white));
me->wy = fix(chromaticity_y(white));
me->rx = fix(chromaticity_x(encoding->red));
me->ry = fix(chromaticity_y(encoding->red));
me->gx = fix(chromaticity_x(encoding->green));
me->gy = fix(chromaticity_y(encoding->green));
me->bx = fix(chromaticity_x(encoding->blue));
me->by = fix(chromaticity_y(encoding->blue));
modification_init(&me->this);
me->this.chunk = CHUNK_cHRM;
me->this.modify_fn = chrm_modify;
me->this.add = CHUNK_PLTE;
me->this.next = pm->modifications;
pm->modifications = &me->this;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | chrm_modification_init(chrm_modification *me, png_modifier *pm,
const color_encoding *encoding)
{
CIE_color white = white_point(encoding);
/* Original end points: */
me->encoding = encoding;
/* Chromaticities (in fixed point): */
me->wx = fix(chromaticity_x(white));
me->wy = fix(chromaticity_y(white));
me->rx = fix(chromaticity_x(encoding->red));
me->ry = fix(chromaticity_y(encoding->red));
me->gx = fix(chromaticity_x(encoding->green));
me->gy = fix(chromaticity_y(encoding->green));
me->bx = fix(chromaticity_x(encoding->blue));
me->by = fix(chromaticity_y(encoding->blue));
modification_init(&me->this);
me->this.chunk = CHUNK_cHRM;
me->this.modify_fn = chrm_modify;
me->this.add = CHUNK_PLTE;
me->this.next = pm->modifications;
pm->modifications = &me->this;
}
| 173,606 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetMountLibrary(
MountLibrary* library, bool own) {
library_->mount_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void CrosLibrary::TestApi::SetMountLibrary(
| 170,641 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PasswordAutofillManager::OnShowPasswordSuggestions(
int key,
base::i18n::TextDirection text_direction,
const base::string16& typed_username,
int options,
const gfx::RectF& bounds) {
std::vector<autofill::Suggestion> suggestions;
LoginToPasswordInfoMap::const_iterator fill_data_it =
login_to_password_info_.find(key);
if (fill_data_it == login_to_password_info_.end()) {
NOTREACHED();
return;
}
GetSuggestions(fill_data_it->second, typed_username, &suggestions,
(options & autofill::SHOW_ALL) != 0,
(options & autofill::IS_PASSWORD_FIELD) != 0);
form_data_key_ = key;
if (suggestions.empty()) {
autofill_client_->HideAutofillPopup();
return;
}
if (options & autofill::IS_PASSWORD_FIELD) {
autofill::Suggestion password_field_suggestions(l10n_util::GetStringUTF16(
IDS_AUTOFILL_PASSWORD_FIELD_SUGGESTIONS_TITLE));
password_field_suggestions.frontend_id = autofill::POPUP_ITEM_ID_TITLE;
suggestions.insert(suggestions.begin(), password_field_suggestions);
}
GURL origin = (fill_data_it->second).origin;
bool is_context_secure = autofill_client_->IsContextSecure() &&
(!origin.is_valid() || !origin.SchemeIs("http"));
if (!is_context_secure && security_state::IsHttpWarningInFormEnabled()) {
std::string icon_str;
if (origin.is_valid() && origin.SchemeIs("http")) {
icon_str = "httpWarning";
} else {
icon_str = "httpsInvalid";
}
autofill::Suggestion http_warning_suggestion(
l10n_util::GetStringUTF8(IDS_AUTOFILL_LOGIN_HTTP_WARNING_MESSAGE),
l10n_util::GetStringUTF8(IDS_AUTOFILL_HTTP_WARNING_LEARN_MORE),
icon_str, autofill::POPUP_ITEM_ID_HTTP_NOT_SECURE_WARNING_MESSAGE);
#if !defined(OS_ANDROID)
suggestions.insert(suggestions.begin(), autofill::Suggestion());
suggestions.front().frontend_id = autofill::POPUP_ITEM_ID_SEPARATOR;
#endif
suggestions.insert(suggestions.begin(), http_warning_suggestion);
if (!did_show_form_not_secure_warning_) {
did_show_form_not_secure_warning_ = true;
metrics_util::LogShowedFormNotSecureWarningOnCurrentNavigation();
}
}
if (ShouldShowManualFallbackForPreLollipop(
autofill_client_->GetSyncService())) {
if (base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksFilling) &&
(options & autofill::IS_PASSWORD_FIELD) && password_client_ &&
password_client_->IsFillingFallbackEnabledForCurrentPage()) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_SHOW_ALL_SAVED_FALLBACK,
autofill::POPUP_ITEM_ID_ALL_SAVED_PASSWORDS_ENTRY, &suggestions);
show_all_saved_passwords_shown_context_ =
metrics_util::SHOW_ALL_SAVED_PASSWORDS_CONTEXT_PASSWORD;
metrics_util::LogContextOfShowAllSavedPasswordsShown(
show_all_saved_passwords_shown_context_);
}
if (base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksGeneration) &&
password_manager_util::GetPasswordSyncState(
autofill_client_->GetSyncService()) == SYNCING_NORMAL_ENCRYPTION) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_GENERATE_PASSWORD_FALLBACK,
autofill::POPUP_ITEM_ID_GENERATE_PASSWORD_ENTRY, &suggestions);
}
}
autofill_client_->ShowAutofillPopup(bounds,
text_direction,
suggestions,
weak_ptr_factory_.GetWeakPtr());
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <[email protected]>
Commit-Queue: NIKHIL SAHNI <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534923}
CWE ID: CWE-264 | void PasswordAutofillManager::OnShowPasswordSuggestions(
int key,
base::i18n::TextDirection text_direction,
const base::string16& typed_username,
int options,
const gfx::RectF& bounds) {
std::vector<autofill::Suggestion> suggestions;
LoginToPasswordInfoMap::const_iterator fill_data_it =
login_to_password_info_.find(key);
if (fill_data_it == login_to_password_info_.end()) {
NOTREACHED();
return;
}
GetSuggestions(fill_data_it->second, typed_username, &suggestions,
(options & autofill::SHOW_ALL) != 0,
(options & autofill::IS_PASSWORD_FIELD) != 0);
form_data_key_ = key;
if (suggestions.empty()) {
autofill_client_->HideAutofillPopup();
return;
}
if (options & autofill::IS_PASSWORD_FIELD) {
autofill::Suggestion password_field_suggestions(l10n_util::GetStringUTF16(
IDS_AUTOFILL_PASSWORD_FIELD_SUGGESTIONS_TITLE));
password_field_suggestions.frontend_id = autofill::POPUP_ITEM_ID_TITLE;
suggestions.insert(suggestions.begin(), password_field_suggestions);
}
GURL origin = (fill_data_it->second).origin;
bool is_context_secure = autofill_client_->IsContextSecure() &&
(!origin.is_valid() || !origin.SchemeIs("http"));
if (!is_context_secure && security_state::IsHttpWarningInFormEnabled()) {
std::string icon_str;
if (origin.is_valid() && origin.SchemeIs("http")) {
icon_str = "httpWarning";
} else {
icon_str = "httpsInvalid";
}
autofill::Suggestion http_warning_suggestion(
l10n_util::GetStringUTF8(IDS_AUTOFILL_LOGIN_HTTP_WARNING_MESSAGE),
l10n_util::GetStringUTF8(IDS_AUTOFILL_HTTP_WARNING_LEARN_MORE),
icon_str, autofill::POPUP_ITEM_ID_HTTP_NOT_SECURE_WARNING_MESSAGE);
#if !defined(OS_ANDROID)
suggestions.insert(suggestions.begin(), autofill::Suggestion());
suggestions.front().frontend_id = autofill::POPUP_ITEM_ID_SEPARATOR;
#endif
suggestions.insert(suggestions.begin(), http_warning_suggestion);
if (!did_show_form_not_secure_warning_) {
did_show_form_not_secure_warning_ = true;
metrics_util::LogShowedFormNotSecureWarningOnCurrentNavigation();
}
}
if (ShouldShowManualFallbackForPreLollipop(
autofill_client_->GetSyncService())) {
if (base::FeatureList::IsEnabled(
password_manager::features::kManualFallbacksFilling) &&
(options & autofill::IS_PASSWORD_FIELD) && password_client_ &&
password_client_->IsFillingFallbackEnabledForCurrentPage()) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_SHOW_ALL_SAVED_FALLBACK,
autofill::POPUP_ITEM_ID_ALL_SAVED_PASSWORDS_ENTRY, &suggestions);
show_all_saved_passwords_shown_context_ =
metrics_util::SHOW_ALL_SAVED_PASSWORDS_CONTEXT_PASSWORD;
metrics_util::LogContextOfShowAllSavedPasswordsShown(
show_all_saved_passwords_shown_context_);
}
if (base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksGeneration) &&
password_manager_util::GetPasswordSyncState(
autofill_client_->GetSyncService()) == SYNCING_NORMAL_ENCRYPTION) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_GENERATE_PASSWORD_FALLBACK,
autofill::POPUP_ITEM_ID_GENERATE_PASSWORD_ENTRY, &suggestions);
}
}
autofill_client_->ShowAutofillPopup(bounds,
text_direction,
suggestions,
weak_ptr_factory_.GetWeakPtr());
}
| 171,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CompositedLayerRasterInvalidatorTest& Properties(
const TransformPaintPropertyNode* t,
const ClipPaintPropertyNode* c = ClipPaintPropertyNode::Root(),
const EffectPaintPropertyNode* e = EffectPaintPropertyNode::Root()) {
auto& state = data_.chunks.back().properties;
state.SetTransform(t);
state.SetClip(c);
state.SetEffect(e);
return *this;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | CompositedLayerRasterInvalidatorTest& Properties(
const PropertyTreeState& state) {
data_.chunks.back().properties = state;
return *this;
}
| 171,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext4_mb_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
mb_cache_entry_release(ce);
}
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only 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 buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh)
ext4_xattr_cache_insert(struct mb2_cache *ext4_mb_cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
int error;
error = mb2_cache_entry_create(ext4_mb_cache, GFP_NOFS, hash,
bh->b_blocknr);
if (error) {
if (error == -EBUSY)
ea_bdebug(bh, "already in cache");
} else
ea_bdebug(bh, "inserting [%x]", (int)hash);
}
| 169,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GLSurfaceEGLSurfaceControl::CommitPendingTransaction(
SwapCompletionCallback completion_callback,
PresentationCallback present_callback) {
DCHECK(pending_transaction_);
ResourceRefs resources_to_release;
resources_to_release.swap(current_frame_resources_);
current_frame_resources_.clear();
current_frame_resources_.swap(pending_frame_resources_);
pending_frame_resources_.clear();
SurfaceControl::Transaction::OnCompleteCb callback = base::BindOnce(
&GLSurfaceEGLSurfaceControl::OnTransactionAckOnGpuThread,
weak_factory_.GetWeakPtr(), std::move(completion_callback),
std::move(present_callback), std::move(resources_to_release));
pending_transaction_->SetOnCompleteCb(std::move(callback), gpu_task_runner_);
pending_transaction_->Apply();
pending_transaction_.reset();
DCHECK_GE(surface_list_.size(), pending_surfaces_count_);
surface_list_.resize(pending_surfaces_count_);
pending_surfaces_count_ = 0u;
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | void GLSurfaceEGLSurfaceControl::CommitPendingTransaction(
const gfx::Rect& damage_rect,
SwapCompletionCallback completion_callback,
PresentationCallback present_callback) {
DCHECK(pending_transaction_);
// Mark the intersection of a surface's rect with the damage rect as the dirty
// rect for that surface.
DCHECK_LE(pending_surfaces_count_, surface_list_.size());
for (size_t i = 0; i < pending_surfaces_count_; ++i) {
const auto& surface_state = surface_list_[i];
if (!surface_state.buffer_updated_in_pending_transaction)
continue;
gfx::Rect surface_damage_rect = surface_state.dst;
surface_damage_rect.Intersect(damage_rect);
pending_transaction_->SetDamageRect(*surface_state.surface,
surface_damage_rect);
}
ResourceRefs resources_to_release;
resources_to_release.swap(current_frame_resources_);
current_frame_resources_.clear();
current_frame_resources_.swap(pending_frame_resources_);
pending_frame_resources_.clear();
SurfaceControl::Transaction::OnCompleteCb callback = base::BindOnce(
&GLSurfaceEGLSurfaceControl::OnTransactionAckOnGpuThread,
weak_factory_.GetWeakPtr(), std::move(completion_callback),
std::move(present_callback), std::move(resources_to_release));
pending_transaction_->SetOnCompleteCb(std::move(callback), gpu_task_runner_);
pending_transaction_->Apply();
pending_transaction_.reset();
DCHECK_GE(surface_list_.size(), pending_surfaces_count_);
surface_list_.resize(pending_surfaces_count_);
pending_surfaces_count_ = 0u;
}
| 172,108 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct nfs4_state *state;
struct rpc_cred *cred;
int status = 0;
cred = rpc_lookup_cred();
if (IS_ERR(cred)) {
status = PTR_ERR(cred);
goto out;
}
state = nfs4_do_open(dir, &path, flags, sattr, cred);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out_putcred;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
if (flags & O_EXCL) {
struct nfs_fattr fattr;
status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, &fattr);
}
if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)
status = nfs4_intent_set_file(nd, &path, state);
else
nfs4_close_sync(&path, state, flags);
out_putcred:
put_rpccred(cred);
out:
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct nfs4_state *state;
struct rpc_cred *cred;
fmode_t fmode = flags & (FMODE_READ | FMODE_WRITE);
int status = 0;
cred = rpc_lookup_cred();
if (IS_ERR(cred)) {
status = PTR_ERR(cred);
goto out;
}
state = nfs4_do_open(dir, &path, fmode, flags, sattr, cred);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out_putcred;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
if (flags & O_EXCL) {
struct nfs_fattr fattr;
status = nfs4_do_setattr(state->inode, cred, &fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, &fattr);
}
if (status == 0 && (nd->flags & LOOKUP_OPEN) != 0)
status = nfs4_intent_set_file(nd, &path, state, fmode);
else
nfs4_close_sync(&path, state, fmode);
out_putcred:
put_rpccred(cred);
out:
return status;
}
| 165,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
int *peeked, int *off, int *err)
{
struct sk_buff *skb;
long timeo;
/*
* Caller is allowed not to check sk->sk_err before skb_recv_datagram()
*/
int error = sock_error(sk);
if (error)
goto no_packet;
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
/* Again only user level code calls this function, so nothing
* interrupt level will suddenly eat the receive_queue.
*
* Look at current nfs client by the way...
* However, this function was correct in any case. 8)
*/
unsigned long cpu_flags;
struct sk_buff_head *queue = &sk->sk_receive_queue;
spin_lock_irqsave(&queue->lock, cpu_flags);
skb_queue_walk(queue, skb) {
*peeked = skb->peeked;
if (flags & MSG_PEEK) {
if (*off >= skb->len) {
*off -= skb->len;
continue;
}
skb->peeked = 1;
atomic_inc(&skb->users);
} else
__skb_unlink(skb, queue);
spin_unlock_irqrestore(&queue->lock, cpu_flags);
return skb;
}
spin_unlock_irqrestore(&queue->lock, cpu_flags);
/* User doesn't want to wait */
error = -EAGAIN;
if (!timeo)
goto no_packet;
} while (!wait_for_packet(sk, err, &timeo));
return NULL;
no_packet:
*err = error;
return NULL;
}
Commit Message: net: fix infinite loop in __skb_recv_datagram()
Tommi was fuzzing with trinity and reported the following problem :
commit 3f518bf745 (datagram: Add offset argument to __skb_recv_datagram)
missed that a raw socket receive queue can contain skbs with no payload.
We can loop in __skb_recv_datagram() with MSG_PEEK mode, because
wait_for_packet() is not prepared to skip these skbs.
[ 83.541011] INFO: rcu_sched detected stalls on CPUs/tasks: {}
(detected by 0, t=26002 jiffies, g=27673, c=27672, q=75)
[ 83.541011] INFO: Stall ended before state dump start
[ 108.067010] BUG: soft lockup - CPU#0 stuck for 22s! [trinity-child31:2847]
...
[ 108.067010] Call Trace:
[ 108.067010] [<ffffffff818cc103>] __skb_recv_datagram+0x1a3/0x3b0
[ 108.067010] [<ffffffff818cc33d>] skb_recv_datagram+0x2d/0x30
[ 108.067010] [<ffffffff819ed43d>] rawv6_recvmsg+0xad/0x240
[ 108.067010] [<ffffffff818c4b04>] sock_common_recvmsg+0x34/0x50
[ 108.067010] [<ffffffff818bc8ec>] sock_recvmsg+0xbc/0xf0
[ 108.067010] [<ffffffff818bf31e>] sys_recvfrom+0xde/0x150
[ 108.067010] [<ffffffff81ca4329>] system_call_fastpath+0x16/0x1b
Reported-by: Tommi Rantala <[email protected]>
Tested-by: Tommi Rantala <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Pavel Emelyanov <[email protected]>
Acked-by: Pavel Emelyanov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
int *peeked, int *off, int *err)
{
struct sk_buff *skb;
long timeo;
/*
* Caller is allowed not to check sk->sk_err before skb_recv_datagram()
*/
int error = sock_error(sk);
if (error)
goto no_packet;
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
/* Again only user level code calls this function, so nothing
* interrupt level will suddenly eat the receive_queue.
*
* Look at current nfs client by the way...
* However, this function was correct in any case. 8)
*/
unsigned long cpu_flags;
struct sk_buff_head *queue = &sk->sk_receive_queue;
spin_lock_irqsave(&queue->lock, cpu_flags);
skb_queue_walk(queue, skb) {
*peeked = skb->peeked;
if (flags & MSG_PEEK) {
if (*off >= skb->len && skb->len) {
*off -= skb->len;
continue;
}
skb->peeked = 1;
atomic_inc(&skb->users);
} else
__skb_unlink(skb, queue);
spin_unlock_irqrestore(&queue->lock, cpu_flags);
return skb;
}
spin_unlock_irqrestore(&queue->lock, cpu_flags);
/* User doesn't want to wait */
error = -EAGAIN;
if (!timeo)
goto no_packet;
} while (!wait_for_packet(sk, err, &timeo));
return NULL;
no_packet:
*err = error;
return NULL;
}
| 166,144 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintViewManager::PrintPreviewDone() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_NE(NOT_PREVIEWING, print_preview_state_);
if (print_preview_state_ == SCRIPTED_PREVIEW) {
auto& map = g_scripted_print_preview_closure_map.Get();
auto it = map.find(scripted_print_preview_rph_);
CHECK(it != map.end());
it->second.Run();
map.erase(it);
scripted_print_preview_rph_ = nullptr;
}
print_preview_state_ = NOT_PREVIEWING;
print_preview_rfh_ = nullptr;
}
Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated().
BUG=694382,698622
Review-Url: https://codereview.chromium.org/2742853003
Cr-Commit-Position: refs/heads/master@{#457363}
CWE ID: CWE-125 | void PrintViewManager::PrintPreviewDone() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (print_preview_state_ == NOT_PREVIEWING)
return;
if (print_preview_state_ == SCRIPTED_PREVIEW) {
auto& map = g_scripted_print_preview_closure_map.Get();
auto it = map.find(scripted_print_preview_rph_);
CHECK(it != map.end());
it->second.Run();
map.erase(it);
scripted_print_preview_rph_ = nullptr;
}
print_preview_state_ = NOT_PREVIEWING;
print_preview_rfh_ = nullptr;
}
| 172,404 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SniffMimeType(const char* content,
size_t content_size,
const GURL& url,
const std::string& type_hint,
std::string* result) {
DCHECK_LT(content_size, 1000000U); // sanity check
DCHECK(content);
DCHECK(result);
bool have_enough_content = true;
result->assign(type_hint);
if (IsOfficeType(type_hint))
return SniffForInvalidOfficeDocs(content, content_size, url, result);
const bool hint_is_unknown_mime_type = IsUnknownMimeType(type_hint);
if (hint_is_unknown_mime_type && !url.SchemeIsFile() &&
SniffForHTML(content, content_size, &have_enough_content, result)) {
return true;
}
const bool hint_is_text_plain = (type_hint == "text/plain");
if (hint_is_unknown_mime_type || hint_is_text_plain) {
if (!SniffBinary(content, content_size, &have_enough_content, result)) {
if (hint_is_text_plain) {
return have_enough_content;
}
}
}
if (type_hint == "text/xml" || type_hint == "application/xml") {
if (SniffXML(content, content_size, &have_enough_content, result))
return true;
return have_enough_content;
}
if (SniffCRX(content, content_size, url, type_hint,
&have_enough_content, result))
return true;
if (SniffForOfficeDocs(content, content_size, url,
&have_enough_content, result))
return true; // We've matched a magic number. No more content needed.
if (type_hint == "application/octet-stream")
return have_enough_content;
if (SniffForMagicNumbers(content, content_size,
&have_enough_content, result))
return true; // We've matched a magic number. No more content needed.
return have_enough_content;
}
Commit Message: Revert "Don't sniff HTML from documents delivered via the file protocol"
This reverts commit 3519e867dc606437f804561f889d7ed95b95876a.
Reason for revert: crbug.com/786150. Application compatibility for Android WebView applications means we need to allow sniffing on that platform.
Original change's description:
> Don't sniff HTML from documents delivered via the file protocol
>
> To reduce attack surface, Chrome should not MIME-sniff to text/html for
> any document delivered via the file protocol. This change only impacts
> the file protocol (documents served via HTTP/HTTPS/etc are unaffected).
>
> Bug: 777737
> Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet
> Change-Id: I7086454356b8d2d092be9e1bca0f5ff6dd3b62c0
> Reviewed-on: https://chromium-review.googlesource.com/751402
> Reviewed-by: Ben Wells <[email protected]>
> Reviewed-by: Sylvain Defresne <[email protected]>
> Reviewed-by: Achuith Bhandarkar <[email protected]>
> Reviewed-by: Asanka Herath <[email protected]>
> Reviewed-by: Matt Menke <[email protected]>
> Commit-Queue: Eric Lawrence <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#514372}
[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 777737
Change-Id: I864ae060ce3277d41ea257ae75e0b80c51f3ea98
Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet
Reviewed-on: https://chromium-review.googlesource.com/790790
Reviewed-by: Eric Lawrence <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#519347}
CWE ID: | bool SniffMimeType(const char* content,
size_t content_size,
const GURL& url,
const std::string& type_hint,
std::string* result) {
DCHECK_LT(content_size, 1000000U); // sanity check
DCHECK(content);
DCHECK(result);
bool have_enough_content = true;
result->assign(type_hint);
if (IsOfficeType(type_hint))
return SniffForInvalidOfficeDocs(content, content_size, url, result);
const bool hint_is_unknown_mime_type = IsUnknownMimeType(type_hint);
// First check for HTML
if (hint_is_unknown_mime_type) {
// We're only willing to sniff HTML if the server has not supplied a mime
// type, or if the type it did supply indicates that it doesn't know what
// the type should be.
if (SniffForHTML(content, content_size, &have_enough_content, result))
return true; // We succeeded in sniffing HTML. No more content needed.
}
const bool hint_is_text_plain = (type_hint == "text/plain");
if (hint_is_unknown_mime_type || hint_is_text_plain) {
if (!SniffBinary(content, content_size, &have_enough_content, result)) {
if (hint_is_text_plain) {
return have_enough_content;
}
}
}
if (type_hint == "text/xml" || type_hint == "application/xml") {
if (SniffXML(content, content_size, &have_enough_content, result))
return true;
return have_enough_content;
}
if (SniffCRX(content, content_size, url, type_hint,
&have_enough_content, result))
return true;
if (SniffForOfficeDocs(content, content_size, url,
&have_enough_content, result))
return true; // We've matched a magic number. No more content needed.
if (type_hint == "application/octet-stream")
return have_enough_content;
if (SniffForMagicNumbers(content, content_size,
&have_enough_content, result))
return true; // We've matched a magic number. No more content needed.
return have_enough_content;
}
| 172,739 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
int err;
struct sk_buff *skb;
struct sock *sk = sock->sk;
err = -EIO;
if (sk->sk_state & PPPOX_BOUND)
goto end;
msg->msg_namelen = 0;
err = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
goto end;
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);
if (likely(err == 0))
err = len;
kfree_skb(skb);
end:
return err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
int err;
struct sk_buff *skb;
struct sock *sk = sock->sk;
err = -EIO;
if (sk->sk_state & PPPOX_BOUND)
goto end;
err = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
goto end;
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);
if (likely(err == 0))
err = len;
kfree_skb(skb);
end:
return err;
}
| 166,505 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: init_device (u2fh_devs * devs, struct u2fdevice *dev)
{
unsigned char resp[1024];
unsigned char nonce[8];
if (obtain_nonce(nonce) != 0)
{
return U2FH_TRANSPORT_ERROR;
}
size_t resplen = sizeof (resp);
dev->cid = CID_BROADCAST;
if (u2fh_sendrecv
(devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp,
&resplen) == U2FH_OK)
{
U2FHID_INIT_RESP initresp;
if (resplen > sizeof (initresp))
{
return U2FH_MEMORY_ERROR;
}
memcpy (&initresp, resp, resplen);
dev->cid = initresp.cid;
dev->versionInterface = initresp.versionInterface;
dev->versionMajor = initresp.versionMajor;
dev->versionMinor = initresp.versionMinor;
dev->capFlags = initresp.capFlags;
}
else
{
return U2FH_TRANSPORT_ERROR;
}
return U2FH_OK;
}
Commit Message: fix filling out of initresp
CWE ID: CWE-119 | init_device (u2fh_devs * devs, struct u2fdevice *dev)
{
unsigned char resp[1024];
unsigned char nonce[8];
if (obtain_nonce(nonce) != 0)
{
return U2FH_TRANSPORT_ERROR;
}
size_t resplen = sizeof (resp);
dev->cid = CID_BROADCAST;
if (u2fh_sendrecv
(devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp,
&resplen) == U2FH_OK)
{
int offs = sizeof (nonce);
/* the response has to be atleast 17 bytes, if it's more we discard that */
if (resplen < 17)
{
return U2FH_SIZE_ERROR;
}
/* incoming and outgoing nonce has to match */
if (memcmp (nonce, resp, sizeof (nonce)) != 0)
{
return U2FH_TRANSPORT_ERROR;
}
dev->cid =
resp[offs] << 24 | resp[offs + 1] << 16 | resp[offs +
2] << 8 | resp[offs +
3];
offs += 4;
dev->versionInterface = resp[offs++];
dev->versionMajor = resp[offs++];
dev->versionMinor = resp[offs++];
dev->versionBuild = resp[offs++];
dev->capFlags = resp[offs++];
}
else
{
return U2FH_TRANSPORT_ERROR;
}
return U2FH_OK;
}
| 169,721 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PassOwnPtr<GraphicsContext> UpdateAtlas::beginPaintingOnAvailableBuffer(ShareableSurface::Handle& handle, const WebCore::IntSize& size, IntPoint& offset)
{
buildLayoutIfNeeded();
IntRect rect = m_areaAllocator->allocate(size);
if (rect.isEmpty())
return PassOwnPtr<GraphicsContext>();
if (!m_surface->createHandle(handle))
return PassOwnPtr<WebCore::GraphicsContext>();
offset = rect.location();
OwnPtr<GraphicsContext> graphicsContext = m_surface->createGraphicsContext(rect);
if (flags() & ShareableBitmap::SupportsAlpha) {
graphicsContext->setCompositeOperation(CompositeCopy);
graphicsContext->fillRect(IntRect(IntPoint::zero(), size), Color::transparent, ColorSpaceDeviceRGB);
graphicsContext->setCompositeOperation(CompositeSourceOver);
}
return graphicsContext.release();
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | PassOwnPtr<GraphicsContext> UpdateAtlas::beginPaintingOnAvailableBuffer(ShareableSurface::Handle& handle, const WebCore::IntSize& size, IntPoint& offset)
{
m_inactivityInSeconds = 0;
buildLayoutIfNeeded();
IntRect rect = m_areaAllocator->allocate(size);
if (rect.isEmpty())
return PassOwnPtr<GraphicsContext>();
if (!m_surface->createHandle(handle))
return PassOwnPtr<WebCore::GraphicsContext>();
offset = rect.location();
OwnPtr<GraphicsContext> graphicsContext = m_surface->createGraphicsContext(rect);
if (flags() & ShareableBitmap::SupportsAlpha) {
graphicsContext->setCompositeOperation(CompositeCopy);
graphicsContext->fillRect(IntRect(IntPoint::zero(), size), Color::transparent, ColorSpaceDeviceRGB);
graphicsContext->setCompositeOperation(CompositeSourceOver);
}
return graphicsContext.release();
}
| 170,271 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)
{
s->avctx->profile = get_bits(gb, 4);
s->avctx->level = get_bits(gb, 4);
if (s->avctx->profile == 0 && s->avctx->level == 8) {
s->avctx->level = 0;
}
return 0;
}
Commit Message: avcodec/mpeg4videodec: Check read profile before setting it
Fixes: null pointer dereference
Fixes: ffmpeg_crash_7.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
{
*profile = get_bits(gb, 4);
*level = get_bits(gb, 4);
if (*profile == 0 && *level == 8) {
*level = 0;
}
return 0;
}
| 169,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RSA *RSA_generate_key(int bits, unsigned long e_value,
void (*callback)(int,int,void *), void *cb_arg)
{
RSA *rsa=NULL;
BIGNUM *r0=NULL,*r1=NULL,*r2=NULL,*r3=NULL,*tmp;
int bitsp,bitsq,ok= -1,n=0,i;
BN_CTX *ctx=NULL,*ctx2=NULL;
ctx=BN_CTX_new();
if (ctx == NULL) goto err;
ctx2=BN_CTX_new();
if (ctx2 == NULL) goto err;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
r3 = BN_CTX_get(ctx);
if (r3 == NULL) goto err;
bitsp=(bits+1)/2;
bitsq=bits-bitsp;
rsa=RSA_new();
if (rsa == NULL) goto err;
/* set e */
rsa->e=BN_new();
if (rsa->e == NULL) goto err;
#if 1
/* The problem is when building with 8, 16, or 32 BN_ULONG,
* unsigned long can be larger */
for (i=0; i<sizeof(unsigned long)*8; i++)
{
if (e_value & (1<<i))
BN_set_bit(rsa->e,i);
}
#else
if (!BN_set_word(rsa->e,e_value)) goto err;
#endif
/* generate p and q */
for (;;)
{
rsa->p=BN_generate_prime(NULL,bitsp,0,NULL,NULL,callback,cb_arg);
if (rsa->p == NULL) goto err;
if (!BN_sub(r2,rsa->p,BN_value_one())) goto err;
if (!BN_gcd(r1,r2,rsa->e,ctx)) goto err;
if (BN_is_one(r1)) break;
if (callback != NULL) callback(2,n++,cb_arg);
BN_free(rsa->p);
}
if (callback != NULL) callback(3,0,cb_arg);
for (;;)
{
rsa->q=BN_generate_prime(NULL,bitsq,0,NULL,NULL,callback,cb_arg);
if (rsa->q == NULL) goto err;
if (!BN_sub(r2,rsa->q,BN_value_one())) goto err;
if (!BN_gcd(r1,r2,rsa->e,ctx)) goto err;
if (BN_is_one(r1) && (BN_cmp(rsa->p,rsa->q) != 0))
break;
if (callback != NULL) callback(2,n++,cb_arg);
BN_free(rsa->q);
}
if (callback != NULL) callback(3,1,cb_arg);
if (BN_cmp(rsa->p,rsa->q) < 0)
{
tmp=rsa->p;
rsa->p=rsa->q;
rsa->q=tmp;
}
/* calculate n */
rsa->n=BN_new();
if (rsa->n == NULL) goto err;
if (!BN_mul(rsa->n,rsa->p,rsa->q,ctx)) goto err;
/* calculate d */
if (!BN_sub(r1,rsa->p,BN_value_one())) goto err; /* p-1 */
if (!BN_sub(r2,rsa->q,BN_value_one())) goto err; /* q-1 */
if (!BN_mul(r0,r1,r2,ctx)) goto err; /* (p-1)(q-1) */
/* should not be needed, since gcd(p-1,e) == 1 and gcd(q-1,e) == 1 */
/* for (;;)
{
if (!BN_gcd(r3,r0,rsa->e,ctx)) goto err;
if (BN_is_one(r3)) break;
if (1)
{
if (!BN_add_word(rsa->e,2L)) goto err;
continue;
}
RSAerr(RSA_F_RSA_GENERATE_KEY,RSA_R_BAD_E_VALUE);
goto err;
}
*/
rsa->d=BN_mod_inverse(NULL,rsa->e,r0,ctx2); /* d */
if (rsa->d == NULL) goto err;
/* calculate d mod (p-1) */
rsa->dmp1=BN_new();
if (rsa->dmp1 == NULL) goto err;
if (!BN_mod(rsa->dmp1,rsa->d,r1,ctx)) goto err;
/* calculate d mod (q-1) */
rsa->dmq1=BN_new();
if (rsa->dmq1 == NULL) goto err;
if (!BN_mod(rsa->dmq1,rsa->d,r2,ctx)) goto err;
/* calculate inverse of q mod p */
rsa->iqmp=BN_mod_inverse(NULL,rsa->q,rsa->p,ctx2);
if (rsa->iqmp == NULL) goto err;
ok=1;
err:
if (ok == -1)
{
RSAerr(RSA_F_RSA_GENERATE_KEY,ERR_LIB_BN);
ok=0;
}
BN_CTX_end(ctx);
BN_CTX_free(ctx);
BN_CTX_free(ctx2);
if (!ok)
{
if (rsa != NULL) RSA_free(rsa);
return(NULL);
}
else
return(rsa);
}
Commit Message:
CWE ID: CWE-310 | RSA *RSA_generate_key(int bits, unsigned long e_value,
void (*callback)(int,int,void *), void *cb_arg)
{
RSA *rsa=NULL;
BIGNUM *r0=NULL,*r1=NULL,*r2=NULL,*r3=NULL,*tmp;
int bitsp,bitsq,ok= -1,n=0,i;
BN_CTX *ctx=NULL,*ctx2=NULL;
ctx=BN_CTX_new();
if (ctx == NULL) goto err;
ctx2=BN_CTX_new();
if (ctx2 == NULL) goto err;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
r3 = BN_CTX_get(ctx);
if (r3 == NULL) goto err;
bitsp=(bits+1)/2;
bitsq=bits-bitsp;
rsa=RSA_new();
if (rsa == NULL) goto err;
/* set e */
rsa->e=BN_new();
if (rsa->e == NULL) goto err;
#if 1
/* The problem is when building with 8, 16, or 32 BN_ULONG,
* unsigned long can be larger */
for (i=0; i<sizeof(unsigned long)*8; i++)
{
if (e_value & (1UL<<i))
BN_set_bit(rsa->e,i);
}
#else
if (!BN_set_word(rsa->e,e_value)) goto err;
#endif
/* generate p and q */
for (;;)
{
rsa->p=BN_generate_prime(NULL,bitsp,0,NULL,NULL,callback,cb_arg);
if (rsa->p == NULL) goto err;
if (!BN_sub(r2,rsa->p,BN_value_one())) goto err;
if (!BN_gcd(r1,r2,rsa->e,ctx)) goto err;
if (BN_is_one(r1)) break;
if (callback != NULL) callback(2,n++,cb_arg);
BN_free(rsa->p);
}
if (callback != NULL) callback(3,0,cb_arg);
for (;;)
{
rsa->q=BN_generate_prime(NULL,bitsq,0,NULL,NULL,callback,cb_arg);
if (rsa->q == NULL) goto err;
if (!BN_sub(r2,rsa->q,BN_value_one())) goto err;
if (!BN_gcd(r1,r2,rsa->e,ctx)) goto err;
if (BN_is_one(r1) && (BN_cmp(rsa->p,rsa->q) != 0))
break;
if (callback != NULL) callback(2,n++,cb_arg);
BN_free(rsa->q);
}
if (callback != NULL) callback(3,1,cb_arg);
if (BN_cmp(rsa->p,rsa->q) < 0)
{
tmp=rsa->p;
rsa->p=rsa->q;
rsa->q=tmp;
}
/* calculate n */
rsa->n=BN_new();
if (rsa->n == NULL) goto err;
if (!BN_mul(rsa->n,rsa->p,rsa->q,ctx)) goto err;
/* calculate d */
if (!BN_sub(r1,rsa->p,BN_value_one())) goto err; /* p-1 */
if (!BN_sub(r2,rsa->q,BN_value_one())) goto err; /* q-1 */
if (!BN_mul(r0,r1,r2,ctx)) goto err; /* (p-1)(q-1) */
/* should not be needed, since gcd(p-1,e) == 1 and gcd(q-1,e) == 1 */
/* for (;;)
{
if (!BN_gcd(r3,r0,rsa->e,ctx)) goto err;
if (BN_is_one(r3)) break;
if (1)
{
if (!BN_add_word(rsa->e,2L)) goto err;
continue;
}
RSAerr(RSA_F_RSA_GENERATE_KEY,RSA_R_BAD_E_VALUE);
goto err;
}
*/
rsa->d=BN_mod_inverse(NULL,rsa->e,r0,ctx2); /* d */
if (rsa->d == NULL) goto err;
/* calculate d mod (p-1) */
rsa->dmp1=BN_new();
if (rsa->dmp1 == NULL) goto err;
if (!BN_mod(rsa->dmp1,rsa->d,r1,ctx)) goto err;
/* calculate d mod (q-1) */
rsa->dmq1=BN_new();
if (rsa->dmq1 == NULL) goto err;
if (!BN_mod(rsa->dmq1,rsa->d,r2,ctx)) goto err;
/* calculate inverse of q mod p */
rsa->iqmp=BN_mod_inverse(NULL,rsa->q,rsa->p,ctx2);
if (rsa->iqmp == NULL) goto err;
ok=1;
err:
if (ok == -1)
{
RSAerr(RSA_F_RSA_GENERATE_KEY,ERR_LIB_BN);
ok=0;
}
BN_CTX_end(ctx);
BN_CTX_free(ctx);
BN_CTX_free(ctx2);
if (!ok)
{
if (rsa != NULL) RSA_free(rsa);
return(NULL);
}
else
return(rsa);
}
| 165,345 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
Commit Message: (for 4.9.3) CVE-2018-16230/BGP: fix decoding of MP_REACH_NLRI
When bgp_attr_print() tried to decode the variable-length nexthop value
for the NSAP VPN case, it did not check that the declared length is good
to interpret the value as a mapped IPv4 or IPv6 address. Add missing
checks to make this safe.
This fixes a buffer over-read discovered by Include Security working
under the Mozilla SOS program in 2018 by means of code audit.
Bhargava Shastry, SecT/TU Berlin, had independently identified this
vulnerability by means of fuzzing and provided the packet capture file
for the test.
CWE ID: CWE-125 | bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (tlen == BGP_VPN_RD_LEN + 4 + sizeof(struct in_addr)
&& EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (tlen == BGP_VPN_RD_LEN + 3 + sizeof(struct in6_addr)
&& EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
| 169,818 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebString WebPageSerializer::generateBaseTagDeclaration(const WebString& baseTarget)
{
if (baseTarget.isEmpty())
return String("<base href=\".\">");
String baseString = "<base href=\".\" target=\"" + static_cast<const String&>(baseTarget) + "\">";
return baseString;
}
Commit Message: Escape "--" in the page URL at page serialization
This patch makes page serializer to escape the page URL embed into a HTML
comment of result HTML[1] to avoid inserting text as HTML from URL by
introducing a static member function |PageSerialzier::markOfTheWebDeclaration()|
for sharing it between |PageSerialzier| and |WebPageSerialzier| classes.
[1] We use following format for serialized HTML:
saved from url=(${lengthOfURL})${URL}
BUG=503217
TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration
TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu
Review URL: https://codereview.chromium.org/1371323003
Cr-Commit-Position: refs/heads/master@{#351736}
CWE ID: CWE-20 | WebString WebPageSerializer::generateBaseTagDeclaration(const WebString& baseTarget)
{
// TODO(yosin) We should call |PageSerializer::baseTagDeclarationOf()|.
if (baseTarget.isEmpty())
return String("<base href=\".\">");
String baseString = "<base href=\".\" target=\"" + static_cast<const String&>(baseTarget) + "\">";
return baseString;
}
| 171,786 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct timespec ns_to_timespec(const s64 nsec)
{
struct timespec ts;
if (!nsec)
return (struct timespec) {0, 0};
ts.tv_sec = div_long_long_rem_signed(nsec, NSEC_PER_SEC, &ts.tv_nsec);
if (unlikely(nsec < 0))
set_normalized_timespec(&ts, ts.tv_sec, ts.tv_nsec);
return ts;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | struct timespec ns_to_timespec(const s64 nsec)
{
struct timespec ts;
s32 rem;
if (!nsec)
return (struct timespec) {0, 0};
ts.tv_sec = div_s64_rem(nsec, NSEC_PER_SEC, &rem);
if (unlikely(rem < 0)) {
ts.tv_sec--;
rem += NSEC_PER_SEC;
}
ts.tv_nsec = rem;
return ts;
}
| 165,756 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static scoped_refptr<Extension> MakeSyncTestExtension(
SyncTestExtensionType type,
const GURL& update_url,
const GURL& launch_url,
Manifest::Location location,
int num_plugins,
const base::FilePath& extension_path,
int creation_flags) {
base::DictionaryValue source;
source.SetString(keys::kName, "PossiblySyncableExtension");
source.SetString(keys::kVersion, "0.0.0.0");
if (type == APP)
source.SetString(keys::kApp, "true");
if (type == THEME)
source.Set(keys::kTheme, new base::DictionaryValue());
if (!update_url.is_empty()) {
source.SetString(keys::kUpdateURL, update_url.spec());
}
if (!launch_url.is_empty()) {
source.SetString(keys::kLaunchWebURL, launch_url.spec());
}
if (type != THEME) {
source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT);
base::ListValue* plugins = new base::ListValue();
for (int i = 0; i < num_plugins; ++i) {
base::DictionaryValue* plugin = new base::DictionaryValue();
plugin->SetString(keys::kPluginsPath, std::string());
plugins->Set(i, plugin);
}
source.Set(keys::kPlugins, plugins);
}
std::string error;
scoped_refptr<Extension> extension = Extension::Create(
extension_path, location, source, creation_flags, &error);
EXPECT_TRUE(extension.get());
EXPECT_EQ("", error);
return extension;
}
Commit Message: Fix syncing of NPAPI plugins.
This fix adds a check for |plugin| permission
while syncing NPAPI plugins.
BUG=252034
Review URL: https://chromiumcodereview.appspot.com/16816024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | static scoped_refptr<Extension> MakeSyncTestExtension(
static scoped_refptr<Extension> MakeSyncTestExtensionWithPluginPermission(
SyncTestExtensionType type,
const GURL& update_url,
const GURL& launch_url,
Manifest::Location location,
int num_plugins,
const base::FilePath& extension_path,
int creation_flags,
bool has_plugin_permission) {
base::DictionaryValue source;
source.SetString(keys::kName, "PossiblySyncableExtension");
source.SetString(keys::kVersion, "0.0.0.0");
if (type == APP)
source.SetString(keys::kApp, "true");
if (type == THEME)
source.Set(keys::kTheme, new base::DictionaryValue());
if (!update_url.is_empty()) {
source.SetString(keys::kUpdateURL, update_url.spec());
}
if (!launch_url.is_empty()) {
source.SetString(keys::kLaunchWebURL, launch_url.spec());
}
if (type != THEME) {
source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT);
base::ListValue* plugins = new base::ListValue();
for (int i = 0; i < num_plugins; ++i) {
base::DictionaryValue* plugin = new base::DictionaryValue();
plugin->SetString(keys::kPluginsPath, std::string());
plugins->Set(i, plugin);
}
source.Set(keys::kPlugins, plugins);
}
if (has_plugin_permission) {
ListValue* plugins = new ListValue();
plugins->Set(0, new StringValue("plugin"));
source.Set(keys::kPermissions, plugins);
}
std::string error;
scoped_refptr<Extension> extension = Extension::Create(
extension_path, location, source, creation_flags, &error);
EXPECT_TRUE(extension.get());
EXPECT_EQ("", error);
return extension;
}
| 171,249 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fillWidgetStates(AXObject& axObject,
protocol::Array<AXProperty>& properties) {
AccessibilityRole role = axObject.roleValue();
if (roleAllowsChecked(role)) {
AccessibilityButtonState checked = axObject.checkboxOrRadioValue();
switch (checked) {
case ButtonStateOff:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("false", AXValueTypeEnum::Tristate)));
break;
case ButtonStateOn:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("true", AXValueTypeEnum::Tristate)));
break;
case ButtonStateMixed:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("mixed", AXValueTypeEnum::Tristate)));
break;
}
}
AccessibilityExpanded expanded = axObject.isExpanded();
switch (expanded) {
case ExpandedUndefined:
break;
case ExpandedCollapsed:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined)));
break;
case ExpandedExpanded:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
break;
}
if (role == ToggleButtonRole) {
if (!axObject.isPressed()) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("false", AXValueTypeEnum::Tristate)));
} else {
const AtomicString& pressedAttr =
axObject.getAttribute(HTMLNames::aria_pressedAttr);
if (equalIgnoringCase(pressedAttr, "mixed"))
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("mixed", AXValueTypeEnum::Tristate)));
else
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("true", AXValueTypeEnum::Tristate)));
}
}
if (roleAllowsSelected(role)) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Selected,
createBooleanValue(axObject.isSelected())));
}
if (roleAllowsModal(role)) {
properties.addItem(createProperty(AXWidgetStatesEnum::Modal,
createBooleanValue(axObject.isModal())));
}
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | void fillWidgetStates(AXObject& axObject,
protocol::Array<AXProperty>& properties) {
AccessibilityRole role = axObject.roleValue();
if (roleAllowsChecked(role)) {
AccessibilityButtonState checked = axObject.checkboxOrRadioValue();
switch (checked) {
case ButtonStateOff:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("false", AXValueTypeEnum::Tristate)));
break;
case ButtonStateOn:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("true", AXValueTypeEnum::Tristate)));
break;
case ButtonStateMixed:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("mixed", AXValueTypeEnum::Tristate)));
break;
}
}
AccessibilityExpanded expanded = axObject.isExpanded();
switch (expanded) {
case ExpandedUndefined:
break;
case ExpandedCollapsed:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined)));
break;
case ExpandedExpanded:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
break;
}
if (role == ToggleButtonRole) {
if (!axObject.isPressed()) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("false", AXValueTypeEnum::Tristate)));
} else {
const AtomicString& pressedAttr =
axObject.getAttribute(HTMLNames::aria_pressedAttr);
if (equalIgnoringASCIICase(pressedAttr, "mixed"))
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("mixed", AXValueTypeEnum::Tristate)));
else
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("true", AXValueTypeEnum::Tristate)));
}
}
if (roleAllowsSelected(role)) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Selected,
createBooleanValue(axObject.isSelected())));
}
if (roleAllowsModal(role)) {
properties.addItem(createProperty(AXWidgetStatesEnum::Modal,
createBooleanValue(axObject.isModal())));
}
}
| 171,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *p,*buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
inl=i2d(data,NULL);
buf_in=OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
p=buf_in;
i2d(data,&p);
ret=
EVP_VerifyInit_ex(&ctx,type, NULL)
&& EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (!ret)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message: Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
CVE-2014-8275
Reviewed-by: Emilia Käsper <[email protected]>
CWE ID: CWE-310 | int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *p,*buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)
{
ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
goto err;
}
inl=i2d(data,NULL);
buf_in=OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
p=buf_in;
i2d(data,&p);
ret=
EVP_VerifyInit_ex(&ctx,type, NULL)
&& EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (!ret)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
| 169,932 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_get_mic_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_qop_t qop_req,
gss_iov_buffer_desc *iov, int iov_count)
{
return gss_get_mic_iov_length(minor_status, context_handle, qop_req, iov,
iov_count);
}
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_get_mic_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_qop_t qop_req,
gss_iov_buffer_desc *iov, int iov_count)
{
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
return gss_get_mic_iov_length(minor_status, sc->ctx_handle, qop_req, iov,
iov_count);
}
| 166,658 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
Commit Message: aio: fix kernel memory disclosure in io_getevents() introduced in v3.10
A kernel memory disclosure was introduced in aio_read_events_ring() in v3.10
by commit a31ad380bed817aa25f8830ad23e1a0480fef797. The changes made to
aio_read_events_ring() failed to correctly limit the index into
ctx->ring_pages[], allowing an attacked to cause the subsequent kmap() of
an arbitrary page with a copy_to_user() to copy the contents into userspace.
This vulnerability has been assigned CVE-2014-0206. Thanks to Mateusz and
Petr for disclosing this issue.
This patch applies to v3.12+. A separate backport is needed for 3.10/3.11.
Signed-off-by: Benjamin LaHaise <[email protected]>
Cc: Mateusz Guzik <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Kent Overstreet <[email protected]>
Cc: Jeff Moyer <[email protected]>
Cc: [email protected]
CWE ID: | static long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
head %= ctx->nr_events;
tail %= ctx->nr_events;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
| 166,448 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = joinbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
srcptr += stride;
dstptr += JPC_QMFB_COLGRPSIZE;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec
that was caused by a buffer being allocated with a size that was too small
in some cases.
Added a new regression test case.
CWE ID: CWE-119 | void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = joinbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE,
sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
srcptr += stride;
dstptr += JPC_QMFB_COLGRPSIZE;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
| 169,444 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AudioOutputDevice::AudioOutputDevice(
AudioOutputIPC* ipc,
const scoped_refptr<base::MessageLoopProxy>& io_loop)
: ScopedLoopObserver(io_loop),
input_channels_(0),
callback_(NULL),
ipc_(ipc),
stream_id_(0),
play_on_start_(true),
is_started_(false),
audio_thread_(new AudioDeviceThread()) {
CHECK(ipc_);
}
Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call.
I've kept my unit test changes intact but disabled until I get a proper fix.
BUG=147499,150805
TBR=henrika
Review URL: https://codereview.chromium.org/10946040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | AudioOutputDevice::AudioOutputDevice(
AudioOutputIPC* ipc,
const scoped_refptr<base::MessageLoopProxy>& io_loop)
: ScopedLoopObserver(io_loop),
input_channels_(0),
callback_(NULL),
ipc_(ipc),
stream_id_(0),
play_on_start_(true),
is_started_(false) {
CHECK(ipc_);
}
| 170,703 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, mode_t openflags, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = openflags;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(&opendata->path, newstate, openflags);
*res = newstate;
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, mode_t openflags, struct nfs4_state **res)
static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, fmode_t fmode, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = 0;
opendata->o_arg.fmode = fmode;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(&opendata->path, newstate, fmode);
*res = newstate;
return 0;
}
| 165,696 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PrintPreviewMessageHandler::OnMessageReceived(
const IPC::Message& message,
content::RenderFrameHost* render_frame_host) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(PrintPreviewMessageHandler, message,
render_frame_host)
IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview,
OnRequestPrintPreview)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount,
OnDidGetPreviewPageCount)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidPreviewPage,
OnDidPreviewPage)
IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting,
OnMetafileReadyForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewFailed,
OnPrintPreviewFailed)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetDefaultPageLayout,
OnDidGetDefaultPageLayout)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewCancelled,
OnPrintPreviewCancelled)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewInvalidPrinterSettings,
OnInvalidPrinterSettings)
IPC_MESSAGE_HANDLER(PrintHostMsg_SetOptionsFromDocument,
OnSetOptionsFromDocument)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | bool PrintPreviewMessageHandler::OnMessageReceived(
const IPC::Message& message,
content::RenderFrameHost* render_frame_host) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(PrintPreviewMessageHandler, message,
render_frame_host)
IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview,
OnRequestPrintPreview)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount,
OnDidGetPreviewPageCount)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidPreviewPage, OnDidPreviewPage)
IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting,
OnMetafileReadyForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewFailed,
OnPrintPreviewFailed)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetDefaultPageLayout,
OnDidGetDefaultPageLayout)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewCancelled,
OnPrintPreviewCancelled)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewInvalidPrinterSettings,
OnInvalidPrinterSettings)
IPC_MESSAGE_HANDLER(PrintHostMsg_SetOptionsFromDocument,
OnSetOptionsFromDocument)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
| 171,889 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static JSON_INLINE size_t num_buckets(hashtable_t *hashtable)
{
return primes[hashtable->num_buckets];
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | static JSON_INLINE size_t num_buckets(hashtable_t *hashtable)
| 166,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned long long Track::GetSeekPreRoll() const
{
return m_info.seekPreRoll;
}
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 | unsigned long long Track::GetSeekPreRoll() const
| 174,354 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const {
uint32_t size = data.readInt32();
vector.insertAt((size_t)0, size);
data.read(vector.editArray(), size);
}
Commit Message: Fix information disclosure in mediadrmserver
Test:POC provided in bug
Bug:79218474
Change-Id: Iba12c07a5e615f8ed234b01ac53e3559ba9ac12e
(cherry picked from commit c1bf68a8d1321d7cdf7da6933f0b89b171d251c6)
CWE ID: CWE-200 | void BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const {
uint32_t size = data.readInt32();
if (vector.insertAt((size_t)0, size) < 0) {
vector.clear();
}
if (data.read(vector.editArray(), size) != NO_ERROR) {
vector.clear();
android_errorWriteWithInfoLog(0x534e4554, "62872384", -1, NULL, 0);
}
}
| 174,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(int argc, const char **argv)
{
const char * prog = *argv;
const char * outfile = NULL;
const char * suffix = NULL;
const char * prefix = NULL;
int done = 0; /* if at least one file is processed */
struct global global;
global_init(&global);
while (--argc > 0)
{
++argv;
if (strcmp(*argv, "--debug") == 0)
{
/* To help debugging problems: */
global.errors = global.warnings = 1;
global.quiet = 0;
global.verbose = 7;
}
else if (strncmp(*argv, "--max=", 6) == 0)
{
global.idat_max = (png_uint_32)atol(6+*argv);
if (global.skip < SKIP_UNSAFE)
global.skip = SKIP_UNSAFE;
}
else if (strcmp(*argv, "--max") == 0)
{
global.idat_max = 0x7fffffff;
if (global.skip < SKIP_UNSAFE)
global.skip = SKIP_UNSAFE;
}
else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
global.optimize_zlib = 1;
else if (strncmp(*argv, "--out=", 6) == 0)
outfile = 6+*argv;
else if (strncmp(*argv, "--suffix=", 9) == 0)
suffix = 9+*argv;
else if (strncmp(*argv, "--prefix=", 9) == 0)
prefix = 9+*argv;
else if (strcmp(*argv, "--strip=none") == 0)
global.skip = SKIP_NONE;
else if (strcmp(*argv, "--strip=crc") == 0)
global.skip = SKIP_BAD_CRC;
else if (strcmp(*argv, "--strip=unsafe") == 0)
global.skip = SKIP_UNSAFE;
else if (strcmp(*argv, "--strip=unused") == 0)
global.skip = SKIP_UNUSED;
else if (strcmp(*argv, "--strip=transform") == 0)
global.skip = SKIP_TRANSFORM;
else if (strcmp(*argv, "--strip=color") == 0)
global.skip = SKIP_COLOR;
else if (strcmp(*argv, "--strip=all") == 0)
global.skip = SKIP_ALL;
else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
global.errors = 1;
else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
global.warnings = 1;
else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
{
if (global.quiet)
global.quiet = 2;
else
global.quiet = 1;
}
else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
++global.verbose;
#if 0
/* NYI */
# ifdef PNG_MAXIMUM_INFLATE_WINDOW
else if (strcmp(*argv, "--test") == 0)
++set_option;
# endif
#endif
else if ((*argv)[0] == '-')
usage(prog);
else
{
size_t outlen = strlen(*argv);
char temp_name[FILENAME_MAX+1];
if (outfile == NULL) /* else this takes precedence */
{
/* Consider the prefix/suffix options */
if (prefix != NULL)
{
size_t prefixlen = strlen(prefix);
if (prefixlen+outlen > FILENAME_MAX)
{
fprintf(stderr, "%s: output file name too long: %s%s%s\n",
prog, prefix, *argv, suffix ? suffix : "");
global.status_code |= WRITE_ERROR;
continue;
}
memcpy(temp_name, prefix, prefixlen);
memcpy(temp_name+prefixlen, *argv, outlen);
outlen += prefixlen;
outfile = temp_name;
}
else if (suffix != NULL)
memcpy(temp_name, *argv, outlen);
temp_name[outlen] = 0;
if (suffix != NULL)
{
size_t suffixlen = strlen(suffix);
if (outlen+suffixlen > FILENAME_MAX)
{
fprintf(stderr, "%s: output file name too long: %s%s\n",
prog, *argv, suffix);
global.status_code |= WRITE_ERROR;
continue;
}
memcpy(temp_name+outlen, suffix, suffixlen);
outlen += suffixlen;
temp_name[outlen] = 0;
outfile = temp_name;
}
}
(void)one_file(&global, *argv, outfile);
++done;
outfile = NULL;
}
}
if (!done)
usage(prog);
return global_end(&global);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | main(int argc, const char **argv)
{
char temp_name[FILENAME_MAX+1];
const char * prog = *argv;
const char * outfile = NULL;
const char * suffix = NULL;
const char * prefix = NULL;
int done = 0; /* if at least one file is processed */
struct global global;
global_init(&global);
while (--argc > 0)
{
++argv;
if (strcmp(*argv, "--debug") == 0)
{
/* To help debugging problems: */
global.errors = global.warnings = 1;
global.quiet = 0;
global.verbose = 7;
}
else if (strncmp(*argv, "--max=", 6) == 0)
{
global.idat_max = (png_uint_32)atol(6+*argv);
if (global.skip < SKIP_UNSAFE)
global.skip = SKIP_UNSAFE;
}
else if (strcmp(*argv, "--max") == 0)
{
global.idat_max = 0x7fffffff;
if (global.skip < SKIP_UNSAFE)
global.skip = SKIP_UNSAFE;
}
else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
global.optimize_zlib = 1;
else if (strncmp(*argv, "--out=", 6) == 0)
outfile = 6+*argv;
else if (strncmp(*argv, "--suffix=", 9) == 0)
suffix = 9+*argv;
else if (strncmp(*argv, "--prefix=", 9) == 0)
prefix = 9+*argv;
else if (strcmp(*argv, "--strip=none") == 0)
global.skip = SKIP_NONE;
else if (strcmp(*argv, "--strip=crc") == 0)
global.skip = SKIP_BAD_CRC;
else if (strcmp(*argv, "--strip=unsafe") == 0)
global.skip = SKIP_UNSAFE;
else if (strcmp(*argv, "--strip=unused") == 0)
global.skip = SKIP_UNUSED;
else if (strcmp(*argv, "--strip=transform") == 0)
global.skip = SKIP_TRANSFORM;
else if (strcmp(*argv, "--strip=color") == 0)
global.skip = SKIP_COLOR;
else if (strcmp(*argv, "--strip=all") == 0)
global.skip = SKIP_ALL;
else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
global.errors = 1;
else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
global.warnings = 1;
else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
{
if (global.quiet)
global.quiet = 2;
else
global.quiet = 1;
}
else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
++global.verbose;
#if 0
/* NYI */
# ifdef PNG_MAXIMUM_INFLATE_WINDOW
else if (strcmp(*argv, "--test") == 0)
++set_option;
# endif
#endif
else if ((*argv)[0] == '-')
usage(prog);
else
{
size_t outlen = strlen(*argv);
if (outfile == NULL) /* else this takes precedence */
{
/* Consider the prefix/suffix options */
if (prefix != NULL)
{
size_t prefixlen = strlen(prefix);
if (prefixlen+outlen > FILENAME_MAX)
{
fprintf(stderr, "%s: output file name too long: %s%s%s\n",
prog, prefix, *argv, suffix ? suffix : "");
global.status_code |= WRITE_ERROR;
continue;
}
memcpy(temp_name, prefix, prefixlen);
memcpy(temp_name+prefixlen, *argv, outlen);
outlen += prefixlen;
outfile = temp_name;
}
else if (suffix != NULL)
memcpy(temp_name, *argv, outlen);
temp_name[outlen] = 0;
if (suffix != NULL)
{
size_t suffixlen = strlen(suffix);
if (outlen+suffixlen > FILENAME_MAX)
{
fprintf(stderr, "%s: output file name too long: %s%s\n",
prog, *argv, suffix);
global.status_code |= WRITE_ERROR;
continue;
}
memcpy(temp_name+outlen, suffix, suffixlen);
outlen += suffixlen;
temp_name[outlen] = 0;
outfile = temp_name;
}
}
(void)one_file(&global, *argv, outfile);
++done;
outfile = NULL;
}
}
if (!done)
usage(prog);
return global_end(&global);
}
| 173,733 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Equalizer_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
int32_t param2;
char *name;
switch (param) {
case EQ_PARAM_NUM_BANDS:
case EQ_PARAM_CUR_PRESET:
case EQ_PARAM_GET_NUM_OF_PRESETS:
case EQ_PARAM_BAND_LEVEL:
case EQ_PARAM_GET_BAND:
if (*pValueSize < sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case EQ_PARAM_LEVEL_RANGE:
if (*pValueSize < 2 * sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int16_t);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
if (*pValueSize < 2 * sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int32_t);
break;
case EQ_PARAM_CENTER_FREQ:
if (*pValueSize < sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
case EQ_PARAM_GET_PRESET_NAME:
break;
case EQ_PARAM_PROPERTIES:
if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param) {
case EQ_PARAM_NUM_BANDS:
*(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS;
break;
case EQ_PARAM_LEVEL_RANGE:
*(int16_t *)pValue = -1500;
*((int16_t *)pValue + 1) = 1500;
break;
case EQ_PARAM_BAND_LEVEL:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32438598");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2);
}
break;
}
*(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2);
break;
case EQ_PARAM_CENTER_FREQ:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32436341");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2);
}
break;
}
*(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32247948");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2);
}
break;
}
EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1));
break;
case EQ_PARAM_GET_BAND:
param2 = *pParamTemp;
*(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2);
break;
case EQ_PARAM_CUR_PRESET:
*(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext);
break;
case EQ_PARAM_GET_NUM_OF_PRESETS:
*(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets();
break;
case EQ_PARAM_GET_PRESET_NAME:
param2 = *pParamTemp;
if (param2 >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
name = (char *)pValue;
strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1);
name[*pValueSize - 1] = 0;
*pValueSize = strlen(name) + 1;
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES");
p[0] = (int16_t)EqualizerGetPreset(pContext);
p[1] = (int16_t)FIVEBAND_NUMBANDS;
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_getParameter */
int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
int Volume_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;;
char *name;
switch (param){
case VOLUME_PARAM_LEVEL:
case VOLUME_PARAM_MAXLEVEL:
case VOLUME_PARAM_STEREOPOSITION:
if (*pValueSize != sizeof(int16_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case VOLUME_PARAM_MUTE:
case VOLUME_PARAM_ENABLESTEREOPOSITION:
if (*pValueSize < sizeof(int32_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param){
case VOLUME_PARAM_LEVEL:
status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue));
break;
case VOLUME_PARAM_MAXLEVEL:
*(int16_t *)pValue = 0;
break;
case VOLUME_PARAM_STEREOPOSITION:
VolumeGetStereoPosition(pContext, (int16_t *)pValue);
break;
case VOLUME_PARAM_MUTE:
status = VolumeGetMute(pContext, (uint32_t *)pValue);
ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d",
*(uint32_t *)pValue);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
*(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled;
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Volume_getParameter */
int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t level;
int16_t position;
uint32_t mute;
uint32_t positionEnabled;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param){
case VOLUME_PARAM_LEVEL:
level = *(int16_t *)pValue;
status = VolumeSetVolumeLevel(pContext, (int16_t)level);
break;
case VOLUME_PARAM_MUTE:
mute = *(uint32_t *)pValue;
status = VolumeSetMute(pContext, mute);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
positionEnabled = *(uint32_t *)pValue;
status = VolumeEnableStereoPosition(pContext, positionEnabled);
status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved);
break;
case VOLUME_PARAM_STEREOPOSITION:
position = *(int16_t *)pValue;
status = VolumeSetStereoPosition(pContext, (int16_t)position);
break;
default:
ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param);
break;
}
return status;
} /* end Volume_setParameter */
/****************************************************************************************
* Name : LVC_ToDB_s32Tos16()
* Input : Signed 32-bit integer
* Output : Signed 16-bit integer
* MSB (16) = sign bit
* (15->05) = integer part
* (04->01) = decimal part
* Returns : Db value with respect to full scale
* Description :
* Remarks :
****************************************************************************************/
LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix)
{
LVM_INT16 db_fix;
LVM_INT16 Shift;
LVM_INT16 SmallRemainder;
LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix;
/* Count leading bits, 1 cycle in assembly*/
for (Shift = 0; Shift<32; Shift++)
{
if ((Remainder & 0x80000000U)!=0)
{
break;
}
Remainder = Remainder << 1;
}
/*
* Based on the approximation equation (for Q11.4 format):
*
* dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2)
*/
db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/
SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24);
db_fix = (LVM_INT16)(db_fix + SmallRemainder );
SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder);
db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9));
/* Correct for small offset */
db_fix = (LVM_INT16)(db_fix - 5);
return db_fix;
}
int Effect_setEnabled(EffectContext *pContext, bool enabled)
{
ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled);
if (enabled) {
bool tempDisabled = false;
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountBb <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountBb =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bBassEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bBassTempDisabled;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountEq <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountEq =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountVirt =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled");
return -EINVAL;
}
pContext->pBundledContext->NumberEffectsEnabled++;
pContext->pBundledContext->bVolumeEnabled = LVM_TRUE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
if (!tempDisabled) {
LvmEffect_enable(pContext);
}
} else {
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bBassEnabled = LVM_FALSE;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
LvmEffect_disable(pContext);
}
return 0;
}
int16_t LVC_Convert_VolToDb(uint32_t vol){
int16_t dB;
dB = LVC_ToDB_s32Tos16(vol <<7);
dB = (dB +8)>>4;
dB = (dB <-96) ? -96 : dB ;
return dB;
}
} // namespace
Commit Message: Fix security vulnerability: Effect command might allow negative indexes
Bug: 32448258
Bug: 32095626
Test: Use POC bug or cts security test
Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df
(cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459)
CWE ID: CWE-200 | int Equalizer_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
int32_t param2;
char *name;
switch (param) {
case EQ_PARAM_NUM_BANDS:
case EQ_PARAM_CUR_PRESET:
case EQ_PARAM_GET_NUM_OF_PRESETS:
case EQ_PARAM_BAND_LEVEL:
case EQ_PARAM_GET_BAND:
if (*pValueSize < sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case EQ_PARAM_LEVEL_RANGE:
if (*pValueSize < 2 * sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int16_t);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
if (*pValueSize < 2 * sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int32_t);
break;
case EQ_PARAM_CENTER_FREQ:
if (*pValueSize < sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
case EQ_PARAM_GET_PRESET_NAME:
break;
case EQ_PARAM_PROPERTIES:
if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param) {
case EQ_PARAM_NUM_BANDS:
*(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS;
break;
case EQ_PARAM_LEVEL_RANGE:
*(int16_t *)pValue = -1500;
*((int16_t *)pValue + 1) = 1500;
break;
case EQ_PARAM_BAND_LEVEL:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32438598");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2);
}
break;
}
*(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2);
break;
case EQ_PARAM_CENTER_FREQ:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32436341");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2);
}
break;
}
*(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32247948");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2);
}
break;
}
EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1));
break;
case EQ_PARAM_GET_BAND:
param2 = *pParamTemp;
*(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2);
break;
case EQ_PARAM_CUR_PRESET:
*(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext);
break;
case EQ_PARAM_GET_NUM_OF_PRESETS:
*(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets();
break;
case EQ_PARAM_GET_PRESET_NAME:
param2 = *pParamTemp;
if ((param2 < 0 && param2 != PRESET_CUSTOM) || param2 >= EqualizerGetNumPresets()) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32448258");
ALOGE("\tERROR Equalizer_getParameter() EQ_PARAM_GET_PRESET_NAME preset %d",
param2);
}
break;
}
name = (char *)pValue;
strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1);
name[*pValueSize - 1] = 0;
*pValueSize = strlen(name) + 1;
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES");
p[0] = (int16_t)EqualizerGetPreset(pContext);
p[1] = (int16_t)FIVEBAND_NUMBANDS;
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_getParameter */
int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band < 0 || band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (band < 0) {
android_errorWriteLog(0x534e4554, "32095626");
ALOGE("\tERROR Equalizer_setParameter() EQ_PARAM_BAND_LEVEL band %d", band);
}
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
int Volume_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;;
char *name;
switch (param){
case VOLUME_PARAM_LEVEL:
case VOLUME_PARAM_MAXLEVEL:
case VOLUME_PARAM_STEREOPOSITION:
if (*pValueSize != sizeof(int16_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case VOLUME_PARAM_MUTE:
case VOLUME_PARAM_ENABLESTEREOPOSITION:
if (*pValueSize < sizeof(int32_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param){
case VOLUME_PARAM_LEVEL:
status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue));
break;
case VOLUME_PARAM_MAXLEVEL:
*(int16_t *)pValue = 0;
break;
case VOLUME_PARAM_STEREOPOSITION:
VolumeGetStereoPosition(pContext, (int16_t *)pValue);
break;
case VOLUME_PARAM_MUTE:
status = VolumeGetMute(pContext, (uint32_t *)pValue);
ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d",
*(uint32_t *)pValue);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
*(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled;
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Volume_getParameter */
int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t level;
int16_t position;
uint32_t mute;
uint32_t positionEnabled;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param){
case VOLUME_PARAM_LEVEL:
level = *(int16_t *)pValue;
status = VolumeSetVolumeLevel(pContext, (int16_t)level);
break;
case VOLUME_PARAM_MUTE:
mute = *(uint32_t *)pValue;
status = VolumeSetMute(pContext, mute);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
positionEnabled = *(uint32_t *)pValue;
status = VolumeEnableStereoPosition(pContext, positionEnabled);
status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved);
break;
case VOLUME_PARAM_STEREOPOSITION:
position = *(int16_t *)pValue;
status = VolumeSetStereoPosition(pContext, (int16_t)position);
break;
default:
ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param);
break;
}
return status;
} /* end Volume_setParameter */
/****************************************************************************************
* Name : LVC_ToDB_s32Tos16()
* Input : Signed 32-bit integer
* Output : Signed 16-bit integer
* MSB (16) = sign bit
* (15->05) = integer part
* (04->01) = decimal part
* Returns : Db value with respect to full scale
* Description :
* Remarks :
****************************************************************************************/
LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix)
{
LVM_INT16 db_fix;
LVM_INT16 Shift;
LVM_INT16 SmallRemainder;
LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix;
/* Count leading bits, 1 cycle in assembly*/
for (Shift = 0; Shift<32; Shift++)
{
if ((Remainder & 0x80000000U)!=0)
{
break;
}
Remainder = Remainder << 1;
}
/*
* Based on the approximation equation (for Q11.4 format):
*
* dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2)
*/
db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/
SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24);
db_fix = (LVM_INT16)(db_fix + SmallRemainder );
SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder);
db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9));
/* Correct for small offset */
db_fix = (LVM_INT16)(db_fix - 5);
return db_fix;
}
int Effect_setEnabled(EffectContext *pContext, bool enabled)
{
ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled);
if (enabled) {
bool tempDisabled = false;
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountBb <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountBb =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bBassEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bBassTempDisabled;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountEq <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountEq =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountVirt =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled");
return -EINVAL;
}
pContext->pBundledContext->NumberEffectsEnabled++;
pContext->pBundledContext->bVolumeEnabled = LVM_TRUE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
if (!tempDisabled) {
LvmEffect_enable(pContext);
}
} else {
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bBassEnabled = LVM_FALSE;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
LvmEffect_disable(pContext);
}
return 0;
}
int16_t LVC_Convert_VolToDb(uint32_t vol){
int16_t dB;
dB = LVC_ToDB_s32Tos16(vol <<7);
dB = (dB +8)>>4;
dB = (dB <-96) ? -96 : dB ;
return dB;
}
} // namespace
| 174,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *) uaddr;
struct net *net = sock_net(sk);
__be32 v4addr = 0;
int addr_type;
int err;
if (!sock_flag(sk, SOCK_ZAPPED))
return -EINVAL;
if (addr->l2tp_family != AF_INET6)
return -EINVAL;
if (addr_len < sizeof(*addr))
return -EINVAL;
addr_type = ipv6_addr_type(&addr->l2tp_addr);
/* l2tp_ip6 sockets are IPv6 only */
if (addr_type == IPV6_ADDR_MAPPED)
return -EADDRNOTAVAIL;
/* L2TP is point-point, not multicast */
if (addr_type & IPV6_ADDR_MULTICAST)
return -EADDRNOTAVAIL;
err = -EADDRINUSE;
read_lock_bh(&l2tp_ip6_lock);
if (__l2tp_ip6_bind_lookup(net, &addr->l2tp_addr,
sk->sk_bound_dev_if, addr->l2tp_conn_id))
goto out_in_use;
read_unlock_bh(&l2tp_ip6_lock);
lock_sock(sk);
err = -EINVAL;
if (sk->sk_state != TCP_CLOSE)
goto out_unlock;
/* Check if the address belongs to the host. */
rcu_read_lock();
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->l2tp_scope_id) {
/* Override any existing binding, if another
* one is supplied by user.
*/
sk->sk_bound_dev_if = addr->l2tp_scope_id;
}
/* Binding to link-local address requires an
interface */
if (!sk->sk_bound_dev_if)
goto out_unlock_rcu;
err = -ENODEV;
dev = dev_get_by_index_rcu(sock_net(sk),
sk->sk_bound_dev_if);
if (!dev)
goto out_unlock_rcu;
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
err = -EADDRNOTAVAIL;
if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0))
goto out_unlock_rcu;
}
rcu_read_unlock();
inet->inet_rcv_saddr = inet->inet_saddr = v4addr;
sk->sk_v6_rcv_saddr = addr->l2tp_addr;
np->saddr = addr->l2tp_addr;
l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id;
write_lock_bh(&l2tp_ip6_lock);
sk_add_bind_node(sk, &l2tp_ip6_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip6_lock);
sock_reset_flag(sk, SOCK_ZAPPED);
release_sock(sk);
return 0;
out_unlock_rcu:
rcu_read_unlock();
out_unlock:
release_sock(sk);
return err;
out_in_use:
read_unlock_bh(&l2tp_ip6_lock);
return err;
}
Commit Message: l2tp: fix racy SOCK_ZAPPED flag check in l2tp_ip{,6}_bind()
Lock socket before checking the SOCK_ZAPPED flag in l2tp_ip6_bind().
Without lock, a concurrent call could modify the socket flags between
the sock_flag(sk, SOCK_ZAPPED) test and the lock_sock() call. This way,
a socket could be inserted twice in l2tp_ip6_bind_table. Releasing it
would then leave a stale pointer there, generating use-after-free
errors when walking through the list or modifying adjacent entries.
BUG: KASAN: use-after-free in l2tp_ip6_close+0x22e/0x290 at addr ffff8800081b0ed8
Write of size 8 by task syz-executor/10987
CPU: 0 PID: 10987 Comm: syz-executor Not tainted 4.8.0+ #39
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014
ffff880031d97838 ffffffff829f835b ffff88001b5a1640 ffff8800081b0ec0
ffff8800081b15a0 ffff8800081b6d20 ffff880031d97860 ffffffff8174d3cc
ffff880031d978f0 ffff8800081b0e80 ffff88001b5a1640 ffff880031d978e0
Call Trace:
[<ffffffff829f835b>] dump_stack+0xb3/0x118 lib/dump_stack.c:15
[<ffffffff8174d3cc>] kasan_object_err+0x1c/0x70 mm/kasan/report.c:156
[< inline >] print_address_description mm/kasan/report.c:194
[<ffffffff8174d666>] kasan_report_error+0x1f6/0x4d0 mm/kasan/report.c:283
[< inline >] kasan_report mm/kasan/report.c:303
[<ffffffff8174db7e>] __asan_report_store8_noabort+0x3e/0x40 mm/kasan/report.c:329
[< inline >] __write_once_size ./include/linux/compiler.h:249
[< inline >] __hlist_del ./include/linux/list.h:622
[< inline >] hlist_del_init ./include/linux/list.h:637
[<ffffffff8579047e>] l2tp_ip6_close+0x22e/0x290 net/l2tp/l2tp_ip6.c:239
[<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415
[<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422
[<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570
[<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017
[<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208
[<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244
[<ffffffff813774f9>] task_work_run+0xf9/0x170
[<ffffffff81324aae>] do_exit+0x85e/0x2a00
[<ffffffff81326dc8>] do_group_exit+0x108/0x330
[<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307
[<ffffffff811b49af>] do_signal+0x7f/0x18f0
[<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156
[< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190
[<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259
[<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6
Object at ffff8800081b0ec0, in cache L2TP/IPv6 size: 1448
Allocated:
PID = 10987
[ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20
[ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0
[ 1116.897025] [<ffffffff8174c9ad>] kasan_kmalloc+0xad/0xe0
[ 1116.897025] [<ffffffff8174cee2>] kasan_slab_alloc+0x12/0x20
[ 1116.897025] [< inline >] slab_post_alloc_hook mm/slab.h:417
[ 1116.897025] [< inline >] slab_alloc_node mm/slub.c:2708
[ 1116.897025] [< inline >] slab_alloc mm/slub.c:2716
[ 1116.897025] [<ffffffff817476a8>] kmem_cache_alloc+0xc8/0x2b0 mm/slub.c:2721
[ 1116.897025] [<ffffffff84c4f6a9>] sk_prot_alloc+0x69/0x2b0 net/core/sock.c:1326
[ 1116.897025] [<ffffffff84c58ac8>] sk_alloc+0x38/0xae0 net/core/sock.c:1388
[ 1116.897025] [<ffffffff851ddf67>] inet6_create+0x2d7/0x1000 net/ipv6/af_inet6.c:182
[ 1116.897025] [<ffffffff84c4af7b>] __sock_create+0x37b/0x640 net/socket.c:1153
[ 1116.897025] [< inline >] sock_create net/socket.c:1193
[ 1116.897025] [< inline >] SYSC_socket net/socket.c:1223
[ 1116.897025] [<ffffffff84c4b46f>] SyS_socket+0xef/0x1b0 net/socket.c:1203
[ 1116.897025] [<ffffffff85e4d685>] entry_SYSCALL_64_fastpath+0x23/0xc6
Freed:
PID = 10987
[ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20
[ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0
[ 1116.897025] [<ffffffff8174cf61>] kasan_slab_free+0x71/0xb0
[ 1116.897025] [< inline >] slab_free_hook mm/slub.c:1352
[ 1116.897025] [< inline >] slab_free_freelist_hook mm/slub.c:1374
[ 1116.897025] [< inline >] slab_free mm/slub.c:2951
[ 1116.897025] [<ffffffff81748b28>] kmem_cache_free+0xc8/0x330 mm/slub.c:2973
[ 1116.897025] [< inline >] sk_prot_free net/core/sock.c:1369
[ 1116.897025] [<ffffffff84c541eb>] __sk_destruct+0x32b/0x4f0 net/core/sock.c:1444
[ 1116.897025] [<ffffffff84c5aca4>] sk_destruct+0x44/0x80 net/core/sock.c:1452
[ 1116.897025] [<ffffffff84c5ad33>] __sk_free+0x53/0x220 net/core/sock.c:1460
[ 1116.897025] [<ffffffff84c5af23>] sk_free+0x23/0x30 net/core/sock.c:1471
[ 1116.897025] [<ffffffff84c5cb6c>] sk_common_release+0x28c/0x3e0 ./include/net/sock.h:1589
[ 1116.897025] [<ffffffff8579044e>] l2tp_ip6_close+0x1fe/0x290 net/l2tp/l2tp_ip6.c:243
[ 1116.897025] [<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415
[ 1116.897025] [<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422
[ 1116.897025] [<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570
[ 1116.897025] [<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017
[ 1116.897025] [<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208
[ 1116.897025] [<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244
[ 1116.897025] [<ffffffff813774f9>] task_work_run+0xf9/0x170
[ 1116.897025] [<ffffffff81324aae>] do_exit+0x85e/0x2a00
[ 1116.897025] [<ffffffff81326dc8>] do_group_exit+0x108/0x330
[ 1116.897025] [<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307
[ 1116.897025] [<ffffffff811b49af>] do_signal+0x7f/0x18f0
[ 1116.897025] [<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156
[ 1116.897025] [< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190
[ 1116.897025] [<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259
[ 1116.897025] [<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6
Memory state around the buggy address:
ffff8800081b0d80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff8800081b0e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff8800081b0e80: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
^
ffff8800081b0f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8800081b0f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
The same issue exists with l2tp_ip_bind() and l2tp_ip_bind_table.
Fixes: c51ce49735c1 ("l2tp: fix oops in L2TP IP sockets for connect() AF_UNSPEC case")
Reported-by: Baozeng Ding <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Baozeng Ding <[email protected]>
Signed-off-by: Guillaume Nault <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *) uaddr;
struct net *net = sock_net(sk);
__be32 v4addr = 0;
int addr_type;
int err;
if (addr->l2tp_family != AF_INET6)
return -EINVAL;
if (addr_len < sizeof(*addr))
return -EINVAL;
addr_type = ipv6_addr_type(&addr->l2tp_addr);
/* l2tp_ip6 sockets are IPv6 only */
if (addr_type == IPV6_ADDR_MAPPED)
return -EADDRNOTAVAIL;
/* L2TP is point-point, not multicast */
if (addr_type & IPV6_ADDR_MULTICAST)
return -EADDRNOTAVAIL;
err = -EADDRINUSE;
read_lock_bh(&l2tp_ip6_lock);
if (__l2tp_ip6_bind_lookup(net, &addr->l2tp_addr,
sk->sk_bound_dev_if, addr->l2tp_conn_id))
goto out_in_use;
read_unlock_bh(&l2tp_ip6_lock);
lock_sock(sk);
err = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED))
goto out_unlock;
if (sk->sk_state != TCP_CLOSE)
goto out_unlock;
/* Check if the address belongs to the host. */
rcu_read_lock();
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->l2tp_scope_id) {
/* Override any existing binding, if another
* one is supplied by user.
*/
sk->sk_bound_dev_if = addr->l2tp_scope_id;
}
/* Binding to link-local address requires an
interface */
if (!sk->sk_bound_dev_if)
goto out_unlock_rcu;
err = -ENODEV;
dev = dev_get_by_index_rcu(sock_net(sk),
sk->sk_bound_dev_if);
if (!dev)
goto out_unlock_rcu;
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
err = -EADDRNOTAVAIL;
if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0))
goto out_unlock_rcu;
}
rcu_read_unlock();
inet->inet_rcv_saddr = inet->inet_saddr = v4addr;
sk->sk_v6_rcv_saddr = addr->l2tp_addr;
np->saddr = addr->l2tp_addr;
l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id;
write_lock_bh(&l2tp_ip6_lock);
sk_add_bind_node(sk, &l2tp_ip6_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip6_lock);
sock_reset_flag(sk, SOCK_ZAPPED);
release_sock(sk);
return 0;
out_unlock_rcu:
rcu_read_unlock();
out_unlock:
release_sock(sk);
return err;
out_in_use:
read_unlock_bh(&l2tp_ip6_lock);
return err;
}
| 168,490 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
Commit Message:
CWE ID: CWE-119 | int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
| 164,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PepperRendererConnection::OnMsgDidDeleteInProcessInstance(
PP_Instance instance) {
in_process_host_->DeleteInstance(instance);
}
Commit Message: Validate in-process plugin instance messages.
Bug: 733548, 733549
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba
Reviewed-on: https://chromium-review.googlesource.com/538908
Commit-Queue: Bill Budge <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480696}
CWE ID: CWE-20 | void PepperRendererConnection::OnMsgDidDeleteInProcessInstance(
PP_Instance instance) {
// 'instance' is possibly invalid. The host must be careful not to trust it.
in_process_host_->DeleteInstance(instance);
}
| 172,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MockRenderProcess::MockRenderProcess()
: transport_dib_next_sequence_number_(0) {
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | MockRenderProcess::MockRenderProcess()
: transport_dib_next_sequence_number_(0),
enabled_bindings_(0) {
}
| 171,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: build_config(char *prefix, struct server *server)
{
char *path = NULL;
int path_size = strlen(prefix) + strlen(server->port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port);
FILE *f = fopen(path, "w+");
if (f == NULL) {
if (verbose) {
LOGE("unable to open config file");
}
ss_free(path);
return;
}
fprintf(f, "{\n");
fprintf(f, "\"server_port\":%d,\n", atoi(server->port));
fprintf(f, "\"password\":\"%s\"", server->password);
if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open);
if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode);
if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method);
if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin);
if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts);
fprintf(f, "\n}\n");
fclose(f);
ss_free(path);
}
Commit Message: Fix #1734
CWE ID: CWE-78 | build_config(char *prefix, struct server *server)
build_config(char *prefix, struct manager_ctx *manager, struct server *server)
{
char *path = NULL;
int path_size = strlen(prefix) + strlen(server->port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port);
FILE *f = fopen(path, "w+");
if (f == NULL) {
if (verbose) {
LOGE("unable to open config file");
}
ss_free(path);
return;
}
fprintf(f, "{\n");
fprintf(f, "\"server_port\":%d,\n", atoi(server->port));
fprintf(f, "\"password\":\"%s\"", server->password);
if (server->method)
fprintf(f, ",\n\"method\":\"%s\"", server->method);
else if (manager->method)
fprintf(f, ",\n\"method\":\"%s\"", manager->method);
if (server->fast_open[0])
fprintf(f, ",\n\"fast_open\": %s", server->fast_open);
if (server->mode)
fprintf(f, ",\n\"mode\":\"%s\"", server->mode);
if (server->plugin)
fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin);
if (server->plugin_opts)
fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts);
fprintf(f, "\n}\n");
fclose(f);
ss_free(path);
}
| 167,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int putint(jas_stream_t *out, int sgnd, int prec, long val)
{
int n;
int c;
bool s;
ulong tmp;
assert((!sgnd && prec >= 1) || (sgnd && prec >= 2));
if (sgnd) {
val = encode_twos_comp(val, prec);
}
assert(val >= 0);
val &= (1 << prec) - 1;
n = (prec + 7) / 8;
while (--n >= 0) {
c = (val >> (n * 8)) & 0xff;
if (jas_stream_putc(out, c) != c)
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 | static int putint(jas_stream_t *out, int sgnd, int prec, long val)
{
int n;
int c;
bool s;
jas_ulong tmp;
assert((!sgnd && prec >= 1) || (sgnd && prec >= 2));
if (sgnd) {
val = encode_twos_comp(val, prec);
}
assert(val >= 0);
val &= (1 << prec) - 1;
n = (prec + 7) / 8;
while (--n >= 0) {
c = (val >> (n * 8)) & 0xff;
if (jas_stream_putc(out, c) != c)
return -1;
}
return 0;
}
| 168,696 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int userfaultfd_release(struct inode *inode, struct file *file)
{
struct userfaultfd_ctx *ctx = file->private_data;
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev;
/* len == 0 means wake all */
struct userfaultfd_wake_range range = { .len = 0, };
unsigned long new_flags;
WRITE_ONCE(ctx->released, true);
if (!mmget_not_zero(mm))
goto wakeup;
/*
* Flush page faults out of all CPUs. NOTE: all page faults
* must be retried without returning VM_FAULT_SIGBUS if
* userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
* changes while handle_userfault released the mmap_sem. So
* it's critical that released is set to true (above), before
* taking the mmap_sem for writing.
*/
down_write(&mm->mmap_sem);
prev = NULL;
for (vma = mm->mmap; vma; vma = vma->vm_next) {
cond_resched();
BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
!!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
if (vma->vm_userfaultfd_ctx.ctx != ctx) {
prev = vma;
continue;
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
new_flags, vma->anon_vma,
vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev)
vma = prev;
else
prev = vma;
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
}
up_write(&mm->mmap_sem);
mmput(mm);
wakeup:
/*
* After no new page faults can wait on this fault_*wqh, flush
* the last page faults that may have been already waiting on
* the fault_*wqh.
*/
spin_lock(&ctx->fault_pending_wqh.lock);
__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
spin_unlock(&ctx->fault_pending_wqh.lock);
/* Flush pending events that may still wait on event_wqh */
wake_up_all(&ctx->event_wqh);
wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
userfaultfd_ctx_put(ctx);
return 0;
}
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static int userfaultfd_release(struct inode *inode, struct file *file)
{
struct userfaultfd_ctx *ctx = file->private_data;
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev;
/* len == 0 means wake all */
struct userfaultfd_wake_range range = { .len = 0, };
unsigned long new_flags;
WRITE_ONCE(ctx->released, true);
if (!mmget_not_zero(mm))
goto wakeup;
/*
* Flush page faults out of all CPUs. NOTE: all page faults
* must be retried without returning VM_FAULT_SIGBUS if
* userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
* changes while handle_userfault released the mmap_sem. So
* it's critical that released is set to true (above), before
* taking the mmap_sem for writing.
*/
down_write(&mm->mmap_sem);
if (!mmget_still_valid(mm))
goto skip_mm;
prev = NULL;
for (vma = mm->mmap; vma; vma = vma->vm_next) {
cond_resched();
BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
!!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
if (vma->vm_userfaultfd_ctx.ctx != ctx) {
prev = vma;
continue;
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
new_flags, vma->anon_vma,
vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev)
vma = prev;
else
prev = vma;
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
}
skip_mm:
up_write(&mm->mmap_sem);
mmput(mm);
wakeup:
/*
* After no new page faults can wait on this fault_*wqh, flush
* the last page faults that may have been already waiting on
* the fault_*wqh.
*/
spin_lock(&ctx->fault_pending_wqh.lock);
__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
spin_unlock(&ctx->fault_pending_wqh.lock);
/* Flush pending events that may still wait on event_wqh */
wake_up_all(&ctx->event_wqh);
wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
userfaultfd_ctx_put(ctx);
return 0;
}
| 169,688 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
ut8 *buf = calloc (to - from, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, to - from);
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
}
Commit Message: Fix #9902 - Fix oobread in RBin.string_scan_range
CWE ID: CWE-125 | static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
int len = to - from;
ut8 *buf = calloc (len, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, len);
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5 + rc) {
bool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
}
| 169,224 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name,
int sample,
int boundary_value) {
if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 &&
sample < boundary_value)) {
frontend_host_->BadMessageRecieved();
return;
}
if (name == kDevToolsActionTakenHistogram)
UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value);
else if (name == kDevToolsPanelShownHistogram)
UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value);
else
frontend_host_->BadMessageRecieved();
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name,
int sample,
int boundary_value) {
if (!frontend_host_)
return;
if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 &&
sample < boundary_value)) {
frontend_host_->BadMessageRecieved();
return;
}
if (name == kDevToolsActionTakenHistogram)
UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value);
else if (name == kDevToolsPanelShownHistogram)
UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value);
else
frontend_host_->BadMessageRecieved();
}
| 172,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
RequestGlobalMemoryDump(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, callback);
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
// This merely strips out the |dump_guid| argument.
auto adapter = [](const RequestGlobalMemoryDumpCallback& callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {},
false /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
| 172,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle))
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
| 167,604 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Reinitialize(ReinitTestCase test_case) {
feature_list_.InitAndEnableFeature(network::features::kNetworkService);
ASSERT_TRUE(temp_directory_.CreateUniqueTempDir());
AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index"));
EXPECT_TRUE(db.LazyOpen(true));
if (test_case == CORRUPT_CACHE_ON_INSTALL ||
test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) {
const std::string kCorruptData("deadbeef");
base::FilePath disk_cache_directory =
temp_directory_.GetPath().AppendASCII("Cache");
ASSERT_TRUE(base::CreateDirectory(disk_cache_directory));
base::FilePath index_file = disk_cache_directory.AppendASCII("index");
EXPECT_EQ(static_cast<int>(kCorruptData.length()),
base::WriteFile(index_file, kCorruptData.data(),
kCorruptData.length()));
base::FilePath entry_file =
disk_cache_directory.AppendASCII("01234567_0");
EXPECT_EQ(static_cast<int>(kCorruptData.length()),
base::WriteFile(entry_file, kCorruptData.data(),
kCorruptData.length()));
}
if (test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) {
AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index"));
GURL manifest_url = GetMockUrl("manifest");
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = 1;
group_record.manifest_url = manifest_url;
group_record.origin = url::Origin::Create(manifest_url);
EXPECT_TRUE(db.InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = 1;
cache_record.group_id = 1;
cache_record.online_wildcard = false;
cache_record.update_time = kZeroTime;
cache_record.cache_size = kDefaultEntrySize;
EXPECT_TRUE(db.InsertCache(&cache_record));
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = 1;
entry_record.url = manifest_url;
entry_record.flags = AppCacheEntry::MANIFEST;
entry_record.response_id = 1;
entry_record.response_size = kDefaultEntrySize;
EXPECT_TRUE(db.InsertEntry(&entry_record));
}
service_.reset(new AppCacheServiceImpl(nullptr));
auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>();
loader_factory_getter->SetNetworkFactoryForTesting(
&mock_url_loader_factory_, /* is_corb_enabled = */ true);
service_->set_url_loader_factory_getter(loader_factory_getter.get());
service_->Initialize(temp_directory_.GetPath());
mock_quota_manager_proxy_ = new MockQuotaManagerProxy();
service_->quota_manager_proxy_ = mock_quota_manager_proxy_;
delegate_.reset(new MockStorageDelegate(this));
observer_.reset(new MockServiceObserver(this));
service_->AddObserver(observer_.get());
FlushAllTasks();
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&AppCacheStorageImplTest::Continue_Reinitialize,
base::Unretained(this), test_case));
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void Reinitialize(ReinitTestCase test_case) {
feature_list_.InitAndEnableFeature(network::features::kNetworkService);
ASSERT_TRUE(temp_directory_.CreateUniqueTempDir());
AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index"));
EXPECT_TRUE(db.LazyOpen(true));
if (test_case == CORRUPT_CACHE_ON_INSTALL ||
test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) {
const std::string kCorruptData("deadbeef");
base::FilePath disk_cache_directory =
temp_directory_.GetPath().AppendASCII("Cache");
ASSERT_TRUE(base::CreateDirectory(disk_cache_directory));
base::FilePath index_file = disk_cache_directory.AppendASCII("index");
EXPECT_EQ(static_cast<int>(kCorruptData.length()),
base::WriteFile(index_file, kCorruptData.data(),
kCorruptData.length()));
base::FilePath entry_file =
disk_cache_directory.AppendASCII("01234567_0");
EXPECT_EQ(static_cast<int>(kCorruptData.length()),
base::WriteFile(entry_file, kCorruptData.data(),
kCorruptData.length()));
}
if (test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) {
AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index"));
GURL manifest_url = GetMockUrl("manifest");
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = 1;
group_record.manifest_url = manifest_url;
group_record.origin = url::Origin::Create(manifest_url);
EXPECT_TRUE(db.InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = 1;
cache_record.group_id = 1;
cache_record.online_wildcard = false;
cache_record.update_time = kZeroTime;
cache_record.cache_size = kDefaultEntrySize;
cache_record.padding_size = 0;
EXPECT_TRUE(db.InsertCache(&cache_record));
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = 1;
entry_record.url = manifest_url;
entry_record.flags = AppCacheEntry::MANIFEST;
entry_record.response_id = 1;
entry_record.response_size = kDefaultEntrySize;
entry_record.padding_size = 0;
EXPECT_TRUE(db.InsertEntry(&entry_record));
}
service_.reset(new AppCacheServiceImpl(nullptr));
auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>();
loader_factory_getter->SetNetworkFactoryForTesting(
&mock_url_loader_factory_, /* is_corb_enabled = */ true);
service_->set_url_loader_factory_getter(loader_factory_getter.get());
service_->Initialize(temp_directory_.GetPath());
mock_quota_manager_proxy_ = new MockQuotaManagerProxy();
service_->quota_manager_proxy_ = mock_quota_manager_proxy_;
delegate_.reset(new MockStorageDelegate(this));
observer_.reset(new MockServiceObserver(this));
service_->AddObserver(observer_.get());
FlushAllTasks();
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&AppCacheStorageImplTest::Continue_Reinitialize,
base::Unretained(this), test_case));
}
| 172,988 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int pf_detect(void)
{
struct pf_unit *pf = units;
int k, unit;
printk("%s: %s version %s, major %d, cluster %d, nice %d\n",
name, name, PF_VERSION, major, cluster, nice);
par_drv = pi_register_driver(name);
if (!par_drv) {
pr_err("failed to register %s driver\n", name);
return -1;
}
k = 0;
if (pf_drive_count == 0) {
if (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF,
verbose, pf->name)) {
if (!pf_probe(pf) && pf->disk) {
pf->present = 1;
k++;
} else
pi_release(pf->pi);
}
} else
for (unit = 0; unit < PF_UNITS; unit++, pf++) {
int *conf = *drives[unit];
if (!conf[D_PRT])
continue;
if (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD],
conf[D_UNI], conf[D_PRO], conf[D_DLY],
pf_scratch, PI_PF, verbose, pf->name)) {
if (pf->disk && !pf_probe(pf)) {
pf->present = 1;
k++;
} else
pi_release(pf->pi);
}
}
if (k)
return 0;
printk("%s: No ATAPI disk detected\n", name);
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
blk_cleanup_queue(pf->disk->queue);
pf->disk->queue = NULL;
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
}
pi_unregister_driver(par_drv);
return -1;
}
Commit Message: paride/pf: Fix potential NULL pointer dereference
Syzkaller report this:
pf: pf version 1.04, major 47, cluster 64, nice 0
pf: No ATAPI disk detected
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pf_init+0x7af/0x1000 [pf]
Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34
RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788
RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59
R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000
R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020
FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1e50000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp
c
ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp
td
glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace 7a818cf5f210d79e ]---
If alloc_disk fails in pf_init_units, pf->disk will be
NULL, however in pf_detect and pf_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-476 | static int pf_detect(void)
{
struct pf_unit *pf = units;
int k, unit;
printk("%s: %s version %s, major %d, cluster %d, nice %d\n",
name, name, PF_VERSION, major, cluster, nice);
par_drv = pi_register_driver(name);
if (!par_drv) {
pr_err("failed to register %s driver\n", name);
return -1;
}
k = 0;
if (pf_drive_count == 0) {
if (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF,
verbose, pf->name)) {
if (!pf_probe(pf) && pf->disk) {
pf->present = 1;
k++;
} else
pi_release(pf->pi);
}
} else
for (unit = 0; unit < PF_UNITS; unit++, pf++) {
int *conf = *drives[unit];
if (!conf[D_PRT])
continue;
if (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD],
conf[D_UNI], conf[D_PRO], conf[D_DLY],
pf_scratch, PI_PF, verbose, pf->name)) {
if (pf->disk && !pf_probe(pf)) {
pf->present = 1;
k++;
} else
pi_release(pf->pi);
}
}
if (k)
return 0;
printk("%s: No ATAPI disk detected\n", name);
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
if (!pf->disk)
continue;
blk_cleanup_queue(pf->disk->queue);
pf->disk->queue = NULL;
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
}
pi_unregister_driver(par_drv);
return -1;
}
| 169,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseContentEncAESSettingsEntry(
long long start, long long size, IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
assert(pos <= stop);
}
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long ContentEncoding::ParseContentEncAESSettingsEntry(
long long start, long long size, IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
return 0;
}
| 173,849 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
struct perf_event *event = file->private_data;
return perf_read_hw(event, buf, count);
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
struct perf_event *event = file->private_data;
struct perf_event_context *ctx;
int ret;
ctx = perf_event_ctx_lock(event);
ret = perf_read_hw(event, buf, count);
perf_event_ctx_unlock(event, ctx);
return ret;
}
| 166,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
Commit Message: Add Android SDK version to crash reports.
Bug: 911669
Change-Id: I62a97d76a0b88099a5a42b93463307f03be9b3e2
Reviewed-on: https://chromium-review.googlesource.com/c/1361104
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Peter Conn <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Michael van Ouwerkerk <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615851}
CWE ID: CWE-189 | void SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["sdk"] = base::StringPrintf("%d", info->sdk_int());
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
| 172,546 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ResourcePrefetchPredictor::PredictPreconnectOrigins(
const GURL& url,
PreconnectPrediction* prediction) const {
DCHECK(!prediction || prediction->requests.empty());
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (initialization_state_ != INITIALIZED)
return false;
url::Origin url_origin = url::Origin::Create(url);
url::Origin redirect_origin;
bool has_any_prediction = GetRedirectEndpointsForPreconnect(
url_origin, *host_redirect_data_, prediction);
if (!GetRedirectOrigin(url_origin, *host_redirect_data_, &redirect_origin)) {
return has_any_prediction;
}
OriginData data;
if (!origin_data_->TryGetData(redirect_origin.host(), &data)) {
return has_any_prediction;
}
if (prediction) {
prediction->host = redirect_origin.host();
prediction->is_redirected = (redirect_origin != url_origin);
}
net::NetworkIsolationKey network_isolation_key(redirect_origin,
redirect_origin);
for (const OriginStat& origin : data.origins()) {
float confidence = static_cast<float>(origin.number_of_hits()) /
(origin.number_of_hits() + origin.number_of_misses());
if (confidence < kMinOriginConfidenceToTriggerPreresolve)
continue;
has_any_prediction = true;
if (prediction) {
if (confidence > kMinOriginConfidenceToTriggerPreconnect) {
prediction->requests.emplace_back(GURL(origin.origin()), 1,
network_isolation_key);
} else {
prediction->requests.emplace_back(GURL(origin.origin()), 0,
network_isolation_key);
}
}
}
return has_any_prediction;
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | bool ResourcePrefetchPredictor::PredictPreconnectOrigins(
const GURL& url,
PreconnectPrediction* prediction) const {
DCHECK(!prediction || prediction->requests.empty());
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (initialization_state_ != INITIALIZED)
return false;
url::Origin url_origin = url::Origin::Create(url);
url::Origin redirect_origin;
bool has_any_prediction = GetRedirectEndpointsForPreconnect(
url_origin, *host_redirect_data_, prediction);
if (!GetRedirectOrigin(url_origin, *host_redirect_data_, &redirect_origin)) {
return has_any_prediction;
}
OriginData data;
if (!origin_data_->TryGetData(redirect_origin.host(), &data)) {
return has_any_prediction;
}
if (prediction) {
prediction->host = redirect_origin.host();
prediction->is_redirected = (redirect_origin != url_origin);
}
net::NetworkIsolationKey network_isolation_key(redirect_origin,
redirect_origin);
for (const OriginStat& origin : data.origins()) {
float confidence = static_cast<float>(origin.number_of_hits()) /
(origin.number_of_hits() + origin.number_of_misses());
if (confidence < kMinOriginConfidenceToTriggerPreresolve)
continue;
has_any_prediction = true;
if (prediction) {
if (confidence > kMinOriginConfidenceToTriggerPreconnect) {
prediction->requests.emplace_back(
url::Origin::Create(GURL(origin.origin())), 1,
network_isolation_key);
} else {
prediction->requests.emplace_back(
url::Origin::Create(GURL(origin.origin())), 0,
network_isolation_key);
}
}
}
return has_any_prediction;
}
| 172,382 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary,
int chunk_no,
__be32 rs_handle,
__be64 rs_offset,
u32 write_len)
{
struct rpcrdma_segment *seg = &ary->wc_array[chunk_no].wc_target;
seg->rs_handle = rs_handle;
seg->rs_offset = rs_offset;
seg->rs_length = cpu_to_be32(write_len);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | void svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary,
| 168,159 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Cluster::Cluster(
Segment* pSegment,
long idx,
long long element_start
/* long long element_size */ ) :
m_pSegment(pSegment),
m_element_start(element_start),
m_index(idx),
m_pos(element_start),
m_element_size(-1 /* element_size */ ),
m_timecode(-1),
m_entries(NULL),
m_entries_size(0),
m_entries_count(-1) //means "has not been parsed yet"
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Cluster::Cluster(
| 174,249 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep2,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
ND_TCHECK_16BITS(&p[2]);
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else {
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
| 167,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_release(ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
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_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb2_cache_entry *ce;
struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb2_cache_entry_find_first(ext2_mb_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
/*
* We have to be careful about races with freeing or
* rehashing of xattr block. Once we hold buffer lock
* xattr block's state is stable so we can check
* whether the block got freed / rehashed or not.
* Since we unhash mbcache entry under buffer lock when
* freeing / rehashing xattr block, checking whether
* entry is still hashed is reliable.
*/
if (hlist_bl_unhashed(&ce->e_hash_list)) {
mb2_cache_entry_put(ext2_mb_cache, ce);
unlock_buffer(bh);
brelse(bh);
goto again;
} else if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb2_cache_entry_touch(ext2_mb_cache, ce);
mb2_cache_entry_put(ext2_mb_cache, ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb2_cache_entry_find_next(ext2_mb_cache, ce);
}
return NULL;
}
| 169,977 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
init_get_bits8(&gb, buf, size);
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
Commit Message: avcodec/ac3_parser: Check init_get_bits8() for failure
Fixes: null pointer dereference
Fixes: ffmpeg_crash_6.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Reviewed-by: Paul B Mahol <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
err = init_get_bits8(&gb, buf, size);
if (err < 0)
return AVERROR_INVALIDDATA;
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
| 169,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
key->reject_error = -error;
smp_wmb();
set_bit(KEY_FLAG_NEGATIVE, &key->flags);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring && link_ret == 0)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20 | int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (key->state == KEY_IS_UNINSTANTIATED) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
mark_key_instantiated(key, -error);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring && link_ret == 0)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
| 167,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ContextState::RestoreTextureUnitBindings(
GLuint unit, const ContextState* prev_state) const {
DCHECK_LT(unit, texture_units.size());
const TextureUnit& texture_unit = texture_units[unit];
GLuint service_id_2d = Get2dServiceId(texture_unit);
GLuint service_id_cube = GetCubeServiceId(texture_unit);
GLuint service_id_oes = GetOesServiceId(texture_unit);
GLuint service_id_arb = GetArbServiceId(texture_unit);
bool bind_texture_2d = true;
bool bind_texture_cube = true;
bool bind_texture_oes =
feature_info_->feature_flags().oes_egl_image_external ||
feature_info_->feature_flags().nv_egl_stream_consumer_external;
bool bind_texture_arb = feature_info_->feature_flags().arb_texture_rectangle;
if (prev_state) {
const TextureUnit& prev_unit = prev_state->texture_units[unit];
bind_texture_2d = service_id_2d != Get2dServiceId(prev_unit);
bind_texture_cube = service_id_cube != GetCubeServiceId(prev_unit);
bind_texture_oes =
bind_texture_oes && service_id_oes != GetOesServiceId(prev_unit);
bind_texture_arb =
bind_texture_arb && service_id_arb != GetArbServiceId(prev_unit);
}
if (!bind_texture_2d && !bind_texture_cube
&& !bind_texture_oes && !bind_texture_arb) {
return;
}
api()->glActiveTextureFn(GL_TEXTURE0 + unit);
if (bind_texture_2d) {
api()->glBindTextureFn(GL_TEXTURE_2D, service_id_2d);
}
if (bind_texture_cube) {
api()->glBindTextureFn(GL_TEXTURE_CUBE_MAP, service_id_cube);
}
if (bind_texture_oes) {
api()->glBindTextureFn(GL_TEXTURE_EXTERNAL_OES, service_id_oes);
}
if (bind_texture_arb) {
api()->glBindTextureFn(GL_TEXTURE_RECTANGLE_ARB, service_id_arb);
}
}
Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data.
In linux and android, we are seeing an issue where texture data from one
tab overwrites the texture data of another tab. This is happening for apps
which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D.
Due to a bug in virtual context save/restore code for above texture formats,
the texture data is not properly restored while switching tabs. Hence
texture data from one tab overwrites other.
This CL has fix for that issue, an update for existing test expectations
and a new unit test for this bug.
Bug: 788448
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: Ie933984cdd2d1381f42eb4638f730c8245207a28
Reviewed-on: https://chromium-review.googlesource.com/930327
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: vikas soni <[email protected]>
Cr-Commit-Position: refs/heads/master@{#539111}
CWE ID: CWE-200 | void ContextState::RestoreTextureUnitBindings(
GLuint unit, const ContextState* prev_state) const {
DCHECK_LT(unit, texture_units.size());
const TextureUnit& texture_unit = texture_units[unit];
GLuint service_id_2d = Get2dServiceId(texture_unit);
GLuint service_id_2d_array = Get2dArrayServiceId(texture_unit);
GLuint service_id_3d = Get3dServiceId(texture_unit);
GLuint service_id_cube = GetCubeServiceId(texture_unit);
GLuint service_id_oes = GetOesServiceId(texture_unit);
GLuint service_id_arb = GetArbServiceId(texture_unit);
bool bind_texture_2d = true;
bool bind_texture_cube = true;
bool bind_texture_oes =
feature_info_->feature_flags().oes_egl_image_external ||
feature_info_->feature_flags().nv_egl_stream_consumer_external;
bool bind_texture_arb = feature_info_->feature_flags().arb_texture_rectangle;
// TEXTURE_2D_ARRAY and TEXTURE_3D are only applicable from ES3 version.
// So set it to FALSE by default.
bool bind_texture_2d_array = false;
bool bind_texture_3d = false;
// set the variables to true only if the application is ES3 or newer
if (feature_info_->IsES3Capable()) {
bind_texture_2d_array = true;
bind_texture_3d = true;
}
if (prev_state) {
const TextureUnit& prev_unit = prev_state->texture_units[unit];
bind_texture_2d = service_id_2d != Get2dServiceId(prev_unit);
bind_texture_2d_array =
service_id_2d_array != Get2dArrayServiceId(prev_unit);
bind_texture_3d = service_id_3d != Get3dServiceId(prev_unit);
bind_texture_cube = service_id_cube != GetCubeServiceId(prev_unit);
bind_texture_oes =
bind_texture_oes && service_id_oes != GetOesServiceId(prev_unit);
bind_texture_arb =
bind_texture_arb && service_id_arb != GetArbServiceId(prev_unit);
}
if (!bind_texture_2d && !bind_texture_2d_array && !bind_texture_3d &&
!bind_texture_cube && !bind_texture_oes && !bind_texture_arb) {
return;
}
api()->glActiveTextureFn(GL_TEXTURE0 + unit);
if (bind_texture_2d) {
api()->glBindTextureFn(GL_TEXTURE_2D, service_id_2d);
}
if (bind_texture_cube) {
api()->glBindTextureFn(GL_TEXTURE_CUBE_MAP, service_id_cube);
}
if (bind_texture_oes) {
api()->glBindTextureFn(GL_TEXTURE_EXTERNAL_OES, service_id_oes);
}
if (bind_texture_arb) {
api()->glBindTextureFn(GL_TEXTURE_RECTANGLE_ARB, service_id_arb);
}
if (bind_texture_2d_array) {
api()->glBindTextureFn(GL_TEXTURE_2D_ARRAY, service_id_2d_array);
}
if (bind_texture_3d) {
api()->glBindTextureFn(GL_TEXTURE_3D, service_id_3d);
}
}
| 172,911 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MostVisitedSitesBridge::JavaObserver::OnMostVisitedURLsAvailable(
const NTPTilesVector& tiles) {
JNIEnv* env = AttachCurrentThread();
std::vector<base::string16> titles;
std::vector<std::string> urls;
std::vector<std::string> whitelist_icon_paths;
std::vector<int> sources;
titles.reserve(tiles.size());
urls.reserve(tiles.size());
whitelist_icon_paths.reserve(tiles.size());
sources.reserve(tiles.size());
for (const auto& tile : tiles) {
titles.emplace_back(tile.title);
urls.emplace_back(tile.url.spec());
whitelist_icon_paths.emplace_back(tile.whitelist_icon_path.value());
sources.emplace_back(static_cast<int>(tile.source));
}
Java_MostVisitedURLsObserver_onMostVisitedURLsAvailable(
env, observer_, ToJavaArrayOfStrings(env, titles),
ToJavaArrayOfStrings(env, urls),
ToJavaArrayOfStrings(env, whitelist_icon_paths),
ToJavaIntArray(env, sources));
}
Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer.
BUG=677672
Review-Url: https://codereview.chromium.org/2697543002
Cr-Commit-Position: refs/heads/master@{#449958}
CWE ID: CWE-17 | void MostVisitedSitesBridge::JavaObserver::OnMostVisitedURLsAvailable(
const NTPTilesVector& tiles) {
JNIEnv* env = AttachCurrentThread();
std::vector<base::string16> titles;
std::vector<std::string> urls;
std::vector<std::string> whitelist_icon_paths;
std::vector<int> sources;
titles.reserve(tiles.size());
urls.reserve(tiles.size());
whitelist_icon_paths.reserve(tiles.size());
sources.reserve(tiles.size());
for (const auto& tile : tiles) {
titles.emplace_back(tile.title);
urls.emplace_back(tile.url.spec());
whitelist_icon_paths.emplace_back(tile.whitelist_icon_path.value());
sources.emplace_back(static_cast<int>(tile.source));
}
Java_Observer_onMostVisitedURLsAvailable(
env, observer_, ToJavaArrayOfStrings(env, titles),
ToJavaArrayOfStrings(env, urls),
ToJavaArrayOfStrings(env, whitelist_icon_paths),
ToJavaIntArray(env, sources));
}
| 172,035 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx)
{
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size)
{
const long n = (size <= 0) ? 2048 : 2*size;
Cluster** const qq = new Cluster*[n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p)
{
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
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 Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx)
if (m_clusterPreloadCount > 0) {
assert(m_clusters);
Cluster** const p = m_clusters + m_clusterCount;
assert(*p);
assert((*p)->m_index < 0);
Cluster** q = p + m_clusterPreloadCount;
assert(q < (m_clusters + size));
for (;;) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
}
| 174,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FPXColorspace
colorspace;
FPXImageComponentDesc
*alpha_component,
*blue_component,
*green_component,
*red_component;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*a,
*b,
*g,
*r;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
height,
tile_width,
tile_height,
width;
size_t
scene;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
fpx_status=FPX_InitSystem();
if (fpx_status != FPX_OK)
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
}
tile_width=64;
tile_height=64;
flashpix=(FPXImageHandle *) NULL;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(image->filename,&fsspec);
fpx_status=FPX_OpenImageByFilename((const FSSpec &) fsspec,(char *) NULL,
#else
fpx_status=FPX_OpenImageByFilename(image->filename,(char *) NULL,
#endif
&width,&height,&tile_width,&tile_height,&colorspace,&flashpix);
}
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (colorspace.numberOfComponents == 0)
{
FPX_ClearSystem();
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
if (image_info->view == (char *) NULL)
{
float
aspect_ratio;
/*
Get the aspect ratio.
*/
aspect_ratio=(float) width/height;
fpx_status=FPX_GetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowReaderException(DelegateError,"UnableToReadAspectRatio");
if (width != (size_t) floor((aspect_ratio*height)+0.5))
Swap(width,height);
}
fpx_status=FPX_GetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(DelegateError,"UnableToReadSummaryInfo");
}
if (summary_info.title_valid)
if ((summary_info.title.length != 0) &&
(summary_info.title.ptr != (unsigned char *) NULL))
{
char
*label;
/*
Note image label.
*/
label=(char *) NULL;
if (~summary_info.title.length >= (MaxTextExtent-1))
label=(char *) AcquireQuantumMemory(summary_info.title.length+
MaxTextExtent,sizeof(*label));
if (label == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(label,(char *) summary_info.title.ptr,
summary_info.title.length+1);
(void) SetImageProperty(image,"label",label);
label=DestroyString(label);
}
if (summary_info.comments_valid)
if ((summary_info.comments.length != 0) &&
(summary_info.comments.ptr != (unsigned char *) NULL))
{
char
*comments;
/*
Note image comment.
*/
comments=(char *) NULL;
if (~summary_info.comments.length >= (MaxTextExtent-1))
comments=(char *) AcquireQuantumMemory(summary_info.comments.length+
MaxTextExtent,sizeof(*comments));
if (comments == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(comments,(char *) summary_info.comments.ptr,
summary_info.comments.length+1);
(void) SetImageProperty(image,"comment",comments);
comments=DestroyString(comments);
}
/*
Determine resolution by scene specification.
*/
for (i=1; ; i++)
if (((width >> i) < tile_width) || ((height >> i) < tile_height))
break;
scene=i;
if (image_info->number_scenes != 0)
while (scene > image_info->scene)
{
width>>=1;
height>>=1;
scene--;
}
if (image_info->size != (char *) NULL)
while ((width > image->columns) || (height > image->rows))
{
width>>=1;
height>>=1;
scene--;
}
image->depth=8;
image->columns=width;
image->rows=height;
if ((colorspace.numberOfComponents % 2) == 0)
image->matte=MagickTrue;
if (colorspace.numberOfComponents == 1)
{
/*
Create linear colormap.
*/
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (image_info->ping != MagickFalse)
{
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,(tile_height+
1UL)*colorspace.numberOfComponents*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
FPX_ClearSystem();
(void) FPX_CloseImage(flashpix);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize FlashPix image description.
*/
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < 4; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=image->columns*
fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_R : MONOCHROME;
red_component=(&fpx_info.components[0]);
fpx_info.components[1].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_G : ALPHA;
green_component=(&fpx_info.components[1]);
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
blue_component=(&fpx_info.components[2]);
fpx_info.components[3].myColorType.myColor=ALPHA;
alpha_component=(&fpx_info.components[fpx_info.numberOfComponents-1]);
FPX_SetResampleMethod(FPX_LINEAR_INTERPOLATION);
/*
Initialize image pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if ((y % tile_height) == 0)
{
/*
Read FPX image tile (with or without viewing affine)..
*/
if (image_info->view != (char *) NULL)
fpx_status=FPX_ReadImageRectangle(flashpix,0,y,image->columns,y+
tile_height-1,scene,&fpx_info);
else
fpx_status=FPX_ReadImageTransformRectangle(flashpix,0.0F,
(float) y/image->rows,(float) image->columns/image->rows,
(float) (y+tile_height-1)/image->rows,(ssize_t) image->columns,
(ssize_t) tile_height,&fpx_info);
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
/*
Transfer a FPX pixels.
*/
r=red_component->theData+(y % tile_height)*red_component->lineStride;
g=green_component->theData+(y % tile_height)*green_component->lineStride;
b=blue_component->theData+(y % tile_height)*blue_component->lineStride;
a=alpha_component->theData+(y % tile_height)*alpha_component->lineStride;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (fpx_info.numberOfComponents > 2)
{
SetPixelRed(q,ScaleCharToQuantum(*r));
SetPixelGreen(q,ScaleCharToQuantum(*g));
SetPixelBlue(q,ScaleCharToQuantum(*b));
}
else
{
index=ScaleCharToQuantum(*r);
SetPixelIndex(indexes+x,index);
SetPixelRed(q,index);
SetPixelGreen(q,index);
SetPixelBlue(q,index);
}
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*a));
q++;
r+=red_component->columnStride;
g+=green_component->columnStride;
b+=blue_component->columnStride;
a+=alpha_component->columnStride;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FPXColorspace
colorspace;
FPXImageComponentDesc
*alpha_component,
*blue_component,
*green_component,
*red_component;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*a,
*b,
*g,
*r;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
height,
tile_width,
tile_height,
width;
size_t
scene;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
fpx_status=FPX_InitSystem();
if (fpx_status != FPX_OK)
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
}
tile_width=64;
tile_height=64;
flashpix=(FPXImageHandle *) NULL;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(image->filename,&fsspec);
fpx_status=FPX_OpenImageByFilename((const FSSpec &) fsspec,(char *) NULL,
#else
fpx_status=FPX_OpenImageByFilename(image->filename,(char *) NULL,
#endif
&width,&height,&tile_width,&tile_height,&colorspace,&flashpix);
}
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (colorspace.numberOfComponents == 0)
{
FPX_ClearSystem();
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
if (image_info->view == (char *) NULL)
{
float
aspect_ratio;
/*
Get the aspect ratio.
*/
aspect_ratio=(float) width/height;
fpx_status=FPX_GetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowReaderException(DelegateError,"UnableToReadAspectRatio");
if (width != (size_t) floor((aspect_ratio*height)+0.5))
Swap(width,height);
}
fpx_status=FPX_GetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(DelegateError,"UnableToReadSummaryInfo");
}
if (summary_info.title_valid)
if ((summary_info.title.length != 0) &&
(summary_info.title.ptr != (unsigned char *) NULL))
{
char
*label;
/*
Note image label.
*/
label=(char *) NULL;
if (~summary_info.title.length >= (MaxTextExtent-1))
label=(char *) AcquireQuantumMemory(summary_info.title.length+
MaxTextExtent,sizeof(*label));
if (label == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(label,(char *) summary_info.title.ptr,
summary_info.title.length+1);
(void) SetImageProperty(image,"label",label);
label=DestroyString(label);
}
if (summary_info.comments_valid)
if ((summary_info.comments.length != 0) &&
(summary_info.comments.ptr != (unsigned char *) NULL))
{
char
*comments;
/*
Note image comment.
*/
comments=(char *) NULL;
if (~summary_info.comments.length >= (MaxTextExtent-1))
comments=(char *) AcquireQuantumMemory(summary_info.comments.length+
MaxTextExtent,sizeof(*comments));
if (comments == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(comments,(char *) summary_info.comments.ptr,
summary_info.comments.length+1);
(void) SetImageProperty(image,"comment",comments);
comments=DestroyString(comments);
}
/*
Determine resolution by scene specification.
*/
for (i=1; ; i++)
if (((width >> i) < tile_width) || ((height >> i) < tile_height))
break;
scene=i;
if (image_info->number_scenes != 0)
while (scene > image_info->scene)
{
width>>=1;
height>>=1;
scene--;
}
if (image_info->size != (char *) NULL)
while ((width > image->columns) || (height > image->rows))
{
width>>=1;
height>>=1;
scene--;
}
image->depth=8;
image->columns=width;
image->rows=height;
if ((colorspace.numberOfComponents % 2) == 0)
image->matte=MagickTrue;
if (colorspace.numberOfComponents == 1)
{
/*
Create linear colormap.
*/
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (image_info->ping != MagickFalse)
{
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,(tile_height+
1UL)*colorspace.numberOfComponents*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
FPX_ClearSystem();
(void) FPX_CloseImage(flashpix);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize FlashPix image description.
*/
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < 4; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=image->columns*
fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_R : MONOCHROME;
red_component=(&fpx_info.components[0]);
fpx_info.components[1].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_G : ALPHA;
green_component=(&fpx_info.components[1]);
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
blue_component=(&fpx_info.components[2]);
fpx_info.components[3].myColorType.myColor=ALPHA;
alpha_component=(&fpx_info.components[fpx_info.numberOfComponents-1]);
FPX_SetResampleMethod(FPX_LINEAR_INTERPOLATION);
/*
Initialize image pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if ((y % tile_height) == 0)
{
/*
Read FPX image tile (with or without viewing affine)..
*/
if (image_info->view != (char *) NULL)
fpx_status=FPX_ReadImageRectangle(flashpix,0,y,image->columns,y+
tile_height-1,scene,&fpx_info);
else
fpx_status=FPX_ReadImageTransformRectangle(flashpix,0.0F,
(float) y/image->rows,(float) image->columns/image->rows,
(float) (y+tile_height-1)/image->rows,(ssize_t) image->columns,
(ssize_t) tile_height,&fpx_info);
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
/*
Transfer a FPX pixels.
*/
r=red_component->theData+(y % tile_height)*red_component->lineStride;
g=green_component->theData+(y % tile_height)*green_component->lineStride;
b=blue_component->theData+(y % tile_height)*blue_component->lineStride;
a=alpha_component->theData+(y % tile_height)*alpha_component->lineStride;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (fpx_info.numberOfComponents > 2)
{
SetPixelRed(q,ScaleCharToQuantum(*r));
SetPixelGreen(q,ScaleCharToQuantum(*g));
SetPixelBlue(q,ScaleCharToQuantum(*b));
}
else
{
index=ScaleCharToQuantum(*r);
SetPixelIndex(indexes+x,index);
SetPixelRed(q,index);
SetPixelGreen(q,index);
SetPixelBlue(q,index);
}
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*a));
q++;
r+=red_component->columnStride;
g+=green_component->columnStride;
b+=blue_component->columnStride;
a+=alpha_component->columnStride;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
| 168,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> supplementalMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestInterface.supplementalMethod2");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
TestInterface* imp = V8TestInterface::toNative(args.Holder());
ExceptionCode ec = 0;
{
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0);
ScriptExecutionContext* scriptContext = getScriptExecutionContext();
if (!scriptContext)
return v8::Undefined();
RefPtr<TestObj> result = TestSupplemental::supplementalMethod2(imp, scriptContext, strArg, objArg, ec);
if (UNLIKELY(ec))
goto fail;
return toV8(result.release(), args.GetIsolate());
}
fail:
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> supplementalMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestInterface.supplementalMethod2");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestInterface* imp = V8TestInterface::toNative(args.Holder());
ExceptionCode ec = 0;
{
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0);
ScriptExecutionContext* scriptContext = getScriptExecutionContext();
if (!scriptContext)
return v8::Undefined();
RefPtr<TestObj> result = TestSupplemental::supplementalMethod2(imp, scriptContext, strArg, objArg, ec);
if (UNLIKELY(ec))
goto fail;
return toV8(result.release(), args.GetIsolate());
}
fail:
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
| 171,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
schedule();
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
mutex_lock(&tu->ioctl_lock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
mutex_unlock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
return result > 0 ? result : err;
}
Commit Message: ALSA: timer: Fix race between read and ioctl
The read from ALSA timer device, the function snd_timer_user_tread(),
may access to an uninitialized struct snd_timer_user fields when the
read is concurrently performed while the ioctl like
snd_timer_user_tselect() is invoked. We have already fixed the races
among ioctls via a mutex, but we seem to have forgotten the race
between read vs ioctl.
This patch simply applies (more exactly extends the already applied
range of) tu->ioctl_lock in snd_timer_user_tread() for closing the
race window.
Reported-by: Alexander Potapenko <[email protected]>
Tested-by: Alexander Potapenko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-200 | static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
schedule();
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
return result > 0 ? result : err;
}
| 170,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void dtls1_free(SSL *s)
{
DTLS_RECORD_LAYER_free(&s->rlayer);
{
pqueue *buffered_messages;
pqueue *sent_messages;
unsigned int mtu;
unsigned int link_mtu;
DTLS_RECORD_LAYER_clear(&s->rlayer);
if (s->d1) {
buffered_messages = s->d1->buffered_messages;
sent_messages = s->d1->sent_messages;
mtu = s->d1->mtu;
link_mtu = s->d1->link_mtu;
dtls1_clear_queues(s);
memset(s->d1, 0, sizeof(*s->d1));
if (s->server) {
s->d1->cookie_len = sizeof(s->d1->cookie);
}
if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
s->d1->mtu = mtu;
s->d1->link_mtu = link_mtu;
}
s->d1->buffered_messages = buffered_messages;
s->d1->sent_messages = sent_messages;
}
ssl3_clear(s);
if (s->method->version == DTLS_ANY_VERSION)
s->version = DTLS_MAX_VERSION;
#ifndef OPENSSL_NO_DTLS1_METHOD
else if (s->options & SSL_OP_CISCO_ANYCONNECT)
s->client_version = s->version = DTLS1_BAD_VER;
#endif
else
s->version = s->method->version;
}
long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret = 0;
switch (cmd) {
case DTLS_CTRL_GET_TIMEOUT:
if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
ret = 1;
}
break;
case DTLS_CTRL_HANDLE_TIMEOUT:
ret = dtls1_handle_timeout(s);
break;
case DTLS_CTRL_SET_LINK_MTU:
if (larg < (long)dtls1_link_min_mtu())
return 0;
s->d1->link_mtu = larg;
return 1;
case DTLS_CTRL_GET_LINK_MIN_MTU:
return (long)dtls1_link_min_mtu();
case SSL_CTRL_SET_MTU:
/*
* We may not have a BIO set yet so can't call dtls1_min_mtu()
* We'll have to make do with dtls1_link_min_mtu() and max overhead
*/
if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
return 0;
s->d1->mtu = larg;
return larg;
default:
ret = ssl3_ctrl(s, cmd, larg, parg);
break;
}
return (ret);
}
void dtls1_start_timer(SSL *s)
{
#ifndef OPENSSL_NO_SCTP
/* Disable timer for SCTP */
if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
return;
}
#endif
/* If timer is not set, initialize duration with 1 second */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
s->d1->timeout_duration = 1;
}
/* Set timeout to current time */
get_current_time(&(s->d1->next_timeout));
/* Add duration to current time */
s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
}
struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
{
struct timeval timenow;
/* If no timeout is set, just return NULL */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
return NULL;
}
/* Get current time */
get_current_time(&timenow);
/* If timer already expired, set remaining time to 0 */
if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
(s->d1->next_timeout.tv_sec == timenow.tv_sec &&
s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
memset(timeleft, 0, sizeof(*timeleft));
return timeleft;
}
/* Calculate time left until timer expires */
memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
timeleft->tv_sec -= timenow.tv_sec;
timeleft->tv_usec -= timenow.tv_usec;
if (timeleft->tv_usec < 0) {
timeleft->tv_sec--;
timeleft->tv_usec += 1000000;
}
/*
* If remaining time is less than 15 ms, set it to 0 to prevent issues
* because of small divergences with socket timeouts.
*/
if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
memset(timeleft, 0, sizeof(*timeleft));
}
return timeleft;
}
int dtls1_is_timer_expired(SSL *s)
{
struct timeval timeleft;
/* Get time left until timeout, return false if no timer running */
if (dtls1_get_timeout(s, &timeleft) == NULL) {
return 0;
}
/* Return false if timer is not expired yet */
if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
return 0;
}
/* Timer expired, so return true */
return 1;
}
void dtls1_double_timeout(SSL *s)
{
s->d1->timeout_duration *= 2;
if (s->d1->timeout_duration > 60)
s->d1->timeout_duration = 60;
dtls1_start_timer(s);
}
void dtls1_stop_timer(SSL *s)
{
/* Reset everything */
memset(&s->d1->timeout, 0, sizeof(s->d1->timeout));
memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
s->d1->timeout_duration = 1;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_record_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
{
unsigned int mtu;
s->d1->timeout.num_alerts++;
/* Reduce MTU after 2 unsuccessful retransmissions */
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_record_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
/* fail the connection, enough alerts have been sent */
SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
return -1;
}
return 0;
}
Commit Message:
CWE ID: CWE-399 | void dtls1_free(SSL *s)
{
DTLS_RECORD_LAYER_free(&s->rlayer);
{
pqueue *buffered_messages;
pqueue *sent_messages;
unsigned int mtu;
unsigned int link_mtu;
DTLS_RECORD_LAYER_clear(&s->rlayer);
if (s->d1) {
buffered_messages = s->d1->buffered_messages;
sent_messages = s->d1->sent_messages;
mtu = s->d1->mtu;
link_mtu = s->d1->link_mtu;
dtls1_clear_queues(s);
memset(s->d1, 0, sizeof(*s->d1));
if (s->server) {
s->d1->cookie_len = sizeof(s->d1->cookie);
}
if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
s->d1->mtu = mtu;
s->d1->link_mtu = link_mtu;
}
s->d1->buffered_messages = buffered_messages;
s->d1->sent_messages = sent_messages;
}
ssl3_clear(s);
if (s->method->version == DTLS_ANY_VERSION)
s->version = DTLS_MAX_VERSION;
#ifndef OPENSSL_NO_DTLS1_METHOD
else if (s->options & SSL_OP_CISCO_ANYCONNECT)
s->client_version = s->version = DTLS1_BAD_VER;
#endif
else
s->version = s->method->version;
}
long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret = 0;
switch (cmd) {
case DTLS_CTRL_GET_TIMEOUT:
if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
ret = 1;
}
break;
case DTLS_CTRL_HANDLE_TIMEOUT:
ret = dtls1_handle_timeout(s);
break;
case DTLS_CTRL_SET_LINK_MTU:
if (larg < (long)dtls1_link_min_mtu())
return 0;
s->d1->link_mtu = larg;
return 1;
case DTLS_CTRL_GET_LINK_MIN_MTU:
return (long)dtls1_link_min_mtu();
case SSL_CTRL_SET_MTU:
/*
* We may not have a BIO set yet so can't call dtls1_min_mtu()
* We'll have to make do with dtls1_link_min_mtu() and max overhead
*/
if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
return 0;
s->d1->mtu = larg;
return larg;
default:
ret = ssl3_ctrl(s, cmd, larg, parg);
break;
}
return (ret);
}
void dtls1_start_timer(SSL *s)
{
#ifndef OPENSSL_NO_SCTP
/* Disable timer for SCTP */
if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
return;
}
#endif
/* If timer is not set, initialize duration with 1 second */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
s->d1->timeout_duration = 1;
}
/* Set timeout to current time */
get_current_time(&(s->d1->next_timeout));
/* Add duration to current time */
s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
}
struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
{
struct timeval timenow;
/* If no timeout is set, just return NULL */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
return NULL;
}
/* Get current time */
get_current_time(&timenow);
/* If timer already expired, set remaining time to 0 */
if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
(s->d1->next_timeout.tv_sec == timenow.tv_sec &&
s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
memset(timeleft, 0, sizeof(*timeleft));
return timeleft;
}
/* Calculate time left until timer expires */
memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
timeleft->tv_sec -= timenow.tv_sec;
timeleft->tv_usec -= timenow.tv_usec;
if (timeleft->tv_usec < 0) {
timeleft->tv_sec--;
timeleft->tv_usec += 1000000;
}
/*
* If remaining time is less than 15 ms, set it to 0 to prevent issues
* because of small divergences with socket timeouts.
*/
if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
memset(timeleft, 0, sizeof(*timeleft));
}
return timeleft;
}
int dtls1_is_timer_expired(SSL *s)
{
struct timeval timeleft;
/* Get time left until timeout, return false if no timer running */
if (dtls1_get_timeout(s, &timeleft) == NULL) {
return 0;
}
/* Return false if timer is not expired yet */
if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
return 0;
}
/* Timer expired, so return true */
return 1;
}
void dtls1_double_timeout(SSL *s)
{
s->d1->timeout_duration *= 2;
if (s->d1->timeout_duration > 60)
s->d1->timeout_duration = 60;
dtls1_start_timer(s);
}
void dtls1_stop_timer(SSL *s)
{
/* Reset everything */
memset(&s->d1->timeout, 0, sizeof(s->d1->timeout));
memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
s->d1->timeout_duration = 1;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_record_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
{
unsigned int mtu;
s->d1->timeout.num_alerts++;
/* Reduce MTU after 2 unsuccessful retransmissions */
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_sent_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
/* fail the connection, enough alerts have been sent */
SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
return -1;
}
return 0;
}
| 165,196 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> methodWithNonOptionalArgAndTwoOptionalArgsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodWithNonOptionalArgAndTwoOptionalArgs");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
if (args.Length() <= 1) {
imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, opt1, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
if (args.Length() <= 2) {
imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, opt2, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)));
imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> methodWithNonOptionalArgAndTwoOptionalArgsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodWithNonOptionalArgAndTwoOptionalArgs");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
if (args.Length() <= 1) {
imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, opt1, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
if (args.Length() <= 2) {
imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, opt2, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)));
imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2);
return v8::Handle<v8::Value>();
}
| 171,091 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
{
down_write(&tty->termios_rwsem);
tty->termios.c_line = num;
up_write(&tty->termios_rwsem);
}
Commit Message: tty: Prevent ldisc drivers from re-using stale tty fields
Line discipline drivers may mistakenly misuse ldisc-related fields
when initializing. For example, a failure to initialize tty->receive_room
in the N_GIGASET_M101 line discipline was recently found and fixed [1].
Now, the N_X25 line discipline has been discovered accessing the previous
line discipline's already-freed private data [2].
Harden the ldisc interface against misuse by initializing revelant
tty fields before instancing the new line discipline.
[1]
commit fd98e9419d8d622a4de91f76b306af6aa627aa9c
Author: Tilman Schmidt <[email protected]>
Date: Tue Jul 14 00:37:13 2015 +0200
isdn/gigaset: reset tty->receive_room when attaching ser_gigaset
[2] Report from Sasha Levin <[email protected]>
[ 634.336761] ==================================================================
[ 634.338226] BUG: KASAN: use-after-free in x25_asy_open_tty+0x13d/0x490 at addr ffff8800a743efd0
[ 634.339558] Read of size 4 by task syzkaller_execu/8981
[ 634.340359] =============================================================================
[ 634.341598] BUG kmalloc-512 (Not tainted): kasan: bad access detected
...
[ 634.405018] Call Trace:
[ 634.405277] dump_stack (lib/dump_stack.c:52)
[ 634.405775] print_trailer (mm/slub.c:655)
[ 634.406361] object_err (mm/slub.c:662)
[ 634.406824] kasan_report_error (mm/kasan/report.c:138 mm/kasan/report.c:236)
[ 634.409581] __asan_report_load4_noabort (mm/kasan/report.c:279)
[ 634.411355] x25_asy_open_tty (drivers/net/wan/x25_asy.c:559 (discriminator 1))
[ 634.413997] tty_ldisc_open.isra.2 (drivers/tty/tty_ldisc.c:447)
[ 634.414549] tty_set_ldisc (drivers/tty/tty_ldisc.c:567)
[ 634.415057] tty_ioctl (drivers/tty/tty_io.c:2646 drivers/tty/tty_io.c:2879)
[ 634.423524] do_vfs_ioctl (fs/ioctl.c:43 fs/ioctl.c:607)
[ 634.427491] SyS_ioctl (fs/ioctl.c:622 fs/ioctl.c:613)
[ 634.427945] entry_SYSCALL_64_fastpath (arch/x86/entry/entry_64.S:188)
Cc: Tilman Schmidt <[email protected]>
Cc: Sasha Levin <[email protected]>
Signed-off-by: Peter Hurley <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200 | static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
{
down_write(&tty->termios_rwsem);
tty->termios.c_line = num;
up_write(&tty->termios_rwsem);
tty->disc_data = NULL;
tty->receive_room = 0;
}
| 167,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ParseJSONDictionary(const std::string& json, DictionaryValue** dict,
std::string* error) {
int error_code = 0;
Value* params =
base::JSONReader::ReadAndReturnError(json, true, &error_code, error);
if (error_code != 0) {
VLOG(1) << "Could not parse JSON object, " << *error;
if (params)
delete params;
return false;
}
if (!params || params->GetType() != Value::TYPE_DICTIONARY) {
*error = "Data passed in URL must be of type dictionary.";
VLOG(1) << "Invalid type to parse";
if (params)
delete params;
return false;
}
*dict = static_cast<DictionaryValue*>(params);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ParseJSONDictionary(const std::string& json, DictionaryValue** dict,
| 170,466 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::LoadingStateChanged(bool to_different_document,
bool due_to_interstitial,
LoadNotificationDetails* details) {
if (ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber() &&
!due_to_interstitial) {
return;
}
bool is_loading = IsLoading();
if (!is_loading) {
load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
load_state_host_.clear();
upload_size_ = 0;
upload_position_ = 0;
}
GetRenderManager()->SetIsLoading(is_loading);
waiting_for_response_ = is_loading;
is_load_to_different_document_ = to_different_document;
if (delegate_)
delegate_->LoadingStateChanged(this, to_different_document);
NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
if (is_loading) {
TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
this, "URL", url, "Main FrameTreeNode id",
GetFrameTree()->root()->frame_tree_node_id());
for (auto& observer : observers_)
observer.DidStartLoading();
} else {
TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
this, "URL", url);
for (auto& observer : observers_)
observer.DidStopLoading();
}
int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
NotificationDetails det = NotificationService::NoDetails();
if (details)
det = Details<LoadNotificationDetails>(details);
NotificationService::current()->Notify(
type, Source<NavigationController>(&controller_), det);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void WebContentsImpl::LoadingStateChanged(bool to_different_document,
bool due_to_interstitial,
LoadNotificationDetails* details) {
if (ShowingInterstitialPage() && interstitial_page_->pause_throbber() &&
!due_to_interstitial) {
return;
}
bool is_loading = IsLoading();
if (!is_loading) {
load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
load_state_host_.clear();
upload_size_ = 0;
upload_position_ = 0;
}
GetRenderManager()->SetIsLoading(is_loading);
waiting_for_response_ = is_loading;
is_load_to_different_document_ = to_different_document;
if (delegate_)
delegate_->LoadingStateChanged(this, to_different_document);
NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
if (is_loading) {
TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
this, "URL", url, "Main FrameTreeNode id",
GetFrameTree()->root()->frame_tree_node_id());
for (auto& observer : observers_)
observer.DidStartLoading();
} else {
TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
this, "URL", url);
for (auto& observer : observers_)
observer.DidStopLoading();
}
int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
NotificationDetails det = NotificationService::NoDetails();
if (details)
det = Details<LoadNotificationDetails>(details);
NotificationService::current()->Notify(
type, Source<NavigationController>(&controller_), det);
}
| 172,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
| 168,889 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr_leaf_addname(xfs_da_args_t *args)
{
xfs_inode_t *dp;
struct xfs_buf *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_leaf_addname(args);
/*
* Read the (only) block in the attribute list in.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
/*
* Look up the given attribute in the leaf block. Figure out if
* the given flags produce an error or call for an atomic rename.
*/
retval = xfs_attr3_leaf_lookup_int(bp, args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
xfs_trans_brelse(args->trans, bp);
return retval;
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE) { /* pure create op */
xfs_trans_brelse(args->trans, bp);
return retval;
}
trace_xfs_attr_leaf_replace(args);
args->op_flags |= XFS_DA_OP_RENAME; /* an atomic rename */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
}
/*
* Add the attribute to the leaf block, transitioning to a Btree
* if required.
*/
retval = xfs_attr3_leaf_add(bp, args);
if (retval == ENOSPC) {
/*
* Promote the attribute list to the Btree format, then
* Commit that transaction so that the node_addname() call
* can manage its own transactions.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the current trans (including the inode) and start
* a new one.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* Fob the whole rest of the problem off on the Btree code.
*/
error = xfs_attr_node_addname(args);
return(error);
}
/*
* Commit the transaction that added the attr name so that
* later routines can manage their own transactions.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr3_leaf_flipflags(args);
if (error)
return(error);
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Read in the block containing the "old" attr, then
* remove the "old" attr from that block (neat, huh!)
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno,
-1, &bp);
if (error)
return error;
xfs_attr3_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
/*
* Commit the remove and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, dp);
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr3_leaf_clearflag(args);
}
return error;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr_leaf_addname(xfs_da_args_t *args)
{
xfs_inode_t *dp;
struct xfs_buf *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_leaf_addname(args);
/*
* Read the (only) block in the attribute list in.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
if (error)
return error;
/*
* Look up the given attribute in the leaf block. Figure out if
* the given flags produce an error or call for an atomic rename.
*/
retval = xfs_attr3_leaf_lookup_int(bp, args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
xfs_trans_brelse(args->trans, bp);
return retval;
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE) { /* pure create op */
xfs_trans_brelse(args->trans, bp);
return retval;
}
trace_xfs_attr_leaf_replace(args);
/* save the attribute state for later removal*/
args->op_flags |= XFS_DA_OP_RENAME; /* an atomic rename */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
args->rmtvaluelen2 = args->rmtvaluelen;
/*
* clear the remote attr state now that it is saved so that the
* values reflect the state of the attribute we are about to
* add, not the attribute we just found and will remove later.
*/
args->rmtblkno = 0;
args->rmtblkcnt = 0;
args->rmtvaluelen = 0;
}
/*
* Add the attribute to the leaf block, transitioning to a Btree
* if required.
*/
retval = xfs_attr3_leaf_add(bp, args);
if (retval == ENOSPC) {
/*
* Promote the attribute list to the Btree format, then
* Commit that transaction so that the node_addname() call
* can manage its own transactions.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the current trans (including the inode) and start
* a new one.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* Fob the whole rest of the problem off on the Btree code.
*/
error = xfs_attr_node_addname(args);
return(error);
}
/*
* Commit the transaction that added the attr name so that
* later routines can manage their own transactions.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr3_leaf_flipflags(args);
if (error)
return(error);
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
args->rmtvaluelen = args->rmtvaluelen2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Read in the block containing the "old" attr, then
* remove the "old" attr from that block (neat, huh!)
*/
error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno,
-1, &bp);
if (error)
return error;
xfs_attr3_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr3_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
/*
* Commit the remove and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, dp);
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr3_leaf_clearflag(args);
}
return error;
}
| 166,731 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static JSValue getDataViewMember(ExecState* exec, DataView* imp, DataViewAccessType type)
{
if (exec->argumentCount() < 1)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
unsigned byteOffset = exec->argument(0).toUInt32(exec);
if (exec->hadException())
return jsUndefined();
bool littleEndian = false;
if (exec->argumentCount() > 1 && (type == AccessDataViewMemberAsFloat32 || type == AccessDataViewMemberAsFloat64)) {
littleEndian = exec->argument(1).toBoolean(exec);
if (exec->hadException())
return jsUndefined();
}
JSC::JSValue result;
switch (type) {
case AccessDataViewMemberAsInt8:
result = jsNumber(imp->getInt8(byteOffset, ec));
break;
case AccessDataViewMemberAsUint8:
result = jsNumber(imp->getUint8(byteOffset, ec));
break;
case AccessDataViewMemberAsFloat32:
case AccessDataViewMemberAsFloat64: {
double value = (type == AccessDataViewMemberAsFloat32) ? imp->getFloat32(byteOffset, littleEndian, ec) : imp->getFloat64(byteOffset, littleEndian, ec);
result = isnan(value) ? jsNaN() : jsNumber(value);
break;
} default:
ASSERT_NOT_REACHED();
break;
}
setDOMException(exec, ec);
return result;
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | static JSValue getDataViewMember(ExecState* exec, DataView* imp, DataViewAccessType type)
{
if (exec->argumentCount() < 1)
return throwError(exec, createNotEnoughArgumentsError(exec));
ExceptionCode ec = 0;
unsigned byteOffset = exec->argument(0).toUInt32(exec);
if (exec->hadException())
return jsUndefined();
bool littleEndian = false;
if (exec->argumentCount() > 1 && (type == AccessDataViewMemberAsFloat32 || type == AccessDataViewMemberAsFloat64)) {
littleEndian = exec->argument(1).toBoolean(exec);
if (exec->hadException())
return jsUndefined();
}
JSC::JSValue result;
switch (type) {
case AccessDataViewMemberAsInt8:
result = jsNumber(imp->getInt8(byteOffset, ec));
break;
case AccessDataViewMemberAsUint8:
result = jsNumber(imp->getUint8(byteOffset, ec));
break;
case AccessDataViewMemberAsFloat32:
case AccessDataViewMemberAsFloat64: {
double value = (type == AccessDataViewMemberAsFloat32) ? imp->getFloat32(byteOffset, littleEndian, ec) : imp->getFloat64(byteOffset, littleEndian, ec);
result = isnan(value) ? jsNaN() : jsNumber(value);
break;
} default:
ASSERT_NOT_REACHED();
break;
}
setDOMException(exec, ec);
return result;
}
| 170,557 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by, int div_by)
{
lba512_t bc_quot, bc_rem;
/* x * m / d == x / d * m + (x % d) * m / d */
bc_quot = block_count >> div_by;
bc_rem = block_count - (bc_quot << div_by);
return bc_quot * mul_by + ((bc_rem * mul_by) >> div_by);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | static lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by, int div_by)
static lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by,
int right_shift)
{
lba512_t bc_quot, bc_rem;
/* x * m / d == x / d * m + (x % d) * m / d */
bc_quot = block_count >> right_shift;
bc_rem = block_count - (bc_quot << right_shift);
return bc_quot * mul_by + ((bc_rem * mul_by) >> right_shift);
}
| 169,641 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NetworkHandler::SetCookies(
std::unique_ptr<protocol::Array<Network::CookieParam>> cookies,
std::unique_ptr<SetCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&SetCookiesOnIO,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
std::move(cookies),
base::BindOnce(&CookiesSetOnIO, std::move(callback))));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::SetCookies(
std::unique_ptr<protocol::Array<Network::CookieParam>> cookies,
std::unique_ptr<SetCookiesCallback> callback) {
if (!storage_partition_) {
callback->sendFailure(Response::InternalError());
return;
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&SetCookiesOnIO,
base::Unretained(storage_partition_->GetURLRequestContext()),
std::move(cookies),
base::BindOnce(&CookiesSetOnIO, std::move(callback))));
}
| 172,761 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() {
return keyboard_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() {
| 170,624 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int pop_fetch_headers(struct Context *ctx)
{
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = pop_hcache_open(pop_data, ctx->path);
#endif
time(&pop_data->check_time);
pop_data->clear_cache = false;
for (int i = 0; i < ctx->msgcount; i++)
ctx->hdrs[i]->refno = -1;
const int old_count = ctx->msgcount;
int ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
const int new_count = ctx->msgcount;
ctx->msgcount = old_count;
if (pop_data->cmd_uidl == 2)
{
if (ret == 0)
{
pop_data->cmd_uidl = 1;
mutt_debug(1, "set UIDL capability\n");
}
if (ret == -2 && pop_data->cmd_uidl == 2)
{
pop_data->cmd_uidl = 0;
mutt_debug(1, "unset UIDL capability\n");
snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s",
_("Command UIDL is not supported by server."));
}
}
if (!ctx->quiet)
{
mutt_progress_init(&progress, _("Fetching message headers..."),
MUTT_PROGRESS_MSG, ReadInc, new_count - old_count);
}
if (ret == 0)
{
int i, deleted;
for (i = 0, deleted = 0; i < old_count; i++)
{
if (ctx->hdrs[i]->refno == -1)
{
ctx->hdrs[i]->deleted = true;
deleted++;
}
}
if (deleted > 0)
{
mutt_error(
ngettext("%d message has been lost. Try reopening the mailbox.",
"%d messages have been lost. Try reopening the mailbox.", deleted),
deleted);
}
bool hcached = false;
for (i = old_count; i < new_count; i++)
{
if (!ctx->quiet)
mutt_progress_update(&progress, i + 1 - old_count, -1);
#ifdef USE_HCACHE
void *data = mutt_hcache_fetch(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
if (data)
{
char *uidl = mutt_str_strdup(ctx->hdrs[i]->data);
int refno = ctx->hdrs[i]->refno;
int index = ctx->hdrs[i]->index;
/*
* - POP dynamically numbers headers and relies on h->refno
* to map messages; so restore header and overwrite restored
* refno with current refno, same for index
* - h->data needs to a separate pointer as it's driver-specific
* data freed separately elsewhere
* (the old h->data should point inside a malloc'd block from
* hcache so there shouldn't be a memleak here)
*/
struct Header *h = mutt_hcache_restore((unsigned char *) data);
mutt_hcache_free(hc, &data);
mutt_header_free(&ctx->hdrs[i]);
ctx->hdrs[i] = h;
ctx->hdrs[i]->refno = refno;
ctx->hdrs[i]->index = index;
ctx->hdrs[i]->data = uidl;
ret = 0;
hcached = true;
}
else
#endif
if ((ret = pop_read_header(pop_data, ctx->hdrs[i])) < 0)
break;
#ifdef USE_HCACHE
else
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
/*
* faked support for flags works like this:
* - if 'hcached' is true, we have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: old
* (if $mark_old is set which is maybe wrong as
* $mark_old should be considered for syncing the
* folder and not when opening it XXX)
* - if 'hcached' is false, we don't have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: new
*/
const bool bcached =
(mutt_bcache_exists(pop_data->bcache, ctx->hdrs[i]->data) == 0);
ctx->hdrs[i]->old = false;
ctx->hdrs[i]->read = false;
if (hcached)
{
if (bcached)
ctx->hdrs[i]->read = true;
else if (MarkOld)
ctx->hdrs[i]->old = true;
}
else
{
if (bcached)
ctx->hdrs[i]->read = true;
}
ctx->msgcount++;
}
if (i > old_count)
mx_update_context(ctx, i - old_count);
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret < 0)
{
for (int i = ctx->msgcount; i < new_count; i++)
mutt_header_free(&ctx->hdrs[i]);
return ret;
}
/* after putting the result into our structures,
* clean up cache, i.e. wipe messages deleted outside
* the availability of our cache
*/
if (MessageCacheClean)
mutt_bcache_list(pop_data->bcache, msg_cache_check, (void *) ctx);
mutt_clear_error();
return (new_count - old_count);
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22 | static int pop_fetch_headers(struct Context *ctx)
{
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = pop_hcache_open(pop_data, ctx->path);
#endif
time(&pop_data->check_time);
pop_data->clear_cache = false;
for (int i = 0; i < ctx->msgcount; i++)
ctx->hdrs[i]->refno = -1;
const int old_count = ctx->msgcount;
int ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
const int new_count = ctx->msgcount;
ctx->msgcount = old_count;
if (pop_data->cmd_uidl == 2)
{
if (ret == 0)
{
pop_data->cmd_uidl = 1;
mutt_debug(1, "set UIDL capability\n");
}
if (ret == -2 && pop_data->cmd_uidl == 2)
{
pop_data->cmd_uidl = 0;
mutt_debug(1, "unset UIDL capability\n");
snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s",
_("Command UIDL is not supported by server."));
}
}
if (!ctx->quiet)
{
mutt_progress_init(&progress, _("Fetching message headers..."),
MUTT_PROGRESS_MSG, ReadInc, new_count - old_count);
}
if (ret == 0)
{
int i, deleted;
for (i = 0, deleted = 0; i < old_count; i++)
{
if (ctx->hdrs[i]->refno == -1)
{
ctx->hdrs[i]->deleted = true;
deleted++;
}
}
if (deleted > 0)
{
mutt_error(
ngettext("%d message has been lost. Try reopening the mailbox.",
"%d messages have been lost. Try reopening the mailbox.", deleted),
deleted);
}
bool hcached = false;
for (i = old_count; i < new_count; i++)
{
if (!ctx->quiet)
mutt_progress_update(&progress, i + 1 - old_count, -1);
#ifdef USE_HCACHE
void *data = mutt_hcache_fetch(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
if (data)
{
char *uidl = mutt_str_strdup(ctx->hdrs[i]->data);
int refno = ctx->hdrs[i]->refno;
int index = ctx->hdrs[i]->index;
/*
* - POP dynamically numbers headers and relies on h->refno
* to map messages; so restore header and overwrite restored
* refno with current refno, same for index
* - h->data needs to a separate pointer as it's driver-specific
* data freed separately elsewhere
* (the old h->data should point inside a malloc'd block from
* hcache so there shouldn't be a memleak here)
*/
struct Header *h = mutt_hcache_restore((unsigned char *) data);
mutt_hcache_free(hc, &data);
mutt_header_free(&ctx->hdrs[i]);
ctx->hdrs[i] = h;
ctx->hdrs[i]->refno = refno;
ctx->hdrs[i]->index = index;
ctx->hdrs[i]->data = uidl;
ret = 0;
hcached = true;
}
else
#endif
if ((ret = pop_read_header(pop_data, ctx->hdrs[i])) < 0)
break;
#ifdef USE_HCACHE
else
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
/*
* faked support for flags works like this:
* - if 'hcached' is true, we have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: old
* (if $mark_old is set which is maybe wrong as
* $mark_old should be considered for syncing the
* folder and not when opening it XXX)
* - if 'hcached' is false, we don't have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: new
*/
const bool bcached =
(mutt_bcache_exists(pop_data->bcache, cache_id(ctx->hdrs[i]->data)) == 0);
ctx->hdrs[i]->old = false;
ctx->hdrs[i]->read = false;
if (hcached)
{
if (bcached)
ctx->hdrs[i]->read = true;
else if (MarkOld)
ctx->hdrs[i]->old = true;
}
else
{
if (bcached)
ctx->hdrs[i]->read = true;
}
ctx->msgcount++;
}
if (i > old_count)
mx_update_context(ctx, i - old_count);
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret < 0)
{
for (int i = ctx->msgcount; i < new_count; i++)
mutt_header_free(&ctx->hdrs[i]);
return ret;
}
/* after putting the result into our structures,
* clean up cache, i.e. wipe messages deleted outside
* the availability of our cache
*/
if (MessageCacheClean)
mutt_bcache_list(pop_data->bcache, msg_cache_check, (void *) ctx);
mutt_clear_error();
return (new_count - old_count);
}
| 169,121 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Bug: 12394
Change-Id: Ifa023ce70f7a2697bf151009b035a6e6cf8d5d90
Reviewed-on: https://code.wireshark.org/review/15169
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
| 169,967 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ghash_update(struct shash_desc *desc,
const u8 *src, unsigned int srclen)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *dst = dctx->buffer;
if (dctx->bytes) {
int n = min(srclen, dctx->bytes);
u8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes);
dctx->bytes -= n;
srclen -= n;
while (n--)
*pos++ ^= *src++;
if (!dctx->bytes)
gf128mul_4k_lle((be128 *)dst, ctx->gf128);
}
while (srclen >= GHASH_BLOCK_SIZE) {
crypto_xor(dst, src, GHASH_BLOCK_SIZE);
gf128mul_4k_lle((be128 *)dst, ctx->gf128);
src += GHASH_BLOCK_SIZE;
srclen -= GHASH_BLOCK_SIZE;
}
if (srclen) {
dctx->bytes = GHASH_BLOCK_SIZE - srclen;
while (srclen--)
*dst++ ^= *src++;
}
return 0;
}
Commit Message: crypto: ghash - Avoid null pointer dereference if no key is set
The ghash_update function passes a pointer to gf128mul_4k_lle which will
be NULL if ghash_setkey is not called or if the most recent call to
ghash_setkey failed to allocate memory. This causes an oops. Fix this
up by returning an error code in the null case.
This is trivially triggered from unprivileged userspace through the
AF_ALG interface by simply writing to the socket without setting a key.
The ghash_final function has a similar issue, but triggering it requires
a memory allocation failure in ghash_setkey _after_ at least one
successful call to ghash_update.
BUG: unable to handle kernel NULL pointer dereference at 00000670
IP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul]
*pde = 00000000
Oops: 0000 [#1] PREEMPT SMP
Modules linked in: ghash_generic gf128mul algif_hash af_alg nfs lockd nfs_acl sunrpc bridge ipv6 stp llc
Pid: 1502, comm: hashatron Tainted: G W 3.1.0-rc9-00085-ge9308cf #32 Bochs Bochs
EIP: 0060:[<d88c92d4>] EFLAGS: 00000202 CPU: 0
EIP is at gf128mul_4k_lle+0x23/0x60 [gf128mul]
EAX: d69db1f0 EBX: d6b8ddac ECX: 00000004 EDX: 00000000
ESI: 00000670 EDI: d6b8ddac EBP: d6b8ddc8 ESP: d6b8dda4
DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
Process hashatron (pid: 1502, ti=d6b8c000 task=d6810000 task.ti=d6b8c000)
Stack:
00000000 d69db1f0 00000163 00000000 d6b8ddc8 c101a520 d69db1f0 d52aa000
00000ff0 d6b8dde8 d88d310f d6b8a3f8 d52aa000 00001000 d88d502c d6b8ddfc
00001000 d6b8ddf4 c11676ed d69db1e8 d6b8de24 c11679ad d52aa000 00000000
Call Trace:
[<c101a520>] ? kmap_atomic_prot+0x37/0xa6
[<d88d310f>] ghash_update+0x85/0xbe [ghash_generic]
[<c11676ed>] crypto_shash_update+0x18/0x1b
[<c11679ad>] shash_ahash_update+0x22/0x36
[<c11679cc>] shash_async_update+0xb/0xd
[<d88ce0ba>] hash_sendpage+0xba/0xf2 [algif_hash]
[<c121b24c>] kernel_sendpage+0x39/0x4e
[<d88ce000>] ? 0xd88cdfff
[<c121b298>] sock_sendpage+0x37/0x3e
[<c121b261>] ? kernel_sendpage+0x4e/0x4e
[<c10b4dbc>] pipe_to_sendpage+0x56/0x61
[<c10b4e1f>] splice_from_pipe_feed+0x58/0xcd
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b51f5>] __splice_from_pipe+0x36/0x55
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b6383>] splice_from_pipe+0x51/0x64
[<c10b63c2>] ? default_file_splice_write+0x2c/0x2c
[<c10b63d5>] generic_splice_sendpage+0x13/0x15
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b527f>] do_splice_from+0x5d/0x67
[<c10b6865>] sys_splice+0x2bf/0x363
[<c129373b>] ? sysenter_exit+0xf/0x16
[<c104dc1e>] ? trace_hardirqs_on_caller+0x10e/0x13f
[<c129370c>] sysenter_do_call+0x12/0x32
Code: 83 c4 0c 5b 5e 5f c9 c3 55 b9 04 00 00 00 89 e5 57 8d 7d e4 56 53 8d 5d e4 83 ec 18 89 45 e0 89 55 dc 0f b6 70 0f c1 e6 04 01 d6 <f3> a5 be 0f 00 00 00 4e 89 d8 e8 48 ff ff ff 8b 45 e0 89 da 0f
EIP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul] SS:ESP 0068:d6b8dda4
CR2: 0000000000000670
---[ end trace 4eaa2a86a8e2da24 ]---
note: hashatron[1502] exited with preempt_count 1
BUG: scheduling while atomic: hashatron/1502/0x10000002
INFO: lockdep is turned off.
[...]
Signed-off-by: Nick Bowler <[email protected]>
Cc: [email protected] [2.6.37+]
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int ghash_update(struct shash_desc *desc,
const u8 *src, unsigned int srclen)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *dst = dctx->buffer;
if (!ctx->gf128)
return -ENOKEY;
if (dctx->bytes) {
int n = min(srclen, dctx->bytes);
u8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes);
dctx->bytes -= n;
srclen -= n;
while (n--)
*pos++ ^= *src++;
if (!dctx->bytes)
gf128mul_4k_lle((be128 *)dst, ctx->gf128);
}
while (srclen >= GHASH_BLOCK_SIZE) {
crypto_xor(dst, src, GHASH_BLOCK_SIZE);
gf128mul_4k_lle((be128 *)dst, ctx->gf128);
src += GHASH_BLOCK_SIZE;
srclen -= GHASH_BLOCK_SIZE;
}
if (srclen) {
dctx->bytes = GHASH_BLOCK_SIZE - srclen;
while (srclen--)
*dst++ ^= *src++;
}
return 0;
}
| 165,743 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) {
DCHECK(is_preview_);
print_preview_context_.OnPrintPreview();
if (!InitPrintSettings(print_preview_context_.frame(),
print_preview_context_.node(),
true)) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(),
print_pages_params_->params.document_cookie));
return;
}
if (!UpdatePrintSettings(settings, true)) {
LOG(ERROR) << "UpdatePrintSettings failed";
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!print_pages_params_->params.is_first_request &&
old_print_pages_params_.get() &&
PrintMsg_Print_Params_IsEqual(*old_print_pages_params_,
*print_pages_params_)) {
PrintHostMsg_DidPreviewDocument_Params preview_params;
preview_params.reuse_existing_data = true;
preview_params.data_size = 0;
preview_params.document_cookie =
print_pages_params_->params.document_cookie;
preview_params.expected_pages_count =
print_preview_context_.total_page_count();
preview_params.modifiable = print_preview_context_.IsModifiable();
preview_params.preview_request_id =
print_pages_params_->params.preview_request_id;
Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(),
preview_params));
return;
}
old_print_pages_params_.reset();
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(printing::kSettingGenerateDraftData,
&generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
if (CreatePreviewDocument()) {
DidFinishPrinting(OK);
} else {
if (notify_browser_of_print_failure_)
LOG(ERROR) << "CreatePreviewDocument failed";
DidFinishPrinting(FAIL_PREVIEW);
}
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) {
DCHECK(is_preview_);
print_preview_context_.OnPrintPreview();
if (!UpdatePrintSettings(settings, true)) {
if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(), print_pages_params_->params.document_cookie));
notify_browser_of_print_failure_ = false; // Already sent.
}
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!print_pages_params_->params.is_first_request &&
old_print_pages_params_.get() &&
PrintMsg_Print_Params_IsEqual(*old_print_pages_params_,
*print_pages_params_)) {
PrintHostMsg_DidPreviewDocument_Params preview_params;
preview_params.reuse_existing_data = true;
preview_params.data_size = 0;
preview_params.document_cookie =
print_pages_params_->params.document_cookie;
preview_params.expected_pages_count =
print_preview_context_.total_page_count();
preview_params.modifiable = print_preview_context_.IsModifiable();
preview_params.preview_request_id =
print_pages_params_->params.preview_request_id;
Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(),
preview_params));
return;
}
old_print_pages_params_.reset();
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(printing::kSettingGenerateDraftData,
&generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
if (CreatePreviewDocument()) {
DidFinishPrinting(OK);
} else {
if (notify_browser_of_print_failure_)
LOG(ERROR) << "CreatePreviewDocument failed";
DidFinishPrinting(FAIL_PREVIEW);
}
}
| 170,262 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport int LocaleLowercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125 | MagickExport int LocaleLowercase(const int c)
{
if (c == EOF)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
| 170,235 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DoCanonicalizePathURL(const URLComponentSource<CHAR>& source,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
bool success = CanonicalizeScheme(source.scheme, parsed.scheme,
output, &new_parsed->scheme);
new_parsed->username.reset();
new_parsed->password.reset();
new_parsed->host.reset();
new_parsed->port.reset();
success &= DoCanonicalizePathComponent<CHAR, UCHAR>(
source.path, parsed.path, '\0', output, &new_parsed->path);
success &= DoCanonicalizePathComponent<CHAR, UCHAR>(
source.query, parsed.query, '?', output, &new_parsed->query);
success &= DoCanonicalizePathComponent<CHAR, UCHAR>(
source.ref, parsed.ref, '#', output, &new_parsed->ref);
return success;
}
Commit Message: [url] Make path URL parsing more lax
Parsing the path component of a non-special URL like javascript or data
should not fail for invalid URL characters like \uFFFF. See this bit
in the spec:
https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state
Note: some failing WPTs are added which are because url parsing
replaces invalid characters (e.g. \uFFFF) with the replacement char
\uFFFD, when that isn't in the spec.
Bug: 925614
Change-Id: I450495bfdfa68dc70334ebed16a3ecc0d5737e88
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1551917
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Charlie Harrison <[email protected]>
Cr-Commit-Position: refs/heads/master@{#648155}
CWE ID: CWE-20 | bool DoCanonicalizePathURL(const URLComponentSource<CHAR>& source,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
bool success = CanonicalizeScheme(source.scheme, parsed.scheme,
output, &new_parsed->scheme);
new_parsed->username.reset();
new_parsed->password.reset();
new_parsed->host.reset();
new_parsed->port.reset();
//
// Note: parsing the path part should never cause a failure, see
// https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state
DoCanonicalizePathComponent<CHAR, UCHAR>(source.path, parsed.path, '\0',
output, &new_parsed->path);
DoCanonicalizePathComponent<CHAR, UCHAR>(source.query, parsed.query, '?',
output, &new_parsed->query);
DoCanonicalizePathComponent<CHAR, UCHAR>(source.ref, parsed.ref, '#', output,
&new_parsed->ref);
return success;
}
| 173,012 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
sidx = sizeof (t_chunk_info) * nc;
cidx = gdCalloc (sidx, 1);
if (!cidx) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
Commit Message: gd2: handle corrupt images better (CVE-2016-3074)
Make sure we do some range checking on corrupted chunks.
Thanks to Hans Jerry Illikainen <[email protected]> for indepth report
and reproducer information. Made for easy test case writing :).
CWE ID: CWE-189 | _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
sidx = sizeof (t_chunk_info) * nc;
cidx = gdCalloc (sidx, 1);
if (!cidx) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
| 167,382 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
Commit Message: Ensure that not all tiles lie outside the image area.
CWE ID: CWE-20 | static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
| 168,737 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static inline int btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0));
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
| 173,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val)
{
int i;
int c;
for (i = n; i > 0; --i) {
c = (val >> (8 * (i - 1))) & 0xff;
if (jas_stream_putc(out, c) == EOF)
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 | static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val)
static int jas_iccputuint(jas_stream_t *out, int n, jas_ulonglong val)
{
int i;
int c;
for (i = n; i > 0; --i) {
c = (val >> (8 * (i - 1))) & 0xff;
if (jas_stream_putc(out, c) == EOF)
return -1;
}
return 0;
}
| 168,690 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.