instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
return sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
}
Commit Message: proc: restrict access to /proc/PID/io
/proc/PID/io may be used for gathering private information. E.g. for
openssh and vsftpd daemons wchars/rchars may be used to learn the
precise password length. Restrict it to processes being able to ptrace
the target process.
ptrace_may_access() is needed to prevent keeping open file descriptor of
"io" file, executing setuid binary and gathering io information of the
setuid'ed process.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int do_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
if (!ptrace_may_access(task, PTRACE_MODE_READ))
return -EACCES;
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
return sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
}
| 165,860 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
{
jas_matrix_t *y;
int i;
int j;
y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),
jas_seq2d_xend(x), jas_seq2d_yend(x));
assert(y);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
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 | jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
{
jas_matrix_t *y;
jas_matind_t i;
jas_matind_t j;
y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),
jas_seq2d_xend(x), jas_seq2d_yend(x));
assert(y);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
| 168,708 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bmexec_trans (kwset_t kwset, char const *text, size_t size)
{
unsigned char const *d1;
char const *ep, *sp, *tp;
int d;
int len = kwset->mind;
char const *trans = kwset->trans;
if (len == 0)
return 0;
if (len > size)
return -1;
if (len == 1)
{
tp = memchr_kwset (text, size, kwset);
return tp ? tp - text : -1;
}
d1 = kwset->delta;
sp = kwset->target + len;
tp = text + len;
char gc1 = kwset->gc1;
char gc2 = kwset->gc2;
/* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
if (size > 12 * len)
/* 11 is not a bug, the initial offset happens only once. */
for (ep = text + size - 11 * len; tp <= ep; )
{
char const *tp0 = tp;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
/* As a heuristic, prefer memchr to seeking by
delta1 when the latter doesn't advance much. */
int advance_heuristic = 16 * sizeof (long);
if (advance_heuristic <= tp - tp0)
goto big_advance;
tp--;
tp = memchr_kwset (tp, text + size - tp, kwset);
if (! tp)
return -1;
tp++;
}
}
}
big_advance:;
}
/* Now we have only a few characters left to search. We
carefully avoid ever producing an out-of-bounds pointer. */
ep = text + size;
d = d1[U(tp[-1])];
while (d <= ep - tp)
{
d = d1[U((tp += d)[-1])];
if (d != 0)
continue;
if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset))
return tp - text;
}
return -1;
}
Commit Message:
CWE ID: CWE-119 | bmexec_trans (kwset_t kwset, char const *text, size_t size)
{
unsigned char const *d1;
char const *ep, *sp, *tp;
int d;
int len = kwset->mind;
char const *trans = kwset->trans;
if (len == 0)
return 0;
if (len > size)
return -1;
if (len == 1)
{
tp = memchr_kwset (text, size, kwset);
return tp ? tp - text : -1;
}
d1 = kwset->delta;
sp = kwset->target + len;
tp = text + len;
char gc1 = kwset->gc1;
char gc2 = kwset->gc2;
/* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
if (size > 12 * len)
/* 11 is not a bug, the initial offset happens only once. */
for (ep = text + size - 11 * len; tp <= ep; )
{
char const *tp0 = tp;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
/* As a heuristic, prefer memchr to seeking by
delta1 when the latter doesn't advance much. */
int advance_heuristic = 16 * sizeof (long);
if (advance_heuristic <= tp - tp0)
goto big_advance;
tp--;
tp = memchr_kwset (tp, text + size - tp, kwset);
if (! tp)
return -1;
tp++;
if (ep <= tp)
break;
}
}
}
big_advance:;
}
/* Now we have only a few characters left to search. We
carefully avoid ever producing an out-of-bounds pointer. */
ep = text + size;
d = d1[U(tp[-1])];
while (d <= ep - tp)
{
d = d1[U((tp += d)[-1])];
if (d != 0)
continue;
if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset))
return tp - text;
}
return -1;
}
| 164,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint64_t offset;
zip_uint8_t eocd[EOCD64LEN];
zip_uint64_t eocd_offset;
zip_uint64_t size, nentry, i, eocdloc_offset;
bool free_buffer;
zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64;
eocdloc_offset = _zip_buffer_offset(buffer);
_zip_buffer_get(buffer, 4); /* magic already verified */
num_disks = _zip_buffer_get_16(buffer);
eocd_disk = _zip_buffer_get_16(buffer);
eocd_offset = _zip_buffer_get_64(buffer);
if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) {
_zip_buffer_set_offset(buffer, eocd_offset - buf_offset);
free_buffer = false;
}
else {
if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) {
return NULL;
}
free_buffer = true;
}
if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
_zip_buffer_get(buffer, 4); /* skip version made by/needed */
num_disks64 = _zip_buffer_get_32(buffer);
eocd_disk64 = _zip_buffer_get_32(buffer);
/* if eocd values are 0xffff, we have to use eocd64 values.
otherwise, if the values are not the same, it's inconsistent;
in any case, if the value is not 0, we don't support it */
if (num_disks == 0xffff) {
num_disks = num_disks64;
}
if (eocd_disk == 0xffff) {
eocd_disk = eocd_disk64;
}
if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (num_disks != 0 || eocd_disk != 0) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
nentry = _zip_buffer_get_64(buffer);
i = _zip_buffer_get_64(buffer);
if (nentry != i) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
offset = _zip_buffer_get_64(buffer);
if (!_zip_buffer_ok(buffer)) {
zip_error_set(error, ZIP_ER_INTERNAL, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (free_buffer) {
_zip_buffer_free(buffer);
}
if (offset > ZIP_INT64_MAX || offset+size < offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if ((flags & ZIP_CHECKCONS) && offset+size != eocd_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((cd=_zip_cdir_new(nentry, error)) == NULL)
return NULL;
cd->is_zip64 = true;
cd->size = size;
cd->offset = offset;
return cd;
}
Commit Message: Make eocd checks more consistent between zip and zip64 cases.
CWE ID: CWE-119 | _zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint64_t offset;
zip_uint8_t eocd[EOCD64LEN];
zip_uint64_t eocd_offset;
zip_uint64_t size, nentry, i, eocdloc_offset;
bool free_buffer;
zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64;
eocdloc_offset = _zip_buffer_offset(buffer);
_zip_buffer_get(buffer, 4); /* magic already verified */
num_disks = _zip_buffer_get_16(buffer);
eocd_disk = _zip_buffer_get_16(buffer);
eocd_offset = _zip_buffer_get_64(buffer);
if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) {
_zip_buffer_set_offset(buffer, eocd_offset - buf_offset);
free_buffer = false;
}
else {
if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) {
return NULL;
}
free_buffer = true;
}
if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
_zip_buffer_get(buffer, 4); /* skip version made by/needed */
num_disks64 = _zip_buffer_get_32(buffer);
eocd_disk64 = _zip_buffer_get_32(buffer);
/* if eocd values are 0xffff, we have to use eocd64 values.
otherwise, if the values are not the same, it's inconsistent;
in any case, if the value is not 0, we don't support it */
if (num_disks == 0xffff) {
num_disks = num_disks64;
}
if (eocd_disk == 0xffff) {
eocd_disk = eocd_disk64;
}
if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (num_disks != 0 || eocd_disk != 0) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
nentry = _zip_buffer_get_64(buffer);
i = _zip_buffer_get_64(buffer);
if (nentry != i) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
offset = _zip_buffer_get_64(buffer);
if (!_zip_buffer_ok(buffer)) {
zip_error_set(error, ZIP_ER_INTERNAL, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (free_buffer) {
_zip_buffer_free(buffer);
}
if (offset > ZIP_INT64_MAX || offset+size < offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (offset+size > buf_offset + eocd_offset) {
/* cdir spans past EOCD record */
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((flags & ZIP_CHECKCONS) && offset+size != buf_offset + eocd_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((cd=_zip_cdir_new(nentry, error)) == NULL)
return NULL;
cd->is_zip64 = true;
cd->size = size;
cd->offset = offset;
return cd;
}
| 167,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector)
: next_dump_id_(0),
client_process_timeout_(base::TimeDelta::FromSeconds(15)) {
process_map_ = std::make_unique<ProcessMap>(connector);
DCHECK(!g_coordinator_impl);
g_coordinator_impl = this;
base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id(
mojom::kServiceTracingProcessId);
tracing_observer_ = std::make_unique<TracingObserver>(
base::trace_event::TraceLog::GetInstance(), nullptr);
}
Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained
Bug: 856578
Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9
Reviewed-on: https://chromium-review.googlesource.com/1114617
Reviewed-by: Hector Dearman <[email protected]>
Commit-Queue: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#571528}
CWE ID: CWE-416 | CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector)
: next_dump_id_(0),
client_process_timeout_(base::TimeDelta::FromSeconds(15)),
weak_ptr_factory_(this) {
process_map_ = std::make_unique<ProcessMap>(connector);
DCHECK(!g_coordinator_impl);
g_coordinator_impl = this;
base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id(
mojom::kServiceTracingProcessId);
tracing_observer_ = std::make_unique<TracingObserver>(
base::trace_event::TraceLog::GetInstance(), nullptr);
}
| 173,211 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void vrend_renderer_context_create_internal(uint32_t handle, uint32_t nlen,
const char *debug_name)
{
struct vrend_decode_ctx *dctx;
if (handle >= VREND_MAX_CTX)
return;
dctx = malloc(sizeof(struct vrend_decode_ctx));
if (!dctx)
return;
return;
}
Commit Message:
CWE ID: CWE-399 | void vrend_renderer_context_create_internal(uint32_t handle, uint32_t nlen,
const char *debug_name)
{
struct vrend_decode_ctx *dctx;
if (handle >= VREND_MAX_CTX)
return;
dctx = dec_ctx[handle];
if (dctx)
return;
dctx = malloc(sizeof(struct vrend_decode_ctx));
if (!dctx)
return;
return;
}
| 165,239 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DefragReverseSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
if (IPV4_GET_HLEN(reassembled) != 20)
goto end;
if (IPV4_GET_IPLEN(reassembled) != 39)
goto end;
/* 20 bytes in we should find 8 bytes of A. */
for (i = 20; i < 20 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 28; i < 28 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 36; i < 36 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragReverseSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p3, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p1, NULL);
if (reassembled == NULL)
goto end;
if (IPV4_GET_HLEN(reassembled) != 20)
goto end;
if (IPV4_GET_IPLEN(reassembled) != 39)
goto end;
/* 20 bytes in we should find 8 bytes of A. */
for (i = 20; i < 20 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 28; i < 28 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 36; i < 36 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
| 168,302 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!iter->ReadData(&fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!iter->ReadData(&variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125 | bool ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
SkImageInfo image_info;
if (!ReadParam(m, iter, &image_info))
return false;
const char* bitmap_data;
int bitmap_data_size = 0;
if (!iter->ReadData(&bitmap_data, &bitmap_data_size))
return false;
// ReadData() only returns true if bitmap_data_size >= 0.
if (!r->tryAllocPixels(image_info))
return false;
if (static_cast<size_t>(bitmap_data_size) != r->computeByteSize())
return false;
memcpy(r->getPixels(), bitmap_data, bitmap_data_size);
return true;
}
| 172,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: T42_Open_Face( T42_Face face )
{
T42_LoaderRec loader;
T42_Parser parser;
T1_Font type1 = &face->type1;
FT_Memory memory = face->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
t42_loader_init( &loader, face );
parser = &loader.parser;
if ( FT_ALLOC( face->ttf_data, 12 ) )
goto Exit;
error = t42_parser_init( parser,
face->root.stream,
memory,
if ( error )
goto Exit;
if ( type1->font_type != 42 )
{
FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n",
type1->font_type ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* now, propagate the charstrings and glyphnames tables */
/* to the Type1 data */
type1->num_glyphs = loader.num_glyphs;
if ( !loader.charstrings.init )
{
FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" ));
error = FT_THROW( Invalid_File_Format );
}
loader.charstrings.init = 0;
type1->charstrings_block = loader.charstrings.block;
type1->charstrings = loader.charstrings.elements;
type1->charstrings_len = loader.charstrings.lengths;
/* we copy the glyph names `block' and `elements' fields; */
/* the `lengths' field must be released later */
type1->glyph_names_block = loader.glyph_names.block;
type1->glyph_names = (FT_String**)loader.glyph_names.elements;
loader.glyph_names.block = 0;
loader.glyph_names.elements = 0;
/* we must now build type1.encoding when we have a custom array */
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY )
{
FT_Int charcode, idx, min_char, max_char;
FT_Byte* glyph_name;
/* OK, we do the following: for each element in the encoding */
/* table, look up the index of the glyph having the same name */
/* as defined in the CharStrings array. */
/* The index is then stored in type1.encoding.char_index, and */
/* the name in type1.encoding.char_name */
min_char = 0;
max_char = 0;
charcode = 0;
for ( ; charcode < loader.encoding_table.max_elems; charcode++ )
{
FT_Byte* char_name;
type1->encoding.char_index[charcode] = 0;
type1->encoding.char_name [charcode] = (char *)".notdef";
char_name = loader.encoding_table.elements[charcode];
if ( char_name )
for ( idx = 0; idx < type1->num_glyphs; idx++ )
{
glyph_name = (FT_Byte*)type1->glyph_names[idx];
if ( ft_strcmp( (const char*)char_name,
(const char*)glyph_name ) == 0 )
{
type1->encoding.char_index[charcode] = (FT_UShort)idx;
type1->encoding.char_name [charcode] = (char*)glyph_name;
/* Change min/max encoded char only if glyph name is */
/* not /.notdef */
if ( ft_strcmp( (const char*)".notdef",
(const char*)glyph_name ) != 0 )
{
if ( charcode < min_char )
min_char = charcode;
if ( charcode >= max_char )
max_char = charcode + 1;
}
break;
}
}
}
type1->encoding.code_first = min_char;
type1->encoding.code_last = max_char;
type1->encoding.num_chars = loader.num_chars;
}
Exit:
t42_loader_done( &loader );
return error;
}
Commit Message:
CWE ID: | T42_Open_Face( T42_Face face )
{
T42_LoaderRec loader;
T42_Parser parser;
T1_Font type1 = &face->type1;
FT_Memory memory = face->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
t42_loader_init( &loader, face );
parser = &loader.parser;
if ( FT_ALLOC( face->ttf_data, 12 ) )
goto Exit;
/* while parsing the font we always update `face->ttf_size' so that */
/* even in case of buggy data (which might lead to premature end of */
/* scanning without causing an error) the call to `FT_Open_Face' in */
/* `T42_Face_Init' passes the correct size */
face->ttf_size = 12;
error = t42_parser_init( parser,
face->root.stream,
memory,
if ( error )
goto Exit;
if ( type1->font_type != 42 )
{
FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n",
type1->font_type ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* now, propagate the charstrings and glyphnames tables */
/* to the Type1 data */
type1->num_glyphs = loader.num_glyphs;
if ( !loader.charstrings.init )
{
FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" ));
error = FT_THROW( Invalid_File_Format );
}
loader.charstrings.init = 0;
type1->charstrings_block = loader.charstrings.block;
type1->charstrings = loader.charstrings.elements;
type1->charstrings_len = loader.charstrings.lengths;
/* we copy the glyph names `block' and `elements' fields; */
/* the `lengths' field must be released later */
type1->glyph_names_block = loader.glyph_names.block;
type1->glyph_names = (FT_String**)loader.glyph_names.elements;
loader.glyph_names.block = 0;
loader.glyph_names.elements = 0;
/* we must now build type1.encoding when we have a custom array */
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY )
{
FT_Int charcode, idx, min_char, max_char;
FT_Byte* glyph_name;
/* OK, we do the following: for each element in the encoding */
/* table, look up the index of the glyph having the same name */
/* as defined in the CharStrings array. */
/* The index is then stored in type1.encoding.char_index, and */
/* the name in type1.encoding.char_name */
min_char = 0;
max_char = 0;
charcode = 0;
for ( ; charcode < loader.encoding_table.max_elems; charcode++ )
{
FT_Byte* char_name;
type1->encoding.char_index[charcode] = 0;
type1->encoding.char_name [charcode] = (char *)".notdef";
char_name = loader.encoding_table.elements[charcode];
if ( char_name )
for ( idx = 0; idx < type1->num_glyphs; idx++ )
{
glyph_name = (FT_Byte*)type1->glyph_names[idx];
if ( ft_strcmp( (const char*)char_name,
(const char*)glyph_name ) == 0 )
{
type1->encoding.char_index[charcode] = (FT_UShort)idx;
type1->encoding.char_name [charcode] = (char*)glyph_name;
/* Change min/max encoded char only if glyph name is */
/* not /.notdef */
if ( ft_strcmp( (const char*)".notdef",
(const char*)glyph_name ) != 0 )
{
if ( charcode < min_char )
min_char = charcode;
if ( charcode >= max_char )
max_char = charcode + 1;
}
break;
}
}
}
type1->encoding.code_first = min_char;
type1->encoding.code_last = max_char;
type1->encoding.num_chars = loader.num_chars;
}
Exit:
t42_loader_done( &loader );
return error;
}
| 164,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int SafeSock::handle_incoming_packet()
{
/* SOCKET_ALTERNATE_LENGTH_TYPE is void on this platform, and
since noone knows what that void* is supposed to point to
in recvfrom, I'm going to predict the "fromlen" variable
the recvfrom uses is a size_t sized quantity since
size_t is how you count bytes right? Stupid Solaris. */
bool last;
int seqNo, length;
_condorMsgID mID;
void* data;
int index;
int received;
_condorInMsg *tempMsg, *delMsg, *prev = NULL;
time_t curTime;
if( _msgReady ) {
char const *existing_msg_type;
bool existing_consumed;
if( _longMsg ) {
existing_msg_type = "long";
existing_consumed = _longMsg->consumed();
}
else {
existing_msg_type = "short";
existing_consumed = _shortMsg.consumed();
}
dprintf( D_ALWAYS,
"ERROR: receiving new UDP message but found a %s "
"message still waiting to be closed (consumed=%d). "
"Closing it now.\n",
existing_msg_type, existing_consumed );
stream_coding saved_coding = _coding;
_coding = stream_decode;
end_of_message();
_coding = saved_coding;
}
received = condor_recvfrom(_sock, _shortMsg.dataGram,
SAFE_MSG_MAX_PACKET_SIZE, 0, _who);
if(received < 0) {
dprintf(D_NETWORK, "recvfrom failed: errno = %d\n", errno);
return FALSE;
}
char str[50];
sprintf(str, sock_to_string(_sock));
dprintf( D_NETWORK, "RECV %d bytes at %s from %s\n",
received, str, _who.to_sinful().Value());
length = received;
_shortMsg.reset(); // To be sure
bool is_full_message = _shortMsg.getHeader(received, last, seqNo, length, mID, data);
if ( length <= 0 || length > SAFE_MSG_MAX_PACKET_SIZE ) {
dprintf(D_ALWAYS,"IO: Incoming datagram improperly sized\n");
return FALSE;
}
if ( is_full_message ) {
_shortMsg.curIndex = 0;
_msgReady = true;
_whole++;
if(_whole == 1)
_avgSwhole = length;
else
_avgSwhole = ((_whole - 1) * _avgSwhole + length) / _whole;
_noMsgs++;
dprintf( D_NETWORK, "\tFull msg [%d bytes]\n", length);
return TRUE;
}
dprintf( D_NETWORK, "\tFrag [%d bytes]\n", length);
/* long message */
curTime = (unsigned long)time(NULL);
index = labs(mID.ip_addr + mID.time + mID.msgNo) % SAFE_SOCK_HASH_BUCKET_SIZE;
tempMsg = _inMsgs[index];
while(tempMsg != NULL && !same(tempMsg->msgID, mID)) {
prev = tempMsg;
tempMsg = tempMsg->nextMsg;
if(curTime - prev->lastTime > _tOutBtwPkts) {
dprintf(D_NETWORK, "found timed out msg: cur=%lu, msg=%lu\n",
curTime, prev->lastTime);
delMsg = prev;
prev = delMsg->prevMsg;
if(prev)
prev->nextMsg = delMsg->nextMsg;
else // delMsg is the 1st message in the chain
_inMsgs[index] = tempMsg;
if(tempMsg)
tempMsg->prevMsg = prev;
_deleted++;
if(_deleted == 1)
_avgSdeleted = delMsg->msgLen;
else {
_avgSdeleted = ((_deleted - 1) * _avgSdeleted + delMsg->msgLen) / _deleted;
}
dprintf(D_NETWORK, "Deleting timeouted message:\n");
delMsg->dumpMsg();
delete delMsg;
}
}
if(tempMsg != NULL) { // found
if (seqNo == 0) {
tempMsg->set_sec(_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted());
}
bool rst = tempMsg->addPacket(last, seqNo, length, data);
if (rst) {
_longMsg = tempMsg;
_msgReady = true;
_whole++;
if(_whole == 1)
_avgSwhole = _longMsg->msgLen;
else
_avgSwhole = ((_whole - 1) * _avgSwhole + _longMsg->msgLen) / _whole;
return TRUE;
}
return FALSE;
} else { // not found
if(prev) { // add a new message at the end of the chain
prev->nextMsg = new _condorInMsg(mID, last, seqNo, length, data,
_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted(), prev);
if(!prev->nextMsg) {
EXCEPT("Error:handle_incomming_packet: Out of Memory");
}
} else { // first message in the bucket
_inMsgs[index] = new _condorInMsg(mID, last, seqNo, length, data,
_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted(), NULL);
if(!_inMsgs[index]) {
EXCEPT("Error:handle_incomming_packet: Out of Memory");
}
}
_noMsgs++;
return FALSE;
}
}
Commit Message:
CWE ID: CWE-134 | int SafeSock::handle_incoming_packet()
{
/* SOCKET_ALTERNATE_LENGTH_TYPE is void on this platform, and
since noone knows what that void* is supposed to point to
in recvfrom, I'm going to predict the "fromlen" variable
the recvfrom uses is a size_t sized quantity since
size_t is how you count bytes right? Stupid Solaris. */
bool last;
int seqNo, length;
_condorMsgID mID;
void* data;
int index;
int received;
_condorInMsg *tempMsg, *delMsg, *prev = NULL;
time_t curTime;
if( _msgReady ) {
char const *existing_msg_type;
bool existing_consumed;
if( _longMsg ) {
existing_msg_type = "long";
existing_consumed = _longMsg->consumed();
}
else {
existing_msg_type = "short";
existing_consumed = _shortMsg.consumed();
}
dprintf( D_ALWAYS,
"ERROR: receiving new UDP message but found a %s "
"message still waiting to be closed (consumed=%d). "
"Closing it now.\n",
existing_msg_type, existing_consumed );
stream_coding saved_coding = _coding;
_coding = stream_decode;
end_of_message();
_coding = saved_coding;
}
received = condor_recvfrom(_sock, _shortMsg.dataGram,
SAFE_MSG_MAX_PACKET_SIZE, 0, _who);
if(received < 0) {
dprintf(D_NETWORK, "recvfrom failed: errno = %d\n", errno);
return FALSE;
}
char str[50];
sprintf(str, "%s", sock_to_string(_sock));
dprintf( D_NETWORK, "RECV %d bytes at %s from %s\n",
received, str, _who.to_sinful().Value());
length = received;
_shortMsg.reset(); // To be sure
bool is_full_message = _shortMsg.getHeader(received, last, seqNo, length, mID, data);
if ( length <= 0 || length > SAFE_MSG_MAX_PACKET_SIZE ) {
dprintf(D_ALWAYS,"IO: Incoming datagram improperly sized\n");
return FALSE;
}
if ( is_full_message ) {
_shortMsg.curIndex = 0;
_msgReady = true;
_whole++;
if(_whole == 1)
_avgSwhole = length;
else
_avgSwhole = ((_whole - 1) * _avgSwhole + length) / _whole;
_noMsgs++;
dprintf( D_NETWORK, "\tFull msg [%d bytes]\n", length);
return TRUE;
}
dprintf( D_NETWORK, "\tFrag [%d bytes]\n", length);
/* long message */
curTime = (unsigned long)time(NULL);
index = labs(mID.ip_addr + mID.time + mID.msgNo) % SAFE_SOCK_HASH_BUCKET_SIZE;
tempMsg = _inMsgs[index];
while(tempMsg != NULL && !same(tempMsg->msgID, mID)) {
prev = tempMsg;
tempMsg = tempMsg->nextMsg;
if(curTime - prev->lastTime > _tOutBtwPkts) {
dprintf(D_NETWORK, "found timed out msg: cur=%lu, msg=%lu\n",
curTime, prev->lastTime);
delMsg = prev;
prev = delMsg->prevMsg;
if(prev)
prev->nextMsg = delMsg->nextMsg;
else // delMsg is the 1st message in the chain
_inMsgs[index] = tempMsg;
if(tempMsg)
tempMsg->prevMsg = prev;
_deleted++;
if(_deleted == 1)
_avgSdeleted = delMsg->msgLen;
else {
_avgSdeleted = ((_deleted - 1) * _avgSdeleted + delMsg->msgLen) / _deleted;
}
dprintf(D_NETWORK, "Deleting timeouted message:\n");
delMsg->dumpMsg();
delete delMsg;
}
}
if(tempMsg != NULL) { // found
if (seqNo == 0) {
tempMsg->set_sec(_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted());
}
bool rst = tempMsg->addPacket(last, seqNo, length, data);
if (rst) {
_longMsg = tempMsg;
_msgReady = true;
_whole++;
if(_whole == 1)
_avgSwhole = _longMsg->msgLen;
else
_avgSwhole = ((_whole - 1) * _avgSwhole + _longMsg->msgLen) / _whole;
return TRUE;
}
return FALSE;
} else { // not found
if(prev) { // add a new message at the end of the chain
prev->nextMsg = new _condorInMsg(mID, last, seqNo, length, data,
_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted(), prev);
if(!prev->nextMsg) {
EXCEPT("Error:handle_incomming_packet: Out of Memory");
}
} else { // first message in the bucket
_inMsgs[index] = new _condorInMsg(mID, last, seqNo, length, data,
_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted(), NULL);
if(!_inMsgs[index]) {
EXCEPT("Error:handle_incomming_packet: Out of Memory");
}
}
_noMsgs++;
return FALSE;
}
}
| 165,374 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vnc_hextile_send_framebuffer_update(VncState *vs, int x,
int y, int w, int h)
{
int i, j;
int has_fg, has_bg;
uint8_t *last_fg, *last_bg;
VncDisplay *vd = vs->vd;
last_fg = (uint8_t *) g_malloc(vd->server->pf.bytes_per_pixel);
last_bg = (uint8_t *) g_malloc(vd->server->pf.bytes_per_pixel);
has_fg = has_bg = 0;
for (j = y; j < (y + h); j += 16) {
for (i = x; i < (x + w); i += 16) {
for (i = x; i < (x + w); i += 16) {
vs->hextile.send_tile(vs, i, j,
MIN(16, x + w - i), MIN(16, y + h - j),
last_bg, last_fg, &has_bg, &has_fg);
}
}
g_free(last_fg);
g_free(last_bg);
return 1;
}
void vnc_hextile_set_pixel_conversion(VncState *vs, int generic)
{
if (!generic) {
switch (vs->ds->surface->pf.bits_per_pixel) {
case 8:
vs->hextile.send_tile = send_hextile_tile_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_32;
break;
}
} else {
switch (vs->ds->surface->pf.bits_per_pixel) {
case 8:
vs->hextile.send_tile = send_hextile_tile_generic_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_generic_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_generic_32;
break;
}
}
}
}
Commit Message:
CWE ID: CWE-125 | int vnc_hextile_send_framebuffer_update(VncState *vs, int x,
int y, int w, int h)
{
int i, j;
int has_fg, has_bg;
uint8_t *last_fg, *last_bg;
last_fg = (uint8_t *) g_malloc(VNC_SERVER_FB_BYTES);
last_bg = (uint8_t *) g_malloc(VNC_SERVER_FB_BYTES);
has_fg = has_bg = 0;
for (j = y; j < (y + h); j += 16) {
for (i = x; i < (x + w); i += 16) {
for (i = x; i < (x + w); i += 16) {
vs->hextile.send_tile(vs, i, j,
MIN(16, x + w - i), MIN(16, y + h - j),
last_bg, last_fg, &has_bg, &has_fg);
}
}
g_free(last_fg);
g_free(last_bg);
return 1;
}
void vnc_hextile_set_pixel_conversion(VncState *vs, int generic)
{
if (!generic) {
switch (VNC_SERVER_FB_BITS) {
case 8:
vs->hextile.send_tile = send_hextile_tile_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_32;
break;
}
} else {
switch (VNC_SERVER_FB_BITS) {
case 8:
vs->hextile.send_tile = send_hextile_tile_generic_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_generic_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_generic_32;
break;
}
}
}
}
| 165,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p,
uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto)
{
switch (proto) {
case DECODE_TUNNEL_PPP:
return DecodePPP(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_IPV4:
return DecodeIPV4(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_IPV6:
return DecodeIPV6(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_VLAN:
return DecodeVLAN(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_ETHERNET:
return DecodeEthernet(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_ERSPAN:
return DecodeERSPAN(tv, dtv, p, pkt, len, pq);
default:
SCLogInfo("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto);
break;
}
return TM_ECODE_OK;
}
Commit Message: teredo: be stricter on what to consider valid teredo
Invalid Teredo can lead to valid DNS traffic (or other UDP traffic)
being misdetected as Teredo. This leads to false negatives in the
UDP payload inspection.
Make the teredo code only consider a packet teredo if the encapsulated
data was decoded without any 'invalid' events being set.
Bug #2736.
CWE ID: CWE-20 | int DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p,
uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto)
{
switch (proto) {
case DECODE_TUNNEL_PPP:
return DecodePPP(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_IPV4:
return DecodeIPV4(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_IPV6:
case DECODE_TUNNEL_IPV6_TEREDO:
return DecodeIPV6(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_VLAN:
return DecodeVLAN(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_ETHERNET:
return DecodeEthernet(tv, dtv, p, pkt, len, pq);
case DECODE_TUNNEL_ERSPAN:
return DecodeERSPAN(tv, dtv, p, pkt, len, pq);
default:
SCLogDebug("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto);
break;
}
return TM_ECODE_OK;
}
| 169,478 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState)
{
if (options.hasVibrate() && options.silent()) {
exceptionState.throwTypeError("Silent notifications must not specify vibration patterns.");
return WebNotificationData();
}
WebNotificationData webData;
webData.title = title;
webData.direction = toDirectionEnumValue(options.dir());
webData.lang = options.lang();
webData.body = options.body();
webData.tag = options.tag();
KURL iconUrl;
iconUrl = executionContext->completeURL(options.icon());
if (!iconUrl.isValid())
iconUrl = KURL();
}
webData.icon = iconUrl;
webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate());
webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS();
webData.silent = options.silent();
webData.requireInteraction = options.requireInteraction();
if (options.hasData()) {
RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState);
if (exceptionState.hadException())
return WebNotificationData();
Vector<char> serializedData;
serializedScriptValue->toWireBytes(serializedData);
webData.data = serializedData;
}
Vector<WebNotificationAction> actions;
const size_t maxActions = Notification::maxActions();
for (const NotificationAction& action : options.actions()) {
if (actions.size() >= maxActions)
break;
WebNotificationAction webAction;
webAction.action = action.action();
webAction.title = action.title();
actions.append(webAction);
}
webData.actions = actions;
return webData;
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID: | WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState)
{
if (options.hasVibrate() && options.silent()) {
exceptionState.throwTypeError("Silent notifications must not specify vibration patterns.");
return WebNotificationData();
}
WebNotificationData webData;
webData.title = title;
webData.direction = toDirectionEnumValue(options.dir());
webData.lang = options.lang();
webData.body = options.body();
webData.tag = options.tag();
KURL iconUrl;
iconUrl = executionContext->completeURL(options.icon());
if (!iconUrl.isValid())
iconUrl = KURL();
}
webData.icon = iconUrl;
webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate());
webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS();
webData.silent = options.silent();
webData.requireInteraction = options.requireInteraction();
if (options.hasData()) {
RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState);
if (exceptionState.hadException())
return WebNotificationData();
Vector<char> serializedData;
serializedScriptValue->toWireBytes(serializedData);
webData.data = serializedData;
}
Vector<WebNotificationAction> actions;
const size_t maxActions = Notification::maxActions();
for (const NotificationAction& action : options.actions()) {
if (actions.size() >= maxActions)
break;
WebNotificationAction webAction;
webAction.action = action.action();
webAction.title = action.title();
KURL iconUrl;
if (action.hasIcon() && !action.icon().isEmpty()) {
iconUrl = executionContext->completeURL(action.icon());
if (!iconUrl.isValid())
iconUrl = KURL();
}
webAction.icon = iconUrl;
actions.append(webAction);
}
webData.actions = actions;
return webData;
}
| 171,634 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
Commit Message: Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108).
CWE ID: CWE-125 | static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
| 168,796 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
| 167,794 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
struct super_block *sb;
int err;
int rc;
if (!ext4_handle_valid(handle)) {
ext4_put_nojournal(handle);
return 0;
}
if (!handle->h_transaction) {
err = jbd2_journal_stop(handle);
return handle->h_err ? handle->h_err : err;
}
sb = handle->h_transaction->t_journal->j_private;
err = handle->h_err;
rc = jbd2_journal_stop(handle);
if (!err)
err = rc;
if (err)
__ext4_std_error(sb, where, line, err);
return err;
}
Commit Message: ext4: fix potential use after free in __ext4_journal_stop
There is a use-after-free possibility in __ext4_journal_stop() in the
case that we free the handle in the first jbd2_journal_stop() because
we're referencing handle->h_err afterwards. This was introduced in
9705acd63b125dee8b15c705216d7186daea4625 and it is wrong. Fix it by
storing the handle->h_err value beforehand and avoid referencing
potentially freed handle.
Fixes: 9705acd63b125dee8b15c705216d7186daea4625
Signed-off-by: Lukas Czerner <[email protected]>
Reviewed-by: Andreas Dilger <[email protected]>
Cc: [email protected]
CWE ID: CWE-416 | int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
struct super_block *sb;
int err;
int rc;
if (!ext4_handle_valid(handle)) {
ext4_put_nojournal(handle);
return 0;
}
err = handle->h_err;
if (!handle->h_transaction) {
rc = jbd2_journal_stop(handle);
return err ? err : rc;
}
sb = handle->h_transaction->t_journal->j_private;
rc = jbd2_journal_stop(handle);
if (!err)
err = rc;
if (err)
__ext4_std_error(sb, where, line, err);
return err;
}
| 167,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
| 173,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data)
{
struct l2cap_conf_req *req = (struct l2cap_conf_req *) data;
u16 dcid, flags;
u8 rsp[64];
struct sock *sk;
int len;
dcid = __le16_to_cpu(req->dcid);
flags = __le16_to_cpu(req->flags);
BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags);
sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid);
if (!sk)
return -ENOENT;
if (sk->sk_state == BT_DISCONN)
goto unlock;
/* Reject if config buffer is too small. */
len = cmd_len - sizeof(*req);
if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) {
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_REJECT, flags), rsp);
goto unlock;
}
/* Store config. */
memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len);
l2cap_pi(sk)->conf_len += len;
if (flags & 0x0001) {
/* Incomplete config. Send empty response. */
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_SUCCESS, 0x0001), rsp);
goto unlock;
}
/* Complete config. */
len = l2cap_parse_conf_req(sk, rsp);
if (len < 0)
goto unlock;
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);
/* Reset config buffer. */
l2cap_pi(sk)->conf_len = 0;
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE))
goto unlock;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
goto unlock;
}
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) {
u8 buf[64];
l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
l2cap_build_conf_req(sk, buf), buf);
}
unlock:
bh_unlock_sock(sk);
return 0;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data)
{
struct l2cap_conf_req *req = (struct l2cap_conf_req *) data;
u16 dcid, flags;
u8 rsp[64];
struct sock *sk;
int len;
dcid = __le16_to_cpu(req->dcid);
flags = __le16_to_cpu(req->flags);
BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags);
sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid);
if (!sk)
return -ENOENT;
if (sk->sk_state == BT_DISCONN)
goto unlock;
/* Reject if config buffer is too small. */
len = cmd_len - sizeof(*req);
if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) {
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_REJECT, flags), rsp);
goto unlock;
}
/* Store config. */
memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len);
l2cap_pi(sk)->conf_len += len;
if (flags & 0x0001) {
/* Incomplete config. Send empty response. */
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_SUCCESS, 0x0001), rsp);
goto unlock;
}
/* Complete config. */
len = l2cap_parse_conf_req(sk, rsp);
if (len < 0) {
struct l2cap_disconn_req req;
req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);
req.scid = cpu_to_le16(l2cap_pi(sk)->scid);
l2cap_send_cmd(conn, l2cap_get_ident(conn),
L2CAP_DISCONN_REQ, sizeof(req), &req);
goto unlock;
}
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);
l2cap_pi(sk)->num_conf_rsp++;
/* Reset config buffer. */
l2cap_pi(sk)->conf_len = 0;
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE))
goto unlock;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
goto unlock;
}
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) {
u8 buf[64];
l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
l2cap_build_conf_req(sk, buf), buf);
l2cap_pi(sk)->num_conf_req++;
}
unlock:
bh_unlock_sock(sk);
return 0;
}
| 167,622 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
Commit Message: CVE-2017-13000/IEEE 802.15.4: Fix bug introduced two fixes prior.
We've already advanced the pointer past the PAN ID, if present; it now
points to the address, so don't add 2 to it.
This fixes a buffer over-read 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-125 | ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| 167,907 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IsAllowed(const scoped_refptr<const Extension>& extension,
const GURL& url,
PermittedFeature feature,
int tab_id) {
const PermissionsData* permissions_data = extension->permissions_data();
bool script =
permissions_data->CanAccessPage(url, tab_id, nullptr) &&
permissions_data->CanRunContentScriptOnPage(url, tab_id, nullptr);
bool capture = permissions_data->CanCaptureVisiblePage(url, tab_id, NULL);
switch (feature) {
case PERMITTED_SCRIPT_ONLY:
return script && !capture;
case PERMITTED_CAPTURE_ONLY:
return capture && !script;
case PERMITTED_BOTH:
return script && capture;
case PERMITTED_NONE:
return !script && !capture;
}
NOTREACHED();
return false;
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20 | bool IsAllowed(const scoped_refptr<const Extension>& extension,
const GURL& url,
PermittedFeature feature,
int tab_id) {
const PermissionsData* permissions_data = extension->permissions_data();
bool script =
permissions_data->CanAccessPage(url, tab_id, nullptr) &&
permissions_data->CanRunContentScriptOnPage(url, tab_id, nullptr);
bool capture = permissions_data->CanCaptureVisiblePage(
url, tab_id, NULL, extensions::CaptureRequirement::kActiveTabOrAllUrls);
switch (feature) {
case PERMITTED_SCRIPT_ONLY:
return script && !capture;
case PERMITTED_CAPTURE_ONLY:
return capture && !script;
case PERMITTED_BOTH:
return script && capture;
case PERMITTED_NONE:
return !script && !capture;
}
NOTREACHED();
return false;
}
| 173,003 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock,
struct buffer_head *bh_map, struct metapath *mp,
const unsigned int sheight,
const unsigned int height,
const unsigned int maxlen)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh = mp->mp_bh[0];
u64 bn, dblock = 0;
unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
unsigned dblks = 0;
unsigned ptrs_per_blk;
const unsigned end_of_metadata = height - 1;
int eob = 0;
enum alloc_state state;
__be64 *ptr;
__be64 zero_bn = 0;
BUG_ON(sheight < 1);
BUG_ON(dibh == NULL);
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (height == sheight) {
struct buffer_head *bh;
/* Bottom indirect block exists, find unalloced extent size */
ptr = metapointer(end_of_metadata, mp);
bh = mp->mp_bh[end_of_metadata];
dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,
&eob);
BUG_ON(dblks < 1);
state = ALLOC_DATA;
} else {
/* Need to allocate indirect blocks */
ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;
dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);
if (height == ip->i_height) {
/* Writing into existing tree, extend tree down */
iblks = height - sheight;
state = ALLOC_GROW_DEPTH;
} else {
/* Building up tree height */
state = ALLOC_GROW_HEIGHT;
iblks = height - ip->i_height;
branch_start = metapath_branch_start(mp);
iblks += (height - branch_start);
}
}
/* start of the second part of the function (state machine) */
blks = dblks + iblks;
i = sheight;
do {
int error;
n = blks - alloced;
error = gfs2_alloc_block(ip, &bn, &n);
if (error)
return error;
alloced += n;
if (state != ALLOC_DATA || gfs2_is_jdata(ip))
gfs2_trans_add_unrevoke(sdp, bn, n);
switch (state) {
/* Growing height of tree */
case ALLOC_GROW_HEIGHT:
if (i == 1) {
ptr = (__be64 *)(dibh->b_data +
sizeof(struct gfs2_dinode));
zero_bn = *ptr;
}
for (; i - 1 < height - ip->i_height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
if (i - 1 == height - ip->i_height) {
i--;
gfs2_buffer_copy_tail(mp->mp_bh[i],
sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
gfs2_buffer_clear_tail(dibh,
sizeof(struct gfs2_dinode) +
sizeof(__be64));
ptr = (__be64 *)(mp->mp_bh[i]->b_data +
sizeof(struct gfs2_meta_header));
*ptr = zero_bn;
state = ALLOC_GROW_DEPTH;
for(i = branch_start; i < height; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
i = branch_start;
}
if (n == 0)
break;
/* Branching from existing tree */
case ALLOC_GROW_DEPTH:
if (i > 1 && i < height)
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);
for (; i < height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i,
mp->mp_list[i-1], bn++);
if (i == height)
state = ALLOC_DATA;
if (n == 0)
break;
/* Tree complete, adding data blocks */
case ALLOC_DATA:
BUG_ON(n > dblks);
BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);
dblks = n;
ptr = metapointer(end_of_metadata, mp);
dblock = bn;
while (n-- > 0)
*ptr++ = cpu_to_be64(bn++);
break;
}
} while ((state != ALLOC_DATA) || !dblock);
ip->i_height = height;
gfs2_add_inode_blocks(&ip->i_inode, alloced);
gfs2_dinode_out(ip, mp->mp_bh[0]->b_data);
map_bh(bh_map, inode->i_sb, dblock);
bh_map->b_size = dblks << inode->i_blkbits;
set_buffer_new(bh_map);
return 0;
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <[email protected]>
Signed-off-by: Steven Whitehouse <[email protected]>
CWE ID: CWE-119 | static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock,
struct buffer_head *bh_map, struct metapath *mp,
const unsigned int sheight,
const unsigned int height,
const unsigned int maxlen)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct super_block *sb = sdp->sd_vfs;
struct buffer_head *dibh = mp->mp_bh[0];
u64 bn, dblock = 0;
unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
unsigned dblks = 0;
unsigned ptrs_per_blk;
const unsigned end_of_metadata = height - 1;
int ret;
int eob = 0;
enum alloc_state state;
__be64 *ptr;
__be64 zero_bn = 0;
BUG_ON(sheight < 1);
BUG_ON(dibh == NULL);
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (height == sheight) {
struct buffer_head *bh;
/* Bottom indirect block exists, find unalloced extent size */
ptr = metapointer(end_of_metadata, mp);
bh = mp->mp_bh[end_of_metadata];
dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,
&eob);
BUG_ON(dblks < 1);
state = ALLOC_DATA;
} else {
/* Need to allocate indirect blocks */
ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;
dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);
if (height == ip->i_height) {
/* Writing into existing tree, extend tree down */
iblks = height - sheight;
state = ALLOC_GROW_DEPTH;
} else {
/* Building up tree height */
state = ALLOC_GROW_HEIGHT;
iblks = height - ip->i_height;
branch_start = metapath_branch_start(mp);
iblks += (height - branch_start);
}
}
/* start of the second part of the function (state machine) */
blks = dblks + iblks;
i = sheight;
do {
int error;
n = blks - alloced;
error = gfs2_alloc_block(ip, &bn, &n);
if (error)
return error;
alloced += n;
if (state != ALLOC_DATA || gfs2_is_jdata(ip))
gfs2_trans_add_unrevoke(sdp, bn, n);
switch (state) {
/* Growing height of tree */
case ALLOC_GROW_HEIGHT:
if (i == 1) {
ptr = (__be64 *)(dibh->b_data +
sizeof(struct gfs2_dinode));
zero_bn = *ptr;
}
for (; i - 1 < height - ip->i_height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
if (i - 1 == height - ip->i_height) {
i--;
gfs2_buffer_copy_tail(mp->mp_bh[i],
sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
gfs2_buffer_clear_tail(dibh,
sizeof(struct gfs2_dinode) +
sizeof(__be64));
ptr = (__be64 *)(mp->mp_bh[i]->b_data +
sizeof(struct gfs2_meta_header));
*ptr = zero_bn;
state = ALLOC_GROW_DEPTH;
for(i = branch_start; i < height; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
i = branch_start;
}
if (n == 0)
break;
/* Branching from existing tree */
case ALLOC_GROW_DEPTH:
if (i > 1 && i < height)
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);
for (; i < height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i,
mp->mp_list[i-1], bn++);
if (i == height)
state = ALLOC_DATA;
if (n == 0)
break;
/* Tree complete, adding data blocks */
case ALLOC_DATA:
BUG_ON(n > dblks);
BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);
dblks = n;
ptr = metapointer(end_of_metadata, mp);
dblock = bn;
while (n-- > 0)
*ptr++ = cpu_to_be64(bn++);
if (buffer_zeronew(bh_map)) {
ret = sb_issue_zeroout(sb, dblock, dblks,
GFP_NOFS);
if (ret) {
fs_err(sdp,
"Failed to zero data buffers\n");
clear_buffer_zeronew(bh_map);
}
}
break;
}
} while ((state != ALLOC_DATA) || !dblock);
ip->i_height = height;
gfs2_add_inode_blocks(&ip->i_inode, alloced);
gfs2_dinode_out(ip, mp->mp_bh[0]->b_data);
map_bh(bh_map, inode->i_sb, dblock);
bh_map->b_size = dblks << inode->i_blkbits;
set_buffer_new(bh_map);
return 0;
}
| 166,210 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: write_one_file(Image *output, Image *image, int convert_to_8bit)
{
if (image->opts & FAST_WRITE)
image->image.flags |= PNG_IMAGE_FLAG_FAST;
if (image->opts & USE_STDIO)
{
FILE *f = tmpfile();
if (f != NULL)
{
if (png_image_write_to_stdio(&image->image, f, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
if (fflush(f) == 0)
{
rewind(f);
initimage(output, image->opts, "tmpfile", image->stride_extra);
output->input_file = f;
if (!checkopaque(image))
return 0;
}
else
return logclose(image, f, "tmpfile", ": flush: ");
}
else
{
fclose(f);
return logerror(image, "tmpfile", ": write failed", "");
}
}
else
return logerror(image, "tmpfile", ": open: ", strerror(errno));
}
else
{
static int counter = 0;
char name[32];
sprintf(name, "%s%d.png", tmpf, ++counter);
if (png_image_write_to_file(&image->image, name, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
initimage(output, image->opts, output->tmpfile_name,
image->stride_extra);
/* Afterwards, or freeimage will delete it! */
strcpy(output->tmpfile_name, name);
if (!checkopaque(image))
return 0;
}
else
return logerror(image, name, ": write failed", "");
}
/* 'output' has an initialized temporary image, read this back in and compare
* this against the original: there should be no change since the original
* format was written unmodified unless 'convert_to_8bit' was specified.
* However, if the original image was color-mapped, a simple read will zap
* the linear, color and maybe alpha flags, this will cause spurious failures
* under some circumstances.
*/
if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL))
{
png_uint_32 original_format = image->image.format;
if (convert_to_8bit)
original_format &= ~PNG_FORMAT_FLAG_LINEAR;
if ((output->image.format & BASE_FORMATS) !=
(original_format & BASE_FORMATS))
return logerror(image, image->file_name, ": format changed on read: ",
output->file_name);
return compare_two_images(image, output, 0/*via linear*/, NULL);
}
else
return logerror(output, output->tmpfile_name,
": read of new file failed", "");
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | write_one_file(Image *output, Image *image, int convert_to_8bit)
{
if (image->opts & FAST_WRITE)
image->image.flags |= PNG_IMAGE_FLAG_FAST;
if (image->opts & USE_STDIO)
{
#ifndef PNG_USE_MKSTEMP
FILE *f = tmpfile();
#else
/* Experimental. Coverity says tmpfile() is insecure because it
* generates predictable names.
*
* It is possible to satisfy Coverity by using mkstemp(); however,
* any platform supporting mkstemp() undoubtedly has a secure tmpfile()
* implementation as well, and doesn't need the fix. Note that
* the fix won't work on platforms that don't support mkstemp().
*
* https://www.securecoding.cert.org/confluence/display/c/
* FIO21-C.+Do+not+create+temporary+files+in+shared+directories
* says that most historic implementations of tmpfile() provide
* only a limited number of possible temporary file names
* (usually 26) before file names are recycled. That article also
* provides a secure solution that unfortunately depends upon mkstemp().
*/
char tmpfile[] = "pngstest-XXXXXX";
int filedes;
FILE *f;
umask(0177);
filedes = mkstemp(tmpfile);
if (filedes < 0)
f = NULL;
else
{
f = fdopen(filedes,"w+");
/* Hide the filename immediately and ensure that the file does
* not exist after the program ends
*/
(void) unlink(tmpfile);
}
#endif
if (f != NULL)
{
if (png_image_write_to_stdio(&image->image, f, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
if (fflush(f) == 0)
{
rewind(f);
initimage(output, image->opts, "tmpfile", image->stride_extra);
output->input_file = f;
if (!checkopaque(image))
return 0;
}
else
return logclose(image, f, "tmpfile", ": flush: ");
}
else
{
fclose(f);
return logerror(image, "tmpfile", ": write failed", "");
}
}
else
return logerror(image, "tmpfile", ": open: ", strerror(errno));
}
else
{
static int counter = 0;
char name[32];
sprintf(name, "%s%d.png", tmpf, ++counter);
if (png_image_write_to_file(&image->image, name, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
initimage(output, image->opts, output->tmpfile_name,
image->stride_extra);
/* Afterwards, or freeimage will delete it! */
strcpy(output->tmpfile_name, name);
if (!checkopaque(image))
return 0;
}
else
return logerror(image, name, ": write failed", "");
}
/* 'output' has an initialized temporary image, read this back in and compare
* this against the original: there should be no change since the original
* format was written unmodified unless 'convert_to_8bit' was specified.
* However, if the original image was color-mapped, a simple read will zap
* the linear, color and maybe alpha flags, this will cause spurious failures
* under some circumstances.
*/
if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL))
{
png_uint_32 original_format = image->image.format;
if (convert_to_8bit)
original_format &= ~PNG_FORMAT_FLAG_LINEAR;
if ((output->image.format & BASE_FORMATS) !=
(original_format & BASE_FORMATS))
return logerror(image, image->file_name, ": format changed on read: ",
output->file_name);
return compare_two_images(image, output, 0/*via linear*/, NULL);
}
else
return logerror(output, output->tmpfile_name,
": read of new file failed", "");
}
| 173,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
{
mainprog_info *mainprog_ptr;
/* retrieve the pointer to our special-purpose struct */
mainprog_ptr = png_get_progressive_ptr(png_ptr);
/* let the main program know that it should flush any buffered image
* data to the display now and set a "done" flag or whatever, but note
* that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
* NOT call readpng2_cleanup() either here or in the finish_display()
* routine; wait until control returns to the main program via
* readpng2_decode_data() */
(*mainprog_ptr->mainprog_finish_display)();
/* all done */
return;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
{
mainprog_info *mainprog_ptr;
/* retrieve the pointer to our special-purpose struct */
mainprog_ptr = png_get_progressive_ptr(png_ptr);
/* let the main program know that it should flush any buffered image
* data to the display now and set a "done" flag or whatever, but note
* that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
* NOT call readpng2_cleanup() either here or in the finish_display()
* routine; wait until control returns to the main program via
* readpng2_decode_data() */
(*mainprog_ptr->mainprog_finish_display)();
/* all done */
(void)info_ptr; /* Unused */
return;
}
| 173,568 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FrameFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason) const {
if (IsDetached())
return;
probe::didBlockRequest(GetFrame()->GetDocument(), resource_request,
MasterDocumentLoader(), fetch_initiator_info,
blocked_reason);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | void FrameFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason,
Resource::Type resource_type) const {
if (IsDetached())
return;
probe::didBlockRequest(GetFrame()->GetDocument(), resource_request,
MasterDocumentLoader(), fetch_initiator_info,
blocked_reason, resource_type);
}
| 172,473 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BiquadDSPKernel::updateCoefficientsIfNecessary(bool useSmoothing, bool forceUpdate)
{
if (forceUpdate || biquadProcessor()->filterCoefficientsDirty()) {
double value1;
double value2;
double gain;
double detune; // in Cents
if (biquadProcessor()->hasSampleAccurateValues()) {
value1 = biquadProcessor()->parameter1()->finalValue();
value2 = biquadProcessor()->parameter2()->finalValue();
gain = biquadProcessor()->parameter3()->finalValue();
detune = biquadProcessor()->parameter4()->finalValue();
} else if (useSmoothing) {
value1 = biquadProcessor()->parameter1()->smoothedValue();
value2 = biquadProcessor()->parameter2()->smoothedValue();
gain = biquadProcessor()->parameter3()->smoothedValue();
detune = biquadProcessor()->parameter4()->smoothedValue();
} else {
value1 = biquadProcessor()->parameter1()->value();
value2 = biquadProcessor()->parameter2()->value();
gain = biquadProcessor()->parameter3()->value();
detune = biquadProcessor()->parameter4()->value();
}
double nyquist = this->nyquist();
double normalizedFrequency = value1 / nyquist;
if (detune)
normalizedFrequency *= pow(2, detune / 1200);
switch (biquadProcessor()->type()) {
case BiquadProcessor::LowPass:
m_biquad.setLowpassParams(normalizedFrequency, value2);
break;
case BiquadProcessor::HighPass:
m_biquad.setHighpassParams(normalizedFrequency, value2);
break;
case BiquadProcessor::BandPass:
m_biquad.setBandpassParams(normalizedFrequency, value2);
break;
case BiquadProcessor::LowShelf:
m_biquad.setLowShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::HighShelf:
m_biquad.setHighShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::Peaking:
m_biquad.setPeakingParams(normalizedFrequency, value2, gain);
break;
case BiquadProcessor::Notch:
m_biquad.setNotchParams(normalizedFrequency, value2);
break;
case BiquadProcessor::Allpass:
m_biquad.setAllpassParams(normalizedFrequency, value2);
break;
}
}
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void BiquadDSPKernel::updateCoefficientsIfNecessary(bool useSmoothing, bool forceUpdate)
void BiquadDSPKernel::updateCoefficientsIfNecessary()
{
if (biquadProcessor()->filterCoefficientsDirty()) {
double cutoffFrequency;
double Q;
double gain;
double detune; // in Cents
if (biquadProcessor()->hasSampleAccurateValues()) {
cutoffFrequency = biquadProcessor()->parameter1()->finalValue();
Q = biquadProcessor()->parameter2()->finalValue();
gain = biquadProcessor()->parameter3()->finalValue();
detune = biquadProcessor()->parameter4()->finalValue();
} else {
cutoffFrequency = biquadProcessor()->parameter1()->smoothedValue();
Q = biquadProcessor()->parameter2()->smoothedValue();
gain = biquadProcessor()->parameter3()->smoothedValue();
detune = biquadProcessor()->parameter4()->smoothedValue();
}
updateCoefficients(cutoffFrequency, Q, gain, detune);
}
}
void BiquadDSPKernel::updateCoefficients(double cutoffFrequency, double Q, double gain, double detune)
{
// Convert from Hertz to normalized frequency 0 -> 1.
double nyquist = this->nyquist();
double normalizedFrequency = cutoffFrequency / nyquist;
// Offset frequency by detune.
if (detune)
normalizedFrequency *= pow(2, detune / 1200);
// Configure the biquad with the new filter parameters for the appropriate type of filter.
switch (biquadProcessor()->type()) {
case BiquadProcessor::LowPass:
m_biquad.setLowpassParams(normalizedFrequency, Q);
break;
case BiquadProcessor::HighPass:
m_biquad.setHighpassParams(normalizedFrequency, Q);
break;
case BiquadProcessor::BandPass:
m_biquad.setBandpassParams(normalizedFrequency, Q);
break;
case BiquadProcessor::LowShelf:
m_biquad.setLowShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::HighShelf:
m_biquad.setHighShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::Peaking:
m_biquad.setPeakingParams(normalizedFrequency, Q, gain);
break;
case BiquadProcessor::Notch:
m_biquad.setNotchParams(normalizedFrequency, Q);
break;
case BiquadProcessor::Allpass:
m_biquad.setAllpassParams(normalizedFrequency, Q);
break;
}
}
| 171,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderViewTest::SetUp() {
blink::initialize(blink_platform_impl_.Get());
content_client_.reset(CreateContentClient());
content_browser_client_.reset(CreateContentBrowserClient());
content_renderer_client_.reset(CreateContentRendererClient());
SetContentClient(content_client_.get());
SetBrowserClientForTesting(content_browser_client_.get());
SetRendererClientForTesting(content_renderer_client_.get());
if (!render_thread_)
render_thread_.reset(new MockRenderThread());
render_thread_->set_routing_id(kRouteId);
render_thread_->set_surface_id(kSurfaceId);
render_thread_->set_new_window_routing_id(kNewWindowRouteId);
render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
#if defined(OS_MACOSX)
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
#endif
command_line_.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
params_.reset(new MainFunctionParams(*command_line_));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
std::string flags("--expose-gc");
v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
RenderThreadImpl::RegisterSchemes();
if (!ui::ResourceBundle::HasSharedInstance())
ui::ResourceBundle::InitSharedInstanceWithLocale(
"en-US", NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
compositor_deps_.reset(new FakeCompositorDependencies);
mock_process_.reset(new MockRenderProcess);
ViewMsg_New_Params view_params;
view_params.opener_frame_route_id = MSG_ROUTING_NONE;
view_params.window_was_created_with_opener = false;
view_params.renderer_preferences = RendererPreferences();
view_params.web_preferences = WebPreferences();
view_params.view_id = kRouteId;
view_params.main_frame_routing_id = kMainFrameRouteId;
view_params.surface_id = kSurfaceId;
view_params.session_storage_namespace_id = kInvalidSessionStorageNamespaceId;
view_params.swapped_out = false;
view_params.replicated_frame_state = FrameReplicationState();
view_params.proxy_routing_id = MSG_ROUTING_NONE;
view_params.hidden = false;
view_params.never_visible = false;
view_params.next_page_id = 1;
view_params.initial_size = *InitialSizeParams();
view_params.enable_auto_resize = false;
view_params.min_size = gfx::Size();
view_params.max_size = gfx::Size();
RenderViewImpl* view =
RenderViewImpl::Create(compositor_deps_.get(), view_params, false);
view_ = view;
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399 | void RenderViewTest::SetUp() {
blink::initialize(blink_platform_impl_.Get());
content_client_.reset(CreateContentClient());
content_browser_client_.reset(CreateContentBrowserClient());
content_renderer_client_.reset(CreateContentRendererClient());
SetContentClient(content_client_.get());
SetBrowserClientForTesting(content_browser_client_.get());
SetRendererClientForTesting(content_renderer_client_.get());
if (!render_thread_)
render_thread_.reset(new MockRenderThread());
render_thread_->set_routing_id(kRouteId);
render_thread_->set_surface_id(kSurfaceId);
render_thread_->set_new_window_routing_id(kNewWindowRouteId);
render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
#if defined(OS_MACOSX)
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
#endif
command_line_.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
params_.reset(new MainFunctionParams(*command_line_));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
std::string flags("--expose-gc");
v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
RenderThreadImpl::RegisterSchemes();
if (!ui::ResourceBundle::HasSharedInstance())
ui::ResourceBundle::InitSharedInstanceWithLocale(
"en-US", NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
compositor_deps_.reset(new FakeCompositorDependencies);
mock_process_.reset(new MockRenderProcess);
ViewMsg_New_Params view_params;
view_params.opener_frame_route_id = MSG_ROUTING_NONE;
view_params.window_was_created_with_opener = false;
view_params.renderer_preferences = RendererPreferences();
view_params.web_preferences = WebPreferences();
view_params.view_id = kRouteId;
view_params.main_frame_routing_id = kMainFrameRouteId;
view_params.surface_id = kSurfaceId;
view_params.session_storage_namespace_id = kInvalidSessionStorageNamespaceId;
view_params.swapped_out = false;
view_params.replicated_frame_state = FrameReplicationState();
view_params.proxy_routing_id = MSG_ROUTING_NONE;
view_params.hidden = false;
view_params.never_visible = false;
view_params.next_page_id = 1;
view_params.initial_size = *InitialSizeParams();
view_params.enable_auto_resize = false;
view_params.min_size = gfx::Size();
view_params.max_size = gfx::Size();
#if !defined(OS_IOS)
InitializeMojo();
#endif
RenderViewImpl* view =
RenderViewImpl::Create(compositor_deps_.get(), view_params, false);
view_ = view;
}
| 171,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
espruino_snprintf(str, len, "?[%d]", token);
}
Commit Message: remove strncpy usage as it's effectively useless, replace with an assertion since fn is only used internally (fix #1426)
CWE ID: CWE-787 | void jslTokenAsString(int token, char *str, size_t len) {
assert(len>28); // size of largest string
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strcpy(str, "EOF"); return;
case LEX_ID : strcpy(str, "ID"); return;
case LEX_INT : strcpy(str, "INT"); return;
case LEX_FLOAT : strcpy(str, "FLOAT"); return;
case LEX_STR : strcpy(str, "STRING"); return;
case LEX_UNFINISHED_STR : strcpy(str, "UNFINISHED STRING"); return;
case LEX_TEMPLATE_LITERAL : strcpy(str, "TEMPLATE LITERAL"); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strcpy(str, "UNFINISHED TEMPLATE LITERAL"); return;
case LEX_REGEX : strcpy(str, "REGEX"); return;
case LEX_UNFINISHED_REGEX : strcpy(str, "UNFINISHED REGEX"); return;
case LEX_UNFINISHED_COMMENT : strcpy(str, "UNFINISHED COMMENT"); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strcpy(str, &tokenNames[p]);
return;
}
espruino_snprintf(str, len, "?[%d]", token);
}
| 169,215 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(Navigator& navigator, ExceptionState& exceptionState)
{
return NavigatorServiceWorker::from(navigator).serviceWorker(exceptionState);
}
Commit Message: Add ASSERT() to avoid accidental leaking ServiceWorkerContainer to cross origin context.
BUG=522791
Review URL: https://codereview.chromium.org/1305903007
git-svn-id: svn://svn.chromium.org/blink/trunk@201889 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(Navigator& navigator, ExceptionState& exceptionState)
ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(ExecutionContext* executionContext, Navigator& navigator, ExceptionState& exceptionState)
{
ASSERT(!navigator.frame() || executionContext->securityOrigin()->canAccessCheckSuborigins(navigator.frame()->securityContext()->securityOrigin()));
return NavigatorServiceWorker::from(navigator).serviceWorker(exceptionState);
}
| 171,862 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MultibufferDataSource::DidGetOpaqueResponseViaServiceWorker() const {
return url_data()->has_opaque_data();
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool MultibufferDataSource::DidGetOpaqueResponseViaServiceWorker() const {
bool MultibufferDataSource::IsCorsCrossOrigin() const {
return url_data()->is_cors_cross_origin();
}
| 172,623 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pentry, *pmembers, *pcount = NULL, *pinf;
long count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pcount);
if (!php_var_unserialize(&pcount, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
while(count-- > 0) {
spl_SplObjectStorageElement *pelement;
char *hash;
int hash_len;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
ALLOC_INIT_ZVAL(pentry);
if (!php_var_unserialize(&pentry, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pentry);
goto outexcept;
}
if(Z_TYPE_P(pentry) != IS_OBJECT) {
zval_ptr_dtor(&pentry);
goto outexcept;
}
ALLOC_INIT_ZVAL(pinf);
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&pinf, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pinf);
goto outexcept;
}
}
hash = spl_object_storage_get_hash(intern, getThis(), pentry, &hash_len TSRMLS_CC);
if (!hash) {
zval_ptr_dtor(&pentry);
zval_ptr_dtor(&pinf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC);
spl_object_storage_free_hash(intern, hash);
if(pelement) {
if(pelement->inf) {
var_push_dtor(&var_hash, &pelement->inf);
}
if(pelement->obj) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
spl_object_storage_attach(intern, getThis(), pentry, pinf TSRMLS_CC);
zval_ptr_dtor(&pentry);
zval_ptr_dtor(&pinf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
if (pcount) {
zval_ptr_dtor(&pcount);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
if (pcount) {
zval_ptr_dtor(&pcount);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
Commit Message:
CWE ID: | SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pentry, *pmembers, *pcount = NULL, *pinf;
long count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pcount);
if (!php_var_unserialize(&pcount, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
while(count-- > 0) {
spl_SplObjectStorageElement *pelement;
char *hash;
int hash_len;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
ALLOC_INIT_ZVAL(pentry);
if (!php_var_unserialize(&pentry, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pentry);
goto outexcept;
}
if(Z_TYPE_P(pentry) != IS_OBJECT) {
zval_ptr_dtor(&pentry);
goto outexcept;
}
ALLOC_INIT_ZVAL(pinf);
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&pinf, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pinf);
goto outexcept;
}
}
hash = spl_object_storage_get_hash(intern, getThis(), pentry, &hash_len TSRMLS_CC);
if (!hash) {
zval_ptr_dtor(&pentry);
zval_ptr_dtor(&pinf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC);
spl_object_storage_free_hash(intern, hash);
if(pelement) {
if(pelement->inf) {
var_push_dtor(&var_hash, &pelement->inf);
}
if(pelement->obj) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
spl_object_storage_attach(intern, getThis(), pentry, pinf TSRMLS_CC);
zval_ptr_dtor(&pentry);
zval_ptr_dtor(&pinf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
if (pcount) {
zval_ptr_dtor(&pcount);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
if (pcount) {
zval_ptr_dtor(&pcount);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
| 165,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
| 169,081 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_id *idp;
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
idp = (const struct ikev2_id *)ext;
ND_TCHECK(*idp);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,796 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
unsigned int, flags, struct sockaddr __user *, addr,
int __user *, addr_len)
{
struct socket *sock;
struct iovec iov;
struct msghdr msg;
struct sockaddr_storage address;
int err, err2;
int fput_needed;
if (size > INT_MAX)
size = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
msg.msg_control = NULL;
msg.msg_controllen = 0;
iov.iov_len = size;
iov.iov_base = ubuf;
iov_iter_init(&msg.msg_iter, READ, &iov, 1, size);
/* Save some cycles and don't copy the address if not needed */
msg.msg_name = addr ? (struct sockaddr *)&address : NULL;
/* We assume all kernel code knows the size of sockaddr_storage */
msg.msg_namelen = 0;
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
err = sock_recvmsg(sock, &msg, size, flags);
if (err >= 0 && addr != NULL) {
err2 = move_addr_to_user(&address,
msg.msg_namelen, addr, addr_len);
if (err2 < 0)
err = err2;
}
fput_light(sock->file, fput_needed);
out:
return err;
}
Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom
Cc: [email protected] # v3.19
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
unsigned int, flags, struct sockaddr __user *, addr,
int __user *, addr_len)
{
struct socket *sock;
struct iovec iov;
struct msghdr msg;
struct sockaddr_storage address;
int err, err2;
int fput_needed;
if (size > INT_MAX)
size = INT_MAX;
if (unlikely(!access_ok(VERIFY_WRITE, ubuf, size)))
return -EFAULT;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
msg.msg_control = NULL;
msg.msg_controllen = 0;
iov.iov_len = size;
iov.iov_base = ubuf;
iov_iter_init(&msg.msg_iter, READ, &iov, 1, size);
/* Save some cycles and don't copy the address if not needed */
msg.msg_name = addr ? (struct sockaddr *)&address : NULL;
/* We assume all kernel code knows the size of sockaddr_storage */
msg.msg_namelen = 0;
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
err = sock_recvmsg(sock, &msg, size, flags);
if (err >= 0 && addr != NULL) {
err2 = move_addr_to_user(&address,
msg.msg_namelen, addr, addr_len);
if (err2 < 0)
err = err2;
}
fput_light(sock->file, fput_needed);
out:
return err;
}
| 167,571 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
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);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
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);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_gray_to_rgb(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this,
image_transform_png_set_gray_to_rgb_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_gray_to_rgb(pp);
/* NOTE: this doesn't result in tRNS expansion. */
this->next->set(this->next, that, pp, pi);
}
| 173,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
const xmlChar *ptr;
xmlChar cur;
xmlChar *name;
xmlEntityPtr entity = NULL;
if ((str == NULL) || (*str == NULL)) return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '%')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringPEReference: no name\n");
*str = ptr;
return(NULL);
}
cur = *ptr;
if (cur != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData,
name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"%%%s; is not a parameter entity\n",
name, NULL);
}
}
ctxt->hasPErefs = 1;
xmlFree(name);
*str = ptr;
return(entity);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
const xmlChar *ptr;
xmlChar cur;
xmlChar *name;
xmlEntityPtr entity = NULL;
if ((str == NULL) || (*str == NULL)) return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '%')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringPEReference: no name\n");
*str = ptr;
return(NULL);
}
cur = *ptr;
if (cur != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(name);
return(NULL);
}
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"%%%s; is not a parameter entity\n",
name, NULL);
}
}
ctxt->hasPErefs = 1;
xmlFree(name);
*str = ptr;
return(entity);
}
| 171,305 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int get_sda(void)
{
return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | int get_sda(void)
| 169,630 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const CuePoint* Cues::GetLast() const
{
if (m_cue_points == NULL)
return NULL;
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const CuePoint* Cues::GetLast() const
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
| 174,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr )
{
MOOV_Manager::BoxInfo udtaInfo;
MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo );
if ( udtaRef == 0 ) return false;
for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) {
MOOV_Manager::BoxInfo currInfo;
MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo );
if ( currRef == 0 ) break; // Sanity check, should not happen.
if ( (currInfo.boxType >> 24) != 0xA9 ) continue;
if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value.
InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(),
InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) );
std::vector<ValueInfo> * newValues = &newInfo->second.values;
XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content;
XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize;
XMP_Uns16 miniLen, macLang;
for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) {
miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen.
macLang = GetUns16BE ( boxPtr+2);
if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) ) continue; // Ignore bad or empty values.
XMP_StringPtr valuePtr = (char*)(boxPtr+4);
size_t valueLen = miniLen - 4;
newValues->push_back ( ValueInfo() );
ValueInfo * newValue = &newValues->back();
newValue->macLang = macLang;
if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang );
newValue->macValue.assign ( valuePtr, valueLen );
}
}
return (! this->parsedBoxes.empty());
} // TradQT_Manager::ParseCachedBoxes
Commit Message:
CWE ID: CWE-835 | bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr )
{
MOOV_Manager::BoxInfo udtaInfo;
MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo );
if ( udtaRef == 0 ) return false;
for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) {
MOOV_Manager::BoxInfo currInfo;
MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo );
if ( currRef == 0 ) break; // Sanity check, should not happen.
if ( (currInfo.boxType >> 24) != 0xA9 ) continue;
if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value.
InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(),
InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) );
std::vector<ValueInfo> * newValues = &newInfo->second.values;
XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content;
XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize;
XMP_Uns16 miniLen, macLang;
for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) {
miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen.
macLang = GetUns16BE ( boxPtr+2);
if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) )
break; // Ignore bad or empty values.
XMP_StringPtr valuePtr = (char*)(boxPtr+4);
size_t valueLen = miniLen - 4;
newValues->push_back ( ValueInfo() );
ValueInfo * newValue = &newValues->back();
newValue->macLang = macLang;
if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang );
newValue->macValue.assign ( valuePtr, valueLen );
}
}
return (! this->parsedBoxes.empty());
} // TradQT_Manager::ParseCachedBoxes
| 165,364 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_read (SF_PRIVATE *psf, void *ptr, int bytes)
{ int count = 0 ;
if (psf->headindex >= SIGNED_SIZEOF (psf->header))
return psf_fread (ptr, 1, bytes, psf) ;
if (psf->headindex + bytes > SIGNED_SIZEOF (psf->header))
{ int most ;
most = SIGNED_SIZEOF (psf->header) - psf->headend ;
psf_fread (psf->header + psf->headend, 1, most, psf) ;
memcpy (ptr, psf->header + psf->headend, most) ;
psf->headend = psf->headindex += most ;
psf_fread ((char *) ptr + most, bytes - most, 1, psf) ;
return bytes ;
} ;
if (psf->headindex + bytes > psf->headend)
{ count = psf_fread (psf->header + psf->headend, 1, bytes - (psf->headend - psf->headindex), psf) ;
if (count != bytes - (int) (psf->headend - psf->headindex))
{ psf_log_printf (psf, "Error : psf_fread returned short count.\n") ;
return count ;
} ;
psf->headend += count ;
} ;
memcpy (ptr, psf->header + psf->headindex, bytes) ;
psf->headindex += bytes ;
return bytes ;
} /* header_read */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_read (SF_PRIVATE *psf, void *ptr, int bytes)
{ int count = 0 ;
if (psf->header.indx + bytes >= psf->header.len && psf_bump_header_allocation (psf, bytes))
return count ;
if (psf->header.indx + bytes > psf->header.end)
{ count = psf_fread (psf->header.ptr + psf->header.end, 1, bytes - (psf->header.end - psf->header.indx), psf) ;
if (count != bytes - (int) (psf->header.end - psf->header.indx))
{ psf_log_printf (psf, "Error : psf_fread returned short count.\n") ;
return count ;
} ;
psf->header.end += count ;
} ;
memcpy (ptr, psf->header.ptr + psf->header.indx, bytes) ;
psf->header.indx += bytes ;
return bytes ;
} /* header_read */
| 170,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool InputWindowInfo::isTrustedOverlay() const {
return layoutParamsType == TYPE_INPUT_METHOD
|| layoutParamsType == TYPE_INPUT_METHOD_DIALOG
|| layoutParamsType == TYPE_MAGNIFICATION_OVERLAY
|| layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
CWE ID: CWE-264 | bool InputWindowInfo::isTrustedOverlay() const {
return layoutParamsType == TYPE_INPUT_METHOD
|| layoutParamsType == TYPE_INPUT_METHOD_DIALOG
|| layoutParamsType == TYPE_MAGNIFICATION_OVERLAY
|| layoutParamsType == TYPE_STATUS_BAR
|| layoutParamsType == TYPE_NAVIGATION_BAR
|| layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
}
| 174,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
if (ShowingInterstitialPage()) {
GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
return;
}
RenderWidgetHostView* const fullscreen_view =
GetFullscreenRenderWidgetHostView();
if (fullscreen_view) {
fullscreen_view->Focus();
return;
}
GetRenderViewHost()->SetInitialFocus(reverse);
}
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::FocusThroughTabTraversal(bool reverse) {
if (ShowingInterstitialPage()) {
interstitial_page_->FocusThroughTabTraversal(reverse);
return;
}
RenderWidgetHostView* const fullscreen_view =
GetFullscreenRenderWidgetHostView();
if (fullscreen_view) {
fullscreen_view->Focus();
return;
}
GetRenderViewHost()->SetInitialFocus(reverse);
}
| 172,327 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_session_destroy(TSRMLS_D) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
return FAILURE;
}
if (PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
}
php_rinit_session_globals(TSRMLS_C);
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */
{
zval **sym_track = NULL;
IF_SESSION_VARS() {
zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track);
} else {
return;
}
if (sym_track == NULL) {
zval *empty_var;
ALLOC_INIT_ZVAL(empty_var);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0);
}
}
/* }}} */
PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var);
}
return ret;
}
/* }}} */
static void php_session_track_init(TSRMLS_D) /* {{{ */
{
zval *session_vars = NULL;
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
MAKE_STD_ZVAL(session_vars);
array_init(session_vars);
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1);
}
/* }}} */
static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
static void php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return;
}
if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) {
php_session_destroy(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed");
}
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
enum {
Commit Message:
CWE ID: CWE-264 | static int php_session_destroy(TSRMLS_D) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
return FAILURE;
}
if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
}
php_rinit_session_globals(TSRMLS_C);
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */
{
zval **sym_track = NULL;
IF_SESSION_VARS() {
zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track);
} else {
return;
}
if (sym_track == NULL) {
zval *empty_var;
ALLOC_INIT_ZVAL(empty_var);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0);
}
}
/* }}} */
PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var);
}
return ret;
}
/* }}} */
static void php_session_track_init(TSRMLS_D) /* {{{ */
{
zval *session_vars = NULL;
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
MAKE_STD_ZVAL(session_vars);
array_init(session_vars);
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1);
}
/* }}} */
static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
static void php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return;
}
if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) {
php_session_destroy(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed");
}
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
enum {
| 164,873 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
Commit Message: Fix bug #73631 - Invalid read when wddx decodes empty boolean element
CWE ID: CWE-125 | static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
} else {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ZVAL_FALSE(&ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
| 168,667 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GLboolean WebGLRenderingContextBase::isShader(WebGLShader* shader) {
if (!shader || isContextLost())
return 0;
return ContextGL()->IsShader(shader->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | GLboolean WebGLRenderingContextBase::isShader(WebGLShader* shader) {
if (!shader || isContextLost() || !shader->Validate(ContextGroup(), this))
return 0;
return ContextGL()->IsShader(shader->Object());
}
| 173,132 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
if (parcel == NULL) {
SkDebugf("-------- unparcel parcel is NULL\n");
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const bool isMutable = p->readInt32() != 0;
const SkColorType colorType = (SkColorType)p->readInt32();
const SkAlphaType alphaType = (SkAlphaType)p->readInt32();
const int width = p->readInt32();
const int height = p->readInt32();
const int rowBytes = p->readInt32();
const int density = p->readInt32();
if (kN32_SkColorType != colorType &&
kRGB_565_SkColorType != colorType &&
kARGB_4444_SkColorType != colorType &&
kIndex_8_SkColorType != colorType &&
kAlpha_8_SkColorType != colorType) {
SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType);
return NULL;
}
SkBitmap* bitmap = new SkBitmap;
bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes);
SkColorTable* ctable = NULL;
if (colorType == kIndex_8_SkColorType) {
int count = p->readInt32();
if (count > 0) {
size_t size = count * sizeof(SkPMColor);
const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
ctable = new SkColorTable(src, count);
}
}
jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable);
if (NULL == buffer) {
SkSafeUnref(ctable);
delete bitmap;
return NULL;
}
SkSafeUnref(ctable);
size_t size = bitmap->getSize();
android::Parcel::ReadableBlob blob;
android::status_t status = p->readBlob(size, &blob);
if (status) {
doThrowRE(env, "Could not read bitmap from parcel blob.");
delete bitmap;
return NULL;
}
bitmap->lockPixels();
memcpy(bitmap->getPixels(), blob.data(), size);
bitmap->unlockPixels();
blob.release();
return GraphicsJNI::createBitmap(env, bitmap, buffer, getPremulBitmapCreateFlags(isMutable),
NULL, NULL, density);
}
Commit Message: Make Bitmap_createFromParcel check the color count. DO NOT MERGE
When reading from the parcel, if the number of colors is invalid, early
exit.
Add two more checks: setInfo must return true, and Parcel::readInplace
must return non-NULL. The former ensures that the previously read values
(width, height, etc) were valid, and the latter checks that the Parcel
had enough data even if the number of colors was reasonable.
Also use an auto-deleter to handle deletion of the SkBitmap.
Cherry pick from change-Id: Icbd562d6d1f131a723724883fd31822d337cf5a6
BUG=19666945
Change-Id: Iab0d218c41ae0c39606e333e44cda078eef32291
CWE ID: CWE-189 | static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
if (parcel == NULL) {
SkDebugf("-------- unparcel parcel is NULL\n");
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const bool isMutable = p->readInt32() != 0;
const SkColorType colorType = (SkColorType)p->readInt32();
const SkAlphaType alphaType = (SkAlphaType)p->readInt32();
const int width = p->readInt32();
const int height = p->readInt32();
const int rowBytes = p->readInt32();
const int density = p->readInt32();
if (kN32_SkColorType != colorType &&
kRGB_565_SkColorType != colorType &&
kARGB_4444_SkColorType != colorType &&
kIndex_8_SkColorType != colorType &&
kAlpha_8_SkColorType != colorType) {
SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType);
return NULL;
}
SkAutoTDelete<SkBitmap> bitmap(new SkBitmap);
if (!bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes)) {
return NULL;
}
SkColorTable* ctable = NULL;
if (colorType == kIndex_8_SkColorType) {
int count = p->readInt32();
if (count < 0 || count > 256) {
// The data is corrupt, since SkColorTable enforces a value between 0 and 256,
// inclusive.
return NULL;
}
if (count > 0) {
size_t size = count * sizeof(SkPMColor);
const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
if (src == NULL) {
return NULL;
}
ctable = new SkColorTable(src, count);
}
}
jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap.get(), ctable);
if (NULL == buffer) {
SkSafeUnref(ctable);
return NULL;
}
SkSafeUnref(ctable);
size_t size = bitmap->getSize();
android::Parcel::ReadableBlob blob;
android::status_t status = p->readBlob(size, &blob);
if (status) {
doThrowRE(env, "Could not read bitmap from parcel blob.");
return NULL;
}
bitmap->lockPixels();
memcpy(bitmap->getPixels(), blob.data(), size);
bitmap->unlockPixels();
blob.release();
return GraphicsJNI::createBitmap(env, bitmap.detach(), buffer,
getPremulBitmapCreateFlags(isMutable), NULL, NULL, density);
}
| 173,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Value> source(GetSource(module_name));
if (source.IsEmpty() || source->IsUndefined()) {
Fatal(context_, "No source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::String> wrapped_source(
WrapSource(v8::Local<v8::String>::Cast(source)));
v8::Local<v8::String> v8_module_name;
if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
NOTREACHED() << "module_name is too long";
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Value> func_as_value =
RunString(wrapped_source, v8_module_name);
if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
Fatal(context_, "Bad source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
v8::Local<v8::Object> natives(NewInstance());
CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
v8::Local<v8::Value> args[] = {
GetPropertyUnsafe(v8_context, define_object, "define"),
GetPropertyUnsafe(v8_context, natives, "require",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireNative",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireAsync",
v8::NewStringType::kInternalized),
exports,
console::AsV8Object(GetIsolate()),
GetPropertyUnsafe(v8_context, natives, "privates",
v8::NewStringType::kInternalized),
context_->safe_builtins()->GetArray(),
context_->safe_builtins()->GetFunction(),
context_->safe_builtins()->GetJSON(),
context_->safe_builtins()->GetObjekt(),
context_->safe_builtins()->GetRegExp(),
context_->safe_builtins()->GetString(),
context_->safe_builtins()->GetError(),
};
{
v8::TryCatch try_catch(GetIsolate());
try_catch.SetCaptureMessage(true);
context_->CallFunction(func, arraysize(args), args);
if (try_catch.HasCaught()) {
HandleException(try_catch);
return v8::Undefined(GetIsolate());
}
}
return handle_scope.Escape(exports);
}
Commit Message: [Extensions] Don't allow built-in extensions code to be overridden
BUG=546677
Review URL: https://codereview.chromium.org/1417513003
Cr-Commit-Position: refs/heads/master@{#356654}
CWE ID: CWE-264 | v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Value> source(GetSource(module_name));
if (source.IsEmpty() || source->IsUndefined()) {
Fatal(context_, "No source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::String> wrapped_source(
WrapSource(v8::Local<v8::String>::Cast(source)));
v8::Local<v8::String> v8_module_name;
if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
NOTREACHED() << "module_name is too long";
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Value> func_as_value =
RunString(wrapped_source, v8_module_name);
if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
Fatal(context_, "Bad source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
v8::Local<v8::Object> exports = v8::Object::New(GetIsolate());
v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
GetIsolate(),
&SetExportsProperty);
v8::Local<v8::String> v8_key;
if (!v8_helpers::ToV8String(GetIsolate(), "$set", &v8_key)) {
NOTREACHED();
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> function;
if (!tmpl->GetFunction(v8_context).ToLocal(&function)) {
NOTREACHED();
return v8::Undefined(GetIsolate());
}
exports->ForceSet(v8_key, function, v8::ReadOnly);
v8::Local<v8::Object> natives(NewInstance());
CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
v8::Local<v8::Value> args[] = {
GetPropertyUnsafe(v8_context, define_object, "define"),
GetPropertyUnsafe(v8_context, natives, "require",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireNative",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireAsync",
v8::NewStringType::kInternalized),
exports,
console::AsV8Object(GetIsolate()),
GetPropertyUnsafe(v8_context, natives, "privates",
v8::NewStringType::kInternalized),
context_->safe_builtins()->GetArray(),
context_->safe_builtins()->GetFunction(),
context_->safe_builtins()->GetJSON(),
context_->safe_builtins()->GetObjekt(),
context_->safe_builtins()->GetRegExp(),
context_->safe_builtins()->GetString(),
context_->safe_builtins()->GetError(),
};
{
v8::TryCatch try_catch(GetIsolate());
try_catch.SetCaptureMessage(true);
context_->CallFunction(func, arraysize(args), args);
if (try_catch.HasCaught()) {
HandleException(try_catch);
return v8::Undefined(GetIsolate());
}
}
return handle_scope.Escape(exports);
}
| 172,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
Commit Message:
CWE ID: CWE-399 | static int bmdma_prepare_buf(IDEDMA *dma, int is_write)
/**
* Return the number of bytes successfully prepared.
* -1 on error.
*/
static int32_t bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
| 164,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)
{
irda_queue_t* queue;
unsigned long flags = 0;
int i;
IRDA_ASSERT(hashbin != NULL, return -1;);
IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags,
hashbin_lock_depth++);
}
/*
* Free the entries in the hashbin, TODO: use hashbin_clear when
* it has been shown to work
*/
for (i = 0; i < HASHBIN_SIZE; i ++ ) {
queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);
while (queue ) {
if (free_func)
(*free_func)(queue);
queue = dequeue_first(
(irda_queue_t**) &hashbin->hb_queue[i]);
}
}
/* Cleanup local data */
hashbin->hb_current = NULL;
hashbin->magic = ~HB_MAGIC;
/* Release lock */
if ( hashbin->hb_type & HB_LOCK) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
#ifdef CONFIG_LOCKDEP
hashbin_lock_depth--;
#endif
}
/*
* Free the hashbin structure
*/
kfree(hashbin);
return 0;
}
Commit Message: irda: Fix lockdep annotations in hashbin_delete().
A nested lock depth was added to the hasbin_delete() code but it
doesn't actually work some well and results in tons of lockdep splats.
Fix the code instead to properly drop the lock around the operation
and just keep peeking the head of the hashbin queue.
Reported-by: Dmitry Vyukov <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)
{
irda_queue_t* queue;
unsigned long flags = 0;
int i;
IRDA_ASSERT(hashbin != NULL, return -1;);
IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);
/* Synchronize */
if (hashbin->hb_type & HB_LOCK)
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
/*
* Free the entries in the hashbin, TODO: use hashbin_clear when
* it has been shown to work
*/
for (i = 0; i < HASHBIN_SIZE; i ++ ) {
while (1) {
queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);
if (!queue)
break;
if (free_func) {
if (hashbin->hb_type & HB_LOCK)
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
free_func(queue);
if (hashbin->hb_type & HB_LOCK)
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
}
}
}
/* Cleanup local data */
hashbin->hb_current = NULL;
hashbin->magic = ~HB_MAGIC;
/* Release lock */
if (hashbin->hb_type & HB_LOCK)
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
/*
* Free the hashbin structure
*/
kfree(hashbin);
return 0;
}
| 168,344 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125 | void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
| 169,273 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.x = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.y = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
rect.width = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
rect.height = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189 | PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.x = Z_LVAL(lval);
} else {
rect.x = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.y = Z_LVAL(lval);
} else {
rect.y = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.width = Z_LVAL(lval);
} else {
rect.width = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.height = Z_LVAL(lval);
} else {
rect.height = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
| 166,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned long Segment::GetCount() const
{
return m_clusterCount;
}
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 Segment::GetCount() const
| 174,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ServiceWorkerPaymentInstrument::OnPaymentAppInvoked(
mojom::PaymentHandlerResponsePtr response) {
DCHECK(delegate_);
if (delegate_ != nullptr) {
delegate_->OnInstrumentDetailsReady(response->method_name,
response->stringified_details);
delegate_ = nullptr;
}
}
Commit Message: [Payment Handler] Don't wait for response from closed payment app.
Before this patch, tapping the back button on top of the payment handler
window on desktop would not affect the |response_helper_|, which would
continue waiting for a response from the payment app. The service worker
of the closed payment app could timeout after 5 minutes and invoke the
|response_helper_|. Depending on what else the user did afterwards, in
the best case scenario, the payment sheet would display a "Transaction
failed" error message. In the worst case scenario, the
|response_helper_| would be used after free.
This patch clears the |response_helper_| in the PaymentRequestState and
in the ServiceWorkerPaymentInstrument after the payment app is closed.
After this patch, the cancelled payment app does not show "Transaction
failed" and does not use memory after it was freed.
Bug: 956597
Change-Id: I64134b911a4f8c154cb56d537a8243a68a806394
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1588682
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654995}
CWE ID: CWE-416 | void ServiceWorkerPaymentInstrument::OnPaymentAppInvoked(
mojom::PaymentHandlerResponsePtr response) {
if (delegate_ != nullptr) {
delegate_->OnInstrumentDetailsReady(response->method_name,
response->stringified_details);
delegate_ = nullptr;
}
}
| 172,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: video_usercopy(struct file *file, unsigned int cmd, unsigned long arg,
v4l2_kioctl func)
{
char sbuf[128];
void *mbuf = NULL;
void *parg = NULL;
long err = -EINVAL;
int is_ext_ctrl;
size_t ctrls_size = 0;
void __user *user_ptr = NULL;
is_ext_ctrl = (cmd == VIDIOC_S_EXT_CTRLS || cmd == VIDIOC_G_EXT_CTRLS ||
cmd == VIDIOC_TRY_EXT_CTRLS);
/* Copy arguments into temp kernel buffer */
switch (_IOC_DIR(cmd)) {
case _IOC_NONE:
parg = NULL;
break;
case _IOC_READ:
case _IOC_WRITE:
case (_IOC_WRITE | _IOC_READ):
if (_IOC_SIZE(cmd) <= sizeof(sbuf)) {
parg = sbuf;
} else {
/* too big to allocate from stack */
mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL);
if (NULL == mbuf)
return -ENOMEM;
parg = mbuf;
}
err = -EFAULT;
if (_IOC_DIR(cmd) & _IOC_WRITE)
if (copy_from_user(parg, (void __user *)arg, _IOC_SIZE(cmd)))
goto out;
break;
}
if (is_ext_ctrl) {
struct v4l2_ext_controls *p = parg;
/* In case of an error, tell the caller that it wasn't
a specific control that caused it. */
p->error_idx = p->count;
user_ptr = (void __user *)p->controls;
if (p->count) {
ctrls_size = sizeof(struct v4l2_ext_control) * p->count;
/* Note: v4l2_ext_controls fits in sbuf[] so mbuf is still NULL. */
mbuf = kmalloc(ctrls_size, GFP_KERNEL);
err = -ENOMEM;
if (NULL == mbuf)
goto out_ext_ctrl;
err = -EFAULT;
if (copy_from_user(mbuf, user_ptr, ctrls_size))
goto out_ext_ctrl;
p->controls = mbuf;
}
}
/* call driver */
err = func(file, cmd, parg);
if (err == -ENOIOCTLCMD)
err = -EINVAL;
if (is_ext_ctrl) {
struct v4l2_ext_controls *p = parg;
p->controls = (void *)user_ptr;
if (p->count && err == 0 && copy_to_user(user_ptr, mbuf, ctrls_size))
err = -EFAULT;
goto out_ext_ctrl;
}
if (err < 0)
goto out;
out_ext_ctrl:
/* Copy results into user buffer */
switch (_IOC_DIR(cmd)) {
case _IOC_READ:
case (_IOC_WRITE | _IOC_READ):
if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd)))
err = -EFAULT;
break;
}
out:
kfree(mbuf);
return err;
}
Commit Message: [media] v4l: Share code between video_usercopy and video_ioctl2
The two functions are mostly identical. They handle the copy_from_user
and copy_to_user operations related with V4L2 ioctls and call the real
ioctl handler.
Create a __video_usercopy function that implements the core of
video_usercopy and video_ioctl2, and call that function from both.
Signed-off-by: Laurent Pinchart <[email protected]>
Acked-by: Hans Verkuil <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-399 | video_usercopy(struct file *file, unsigned int cmd, unsigned long arg,
| 168,916 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int InternalPageInfoBubbleView::GetDialogButtons() const {
return ui::DIALOG_BUTTON_NONE;
}
Commit Message: Desktop Page Info/Harmony: Show close button for internal pages.
The Harmony version of Page Info for internal Chrome pages (chrome://,
chrome-extension:// and view-source:// pages) show a close button. Update the
code to match this.
This patch also adds TestBrowserDialog tests for the latter two cases described
above (internal extension and view source pages).
See screenshot -
https://drive.google.com/file/d/18RZnMiHCu-rCX9N6DLUpu4mkFWguh1xm/view?usp=sharing
Bug: 535074
Change-Id: I55e5f1aa682fd4ec85f7b65ac88f5a4f5906fe53
Reviewed-on: https://chromium-review.googlesource.com/759624
Commit-Queue: Patti <[email protected]>
Reviewed-by: Trent Apted <[email protected]>
Cr-Commit-Position: refs/heads/master@{#516624}
CWE ID: CWE-704 | int InternalPageInfoBubbleView::GetDialogButtons() const {
| 172,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
xmlChar *name;
const xmlChar *ptr;
xmlChar cur;
xmlEntityPtr ent = NULL;
if ((str == NULL) || (*str == NULL))
return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '&')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringEntityRef: no name\n");
*str = ptr;
return(NULL);
}
if (*ptr != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Predefined entites override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL) {
xmlFree(name);
*str = ptr;
return(ent);
}
}
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ent == NULL) && (ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n",
name);
}
/* TODO ? check regressions ctxt->valid = 0; */
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) && (ent->content != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n",
name);
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
xmlFree(name);
*str = ptr;
return(ent);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
xmlChar *name;
const xmlChar *ptr;
xmlChar cur;
xmlEntityPtr ent = NULL;
if ((str == NULL) || (*str == NULL))
return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '&')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringEntityRef: no name\n");
*str = ptr;
return(NULL);
}
if (*ptr != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Predefined entites override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL) {
xmlFree(name);
*str = ptr;
return(ent);
}
}
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ent == NULL) && (ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(name);
return(NULL);
}
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n",
name);
}
/* TODO ? check regressions ctxt->valid = 0; */
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) && (ent->content != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n",
name);
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
xmlFree(name);
*str = ptr;
return(ent);
}
| 171,304 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
for (i = 1; i < argc; i++)
{
if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf(
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
if (argc >= 3)
{
if ((argc == 3) && (!strcmp(argv[1], "-t")))
{
test = 1;
action = argv[2];
}
else if (!strcmp(argv[1], "l2ping"))
{
action = argv[1];
output = argv[2];
}
#ifdef HAVE_EEZE_MOUNT
else
{
const char *s;
s = strrchr(argv[1], '/');
if ((!s) || (!s[1])) exit(1); /* eeze always uses complete path */
s++;
if (strcmp(s, "mount") && strcmp(s, "umount") && strcmp(s, "eject")) exit(1);
mnt = EINA_TRUE;
act = s;
action = argv[1];
}
#endif
}
else if (argc == 2)
{
action = argv[1];
}
else
{
exit(1);
}
if (!action) exit(1);
fprintf(stderr, "action %s %i\n", action, argc);
uid = getuid();
gid = getgid();
egid = getegid();
gn = getgroups(65536, gl);
if (gn < 0)
{
printf("ERROR: MEMBER OF MORE THAN 65536 GROUPS\n");
exit(3);
}
if (setuid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT PRIVILEGES\n");
exit(5);
}
if (setgid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT GROUP PRIVILEGES\n");
exit(7);
}
eina_init();
if (!auth_action_ok(action, gid, gl, gn, egid))
{
printf("ERROR: ACTION NOT ALLOWED: %s\n", action);
exit(10);
}
/* we can add more levels of auth here */
/* when mounting, this will match the exact path to the exe,
* as required in sysactions.conf
* this is intentionally pedantic for security
*/
cmd = eina_hash_find(actions, action);
if (!cmd)
{
printf("ERROR: UNDEFINED ACTION: %s\n", action);
exit(20);
}
if (!test && !strcmp(action, "l2ping"))
{
char tmp[128];
double latency;
latency = e_sys_l2ping(output);
eina_convert_dtoa(latency, tmp);
fputs(tmp, stdout);
return (latency < 0) ? 1 : 0;
}
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
#else
# define NOENV(x)
#endif
NOENV("IFS");
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
#else
# define NOENV(x)
#endif
NOENV("IFS");
NOENV("LD_PRELOAD");
NOENV("PYTHONPATH");
NOENV("LD_LIBRARY_PATH");
#ifdef HAVE_CLEARENV
clearenv();
#endif
/* set path and ifs to minimal defaults */
putenv("PATH=/bin:/usr/bin");
putenv("IFS= \t\n");
const char *p;
char *end;
unsigned long muid;
Eina_Bool nosuid, nodev, noexec, nuid;
nosuid = nodev = noexec = nuid = EINA_FALSE;
/* these are the only possible options which can be present here; check them strictly */
if (eina_strlcpy(buf, opts, sizeof(buf)) >= sizeof(buf)) return EINA_FALSE;
for (p = buf; p && p[1]; p = strchr(p + 1, ','))
{
if (p[0] == ',') p++;
#define CMP(OPT) \
if (!strncmp(p, OPT, sizeof(OPT) - 1))
CMP("nosuid,")
{
nosuid = EINA_TRUE;
continue;
}
CMP("nodev,")
{
nodev = EINA_TRUE;
continue;
}
CMP("noexec,")
{
noexec = EINA_TRUE;
continue;
}
CMP("utf8,") continue;
CMP("utf8=0,") continue;
CMP("utf8=1,") continue;
CMP("iocharset=utf8,") continue;
CMP("uid=")
{
p += 4;
errno = 0;
muid = strtoul(p, &end, 10);
if (muid == ULONG_MAX) return EINA_FALSE;
if (errno) return EINA_FALSE;
if (end[0] != ',') return EINA_FALSE;
if (muid != uid) return EINA_FALSE;
nuid = EINA_TRUE;
continue;
}
return EINA_FALSE;
}
if ((!nosuid) || (!nodev) || (!noexec) || (!nuid)) return EINA_FALSE;
return EINA_TRUE;
}
Commit Message:
CWE ID: CWE-264 | main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
for (i = 1; i < argc; i++)
{
if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf(
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
if (argc >= 3)
{
if ((argc == 3) && (!strcmp(argv[1], "-t")))
{
test = 1;
action = argv[2];
}
else if (!strcmp(argv[1], "l2ping"))
{
action = argv[1];
output = argv[2];
}
#ifdef HAVE_EEZE_MOUNT
else
{
const char *s;
s = strrchr(argv[1], '/');
if ((!s) || (!s[1])) exit(1); /* eeze always uses complete path */
s++;
if (strcmp(s, "mount") && strcmp(s, "umount") && strcmp(s, "eject")) exit(1);
mnt = EINA_TRUE;
act = s;
action = argv[1];
}
#endif
}
else if (argc == 2)
{
action = argv[1];
}
else
{
exit(1);
}
if (!action) exit(1);
fprintf(stderr, "action %s %i\n", action, argc);
uid = getuid();
gid = getgid();
egid = getegid();
gn = getgroups(65536, gl);
if (gn < 0)
{
printf("ERROR: MEMBER OF MORE THAN 65536 GROUPS\n");
exit(3);
}
if (setuid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT PRIVILEGES\n");
exit(5);
}
if (setgid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT GROUP PRIVILEGES\n");
exit(7);
}
eina_init();
if (!auth_action_ok(action, gid, gl, gn, egid))
{
printf("ERROR: ACTION NOT ALLOWED: %s\n", action);
exit(10);
}
/* we can add more levels of auth here */
/* when mounting, this will match the exact path to the exe,
* as required in sysactions.conf
* this is intentionally pedantic for security
*/
cmd = eina_hash_find(actions, action);
if (!cmd)
{
printf("ERROR: UNDEFINED ACTION: %s\n", action);
exit(20);
}
if (!test && !strcmp(action, "l2ping"))
{
char tmp[128];
double latency;
latency = e_sys_l2ping(output);
eina_convert_dtoa(latency, tmp);
fputs(tmp, stdout);
return (latency < 0) ? 1 : 0;
}
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
#else
# define NOENV(x)
#endif
NOENV("IFS");
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
/* pass 1 - just nuke known dangerous env vars brutally if possible via
* unsetenv(). if you don't have unsetenv... there's pass 2 and 3 */
NOENV("IFS");
NOENV("CDPATH");
NOENV("LOCALDOMAIN");
NOENV("RES_OPTIONS");
NOENV("HOSTALIASES");
NOENV("NLSPATH");
NOENV("PATH_LOCALE");
NOENV("COLORTERM");
NOENV("LANG");
NOENV("LANGUAGE");
NOENV("LINGUAS");
NOENV("TERM");
NOENV("LD_PRELOAD");
NOENV("LD_LIBRARY_PATH");
NOENV("SHLIB_PATH");
NOENV("LIBPATH");
NOENV("AUTHSTATE");
NOENV("DYLD_*");
NOENV("KRB_CONF*");
NOENV("KRBCONFDIR");
NOENV("KRBTKFILE");
NOENV("KRB5_CONFIG*");
NOENV("KRB5_KTNAME");
NOENV("VAR_ACE");
NOENV("USR_ACE");
NOENV("DLC_ACE");
NOENV("TERMINFO");
NOENV("TERMINFO_DIRS");
NOENV("TERMPATH");
NOENV("TERMCAP");
NOENV("ENV");
NOENV("BASH_ENV");
NOENV("PS4");
NOENV("GLOBIGNORE");
NOENV("SHELLOPTS");
NOENV("JAVA_TOOL_OPTIONS");
NOENV("PERLIO_DEBUG");
NOENV("PERLLIB");
NOENV("PERL5LIB");
NOENV("PERL5OPT");
NOENV("PERL5DB");
NOENV("FPATH");
NOENV("NULLCMD");
NOENV("READNULLCMD");
NOENV("ZDOTDIR");
NOENV("TMPPREFIX");
NOENV("PYTHONPATH");
NOENV("PYTHONHOME");
NOENV("PYTHONINSPECT");
NOENV("RUBYLIB");
NOENV("RUBYOPT");
# ifdef HAVE_ENVIRON
if (environ)
{
int again;
char *tmp, *p;
/* go over environment array again and again... safely */
do
{
again = 0;
/* walk through and find first entry that we don't like */
for (i = 0; environ[i]; i++)
{
/* if it begins with any of these, it's possibly nasty */
if ((!strncmp(environ[i], "LD_", 3)) ||
(!strncmp(environ[i], "_RLD_", 5)) ||
(!strncmp(environ[i], "LC_", 3)) ||
(!strncmp(environ[i], "LDR_", 3)))
{
/* unset it */
tmp = strdup(environ[i]);
if (!tmp) abort();
p = strchr(tmp, '=');
if (!p) abort();
*p = 0;
NOENV(p);
free(tmp);
/* and mark our do to try again from the start in case
* unsetenv changes environ ptr */
again = 1;
break;
}
}
}
while (again);
}
# endif
#endif
/* pass 2 - clear entire environment so it doesn't exist at all. if you
* can't do this... you're possibly in trouble... but the worst is still
* fixed in pass 3 */
#ifdef HAVE_CLEARENV
clearenv();
#else
# ifdef HAVE_ENVIRON
environ = NULL;
# endif
#endif
/* pass 3 - set path and ifs to minimal defaults */
putenv("PATH=/bin:/usr/bin");
putenv("IFS= \t\n");
const char *p;
char *end;
unsigned long muid;
Eina_Bool nosuid, nodev, noexec, nuid;
nosuid = nodev = noexec = nuid = EINA_FALSE;
/* these are the only possible options which can be present here; check them strictly */
if (eina_strlcpy(buf, opts, sizeof(buf)) >= sizeof(buf)) return EINA_FALSE;
for (p = buf; p && p[1]; p = strchr(p + 1, ','))
{
if (p[0] == ',') p++;
#define CMP(OPT) \
if (!strncmp(p, OPT, sizeof(OPT) - 1))
CMP("nosuid,")
{
nosuid = EINA_TRUE;
continue;
}
CMP("nodev,")
{
nodev = EINA_TRUE;
continue;
}
CMP("noexec,")
{
noexec = EINA_TRUE;
continue;
}
CMP("utf8,") continue;
CMP("utf8=0,") continue;
CMP("utf8=1,") continue;
CMP("iocharset=utf8,") continue;
CMP("uid=")
{
p += 4;
errno = 0;
muid = strtoul(p, &end, 10);
if (muid == ULONG_MAX) return EINA_FALSE;
if (errno) return EINA_FALSE;
if (end[0] != ',') return EINA_FALSE;
if (muid != uid) return EINA_FALSE;
nuid = EINA_TRUE;
continue;
}
return EINA_FALSE;
}
if ((!nosuid) || (!nodev) || (!noexec) || (!nuid)) return EINA_FALSE;
return EINA_TRUE;
}
| 165,513 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftMPEG2::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20 | void SoftMPEG2::setDecodeArgs(
bool SoftMPEG2::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20 | static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0 && xhash_get(out->states, rkey) == (void*) conn_INPROGRESS) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
| 165,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cxusb_ctrl_msg(struct dvb_usb_device *d,
u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)
{
struct cxusb_state *st = d->priv;
int ret, wo;
if (1 + wlen > MAX_XFER_SIZE) {
warn("i2c wr: len=%d is too big!\n", wlen);
return -EOPNOTSUPP;
}
wo = (rbuf == NULL || rlen == 0); /* write-only */
mutex_lock(&d->data_mutex);
st->data[0] = cmd;
memcpy(&st->data[1], wbuf, wlen);
if (wo)
ret = dvb_usb_generic_write(d, st->data, 1 + wlen);
else
ret = dvb_usb_generic_rw(d, st->data, 1 + wlen,
rbuf, rlen, 0);
mutex_unlock(&d->data_mutex);
return ret;
}
Commit Message: [media] cxusb: Use a dma capable buffer also for reading
Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack")
added a kmalloc'ed bounce buffer for writes, but missed to do the same
for reads. As the read only happens after the write is finished, we can
reuse the same buffer.
As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling
it using the dvb_usb_generic_read wrapper function.
Signed-off-by: Stefan Brüns <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int cxusb_ctrl_msg(struct dvb_usb_device *d,
u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)
{
struct cxusb_state *st = d->priv;
int ret;
if (1 + wlen > MAX_XFER_SIZE) {
warn("i2c wr: len=%d is too big!\n", wlen);
return -EOPNOTSUPP;
}
if (rlen > MAX_XFER_SIZE) {
warn("i2c rd: len=%d is too big!\n", rlen);
return -EOPNOTSUPP;
}
mutex_lock(&d->data_mutex);
st->data[0] = cmd;
memcpy(&st->data[1], wbuf, wlen);
ret = dvb_usb_generic_rw(d, st->data, 1 + wlen, st->data, rlen, 0);
if (!ret && rbuf && rlen)
memcpy(rbuf, st->data, rlen);
mutex_unlock(&d->data_mutex);
return ret;
}
| 168,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
{
struct mapped_device *md;
md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
if (test_bit(DMF_FREEING, &md->flags) ||
dm_deleting_md(md))
return NULL;
dm_get(md);
return md;
}
Commit Message: dm: fix race between dm_get_from_kobject() and __dm_destroy()
The following BUG_ON was hit when testing repeat creation and removal of
DM devices:
kernel BUG at drivers/md/dm.c:2919!
CPU: 7 PID: 750 Comm: systemd-udevd Not tainted 4.1.44
Call Trace:
[<ffffffff81649e8b>] dm_get_from_kobject+0x34/0x3a
[<ffffffff81650ef1>] dm_attr_show+0x2b/0x5e
[<ffffffff817b46d1>] ? mutex_lock+0x26/0x44
[<ffffffff811df7f5>] sysfs_kf_seq_show+0x83/0xcf
[<ffffffff811de257>] kernfs_seq_show+0x23/0x25
[<ffffffff81199118>] seq_read+0x16f/0x325
[<ffffffff811de994>] kernfs_fop_read+0x3a/0x13f
[<ffffffff8117b625>] __vfs_read+0x26/0x9d
[<ffffffff8130eb59>] ? security_file_permission+0x3c/0x44
[<ffffffff8117bdb8>] ? rw_verify_area+0x83/0xd9
[<ffffffff8117be9d>] vfs_read+0x8f/0xcf
[<ffffffff81193e34>] ? __fdget_pos+0x12/0x41
[<ffffffff8117c686>] SyS_read+0x4b/0x76
[<ffffffff817b606e>] system_call_fastpath+0x12/0x71
The bug can be easily triggered, if an extra delay (e.g. 10ms) is added
between the test of DMF_FREEING & DMF_DELETING and dm_get() in
dm_get_from_kobject().
To fix it, we need to ensure the test of DMF_FREEING & DMF_DELETING and
dm_get() are done in an atomic way, so _minor_lock is used.
The other callers of dm_get() have also been checked to be OK: some
callers invoke dm_get() under _minor_lock, some callers invoke it under
_hash_lock, and dm_start_request() invoke it after increasing
md->open_count.
Cc: [email protected]
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Mike Snitzer <[email protected]>
CWE ID: CWE-362 | struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
{
struct mapped_device *md;
md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
spin_lock(&_minor_lock);
if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
md = NULL;
goto out;
}
dm_get(md);
out:
spin_unlock(&_minor_lock);
return md;
}
| 169,411 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mutt_b64_decode(char *out, const char *in)
{
int len = 0;
unsigned char digit4;
do
{
const unsigned char digit1 = in[0];
if ((digit1 > 127) || (base64val(digit1) == BAD))
return -1;
const unsigned char digit2 = in[1];
if ((digit2 > 127) || (base64val(digit2) == BAD))
return -1;
const unsigned char digit3 = in[2];
if ((digit3 > 127) || ((digit3 != '=') && (base64val(digit3) == BAD)))
return -1;
digit4 = in[3];
if ((digit4 > 127) || ((digit4 != '=') && (base64val(digit4) == BAD)))
return -1;
in += 4;
/* digits are already sanity-checked */
*out++ = (base64val(digit1) << 2) | (base64val(digit2) >> 4);
len++;
if (digit3 != '=')
{
*out++ = ((base64val(digit2) << 4) & 0xf0) | (base64val(digit3) >> 2);
len++;
if (digit4 != '=')
{
*out++ = ((base64val(digit3) << 6) & 0xc0) | base64val(digit4);
len++;
}
}
} while (*in && digit4 != '=');
return len;
}
Commit Message: Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.
CWE ID: CWE-119 | int mutt_b64_decode(char *out, const char *in)
int mutt_b64_decode(char *out, const char *in, size_t olen)
{
int len = 0;
unsigned char digit4;
do
{
const unsigned char digit1 = in[0];
if ((digit1 > 127) || (base64val(digit1) == BAD))
return -1;
const unsigned char digit2 = in[1];
if ((digit2 > 127) || (base64val(digit2) == BAD))
return -1;
const unsigned char digit3 = in[2];
if ((digit3 > 127) || ((digit3 != '=') && (base64val(digit3) == BAD)))
return -1;
digit4 = in[3];
if ((digit4 > 127) || ((digit4 != '=') && (base64val(digit4) == BAD)))
return -1;
in += 4;
/* digits are already sanity-checked */
if (len == olen)
return len;
*out++ = (base64val(digit1) << 2) | (base64val(digit2) >> 4);
len++;
if (digit3 != '=')
{
if (len == olen)
return len;
*out++ = ((base64val(digit2) << 4) & 0xf0) | (base64val(digit3) >> 2);
len++;
if (digit4 != '=')
{
if (len == olen)
return len;
*out++ = ((base64val(digit3) << 6) & 0xc0) | base64val(digit4);
len++;
}
}
} while (*in && digit4 != '=');
return len;
}
| 169,128 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long BlockGroup::GetDurationTimeCode() const
{
return m_duration;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long BlockGroup::GetDurationTimeCode() const
| 174,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fdct4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct4x4_c(in, out, stride);
}
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 fdct4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
void fdct4x4_ref(const int16_t *in, tran_low_t *out, int stride,
int tx_type) {
vpx_fdct4x4_c(in, out, stride);
}
| 174,557 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip_checkentry(&e->ip))
return -EINVAL;
err = xt_check_entry_offsets(e, e->target_offset, e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264 | check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip_checkentry(&e->ip))
return -EINVAL;
err = xt_check_entry_offsets(e, e->elems, e->target_offset,
e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,218 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int logi_dj_ll_raw_request(struct hid_device *hid,
unsigned char reportnum, __u8 *buf,
size_t count, unsigned char report_type,
int reqtype)
{
struct dj_device *djdev = hid->driver_data;
struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev;
u8 *out_buf;
int ret;
if (buf[0] != REPORT_TYPE_LEDS)
return -EINVAL;
out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC);
if (!out_buf)
return -ENOMEM;
if (count < DJREPORT_SHORT_LENGTH - 2)
count = DJREPORT_SHORT_LENGTH - 2;
out_buf[0] = REPORT_ID_DJ_SHORT;
out_buf[1] = djdev->device_index;
memcpy(out_buf + 2, buf, count);
ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf,
DJREPORT_SHORT_LENGTH, report_type, reqtype);
kfree(out_buf);
return ret;
}
Commit Message: HID: logitech: fix bounds checking on LED report size
The check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request()
is wrong; the current check doesn't make any sense -- the report allocated
by HID core in hid_hw_raw_request() can be much larger than
DJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't
handle this properly at all.
Fix the check by actually trimming down the report size properly if it is
too large.
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119 | static int logi_dj_ll_raw_request(struct hid_device *hid,
unsigned char reportnum, __u8 *buf,
size_t count, unsigned char report_type,
int reqtype)
{
struct dj_device *djdev = hid->driver_data;
struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev;
u8 *out_buf;
int ret;
if (buf[0] != REPORT_TYPE_LEDS)
return -EINVAL;
out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC);
if (!out_buf)
return -ENOMEM;
if (count > DJREPORT_SHORT_LENGTH - 2)
count = DJREPORT_SHORT_LENGTH - 2;
out_buf[0] = REPORT_ID_DJ_SHORT;
out_buf[1] = djdev->device_index;
memcpy(out_buf + 2, buf, count);
ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf,
DJREPORT_SHORT_LENGTH, report_type, reqtype);
kfree(out_buf);
return ret;
}
| 166,376 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ShellBrowserMain(const content::MainFunctionParams& parameters) {
bool layout_test_mode =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);
base::ScopedTempDir browser_context_path_for_layout_tests;
if (layout_test_mode) {
CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());
CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kContentShellDataPath,
browser_context_path_for_layout_tests.path().MaybeAsASCII());
}
scoped_ptr<content::BrowserMainRunner> main_runner_(
content::BrowserMainRunner::Create());
int exit_code = main_runner_->Initialize(parameters);
if (exit_code >= 0)
return exit_code;
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kCheckLayoutTestSysDeps)) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
main_runner_->Shutdown();
return 0;
}
if (layout_test_mode) {
content::WebKitTestController test_controller;
std::string test_string;
CommandLine::StringVector args =
CommandLine::ForCurrentProcess()->GetArgs();
size_t command_line_position = 0;
bool ran_at_least_once = false;
#if defined(OS_ANDROID)
std::cout << "#READY\n";
std::cout.flush();
#endif
while (GetNextTest(args, &command_line_position, &test_string)) {
if (test_string.empty())
continue;
if (test_string == "QUIT")
break;
bool enable_pixel_dumps;
std::string pixel_hash;
FilePath cwd;
GURL test_url = GetURLForLayoutTest(
test_string, &cwd, &enable_pixel_dumps, &pixel_hash);
if (!content::WebKitTestController::Get()->PrepareForLayoutTest(
test_url, cwd, enable_pixel_dumps, pixel_hash)) {
break;
}
ran_at_least_once = true;
main_runner_->Run();
if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())
break;
}
if (!ran_at_least_once) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
}
exit_code = 0;
} else {
exit_code = main_runner_->Run();
}
main_runner_->Shutdown();
return exit_code;
}
Commit Message: [content shell] reset the CWD after each layout test
BUG=111316
[email protected]
Review URL: https://codereview.chromium.org/11633017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173906 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | int ShellBrowserMain(const content::MainFunctionParams& parameters) {
bool layout_test_mode =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);
base::ScopedTempDir browser_context_path_for_layout_tests;
if (layout_test_mode) {
CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());
CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kContentShellDataPath,
browser_context_path_for_layout_tests.path().MaybeAsASCII());
}
scoped_ptr<content::BrowserMainRunner> main_runner_(
content::BrowserMainRunner::Create());
int exit_code = main_runner_->Initialize(parameters);
if (exit_code >= 0)
return exit_code;
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kCheckLayoutTestSysDeps)) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
main_runner_->Shutdown();
return 0;
}
if (layout_test_mode) {
content::WebKitTestController test_controller;
std::string test_string;
CommandLine::StringVector args =
CommandLine::ForCurrentProcess()->GetArgs();
size_t command_line_position = 0;
bool ran_at_least_once = false;
#if defined(OS_ANDROID)
std::cout << "#READY\n";
std::cout.flush();
#endif
FilePath original_cwd;
{
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
file_util::GetCurrentDirectory(&original_cwd);
}
while (GetNextTest(args, &command_line_position, &test_string)) {
if (test_string.empty())
continue;
if (test_string == "QUIT")
break;
bool enable_pixel_dumps;
std::string pixel_hash;
FilePath cwd;
GURL test_url = GetURLForLayoutTest(
test_string, &cwd, &enable_pixel_dumps, &pixel_hash);
if (!content::WebKitTestController::Get()->PrepareForLayoutTest(
test_url, cwd, enable_pixel_dumps, pixel_hash)) {
break;
}
ran_at_least_once = true;
main_runner_->Run();
{
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
file_util::SetCurrentDirectory(original_cwd);
}
if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())
break;
}
if (!ran_at_least_once) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
}
exit_code = 0;
} else {
exit_code = main_runner_->Run();
}
main_runner_->Shutdown();
return exit_code;
}
| 171,469 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void qrio_prstcfg(u8 bit, u8 mode)
{
u32 prstcfg;
u8 i;
void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE;
prstcfg = in_be32(qrio_base + PRSTCFG_OFF);
for (i = 0; i < 2; i++) {
if (mode & (1<<i))
set_bit(2*bit+i, &prstcfg);
else
clear_bit(2*bit+i, &prstcfg);
}
out_be32(qrio_base + PRSTCFG_OFF, prstcfg);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | void qrio_prstcfg(u8 bit, u8 mode)
{
u32 prstcfg;
u8 i;
void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE;
prstcfg = in_be32(qrio_base + PRSTCFG_OFF);
for (i = 0; i < 2; i++) {
if (mode & (1 << i))
set_bit(2 * bit + i, &prstcfg);
else
clear_bit(2 * bit + i, &prstcfg);
}
out_be32(qrio_base + PRSTCFG_OFF, prstcfg);
}
| 169,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ber_parse_header(STREAM s, int tagval, int *length)
{
int tag, len;
if (tagval > 0xff)
{
in_uint16_be(s, tag);
}
else
{
in_uint8(s, tag);
}
if (tag != tagval)
{
logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag);
return False;
}
in_uint8(s, len);
if (len & 0x80)
{
len &= ~0x80;
*length = 0;
while (len--)
next_be(s, *length);
}
else
*length = len;
return s_check(s);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | ber_parse_header(STREAM s, int tagval, int *length)
ber_parse_header(STREAM s, int tagval, uint32 *length)
{
int tag, len;
if (tagval > 0xff)
{
in_uint16_be(s, tag);
}
else
{
in_uint8(s, tag);
}
if (tag != tagval)
{
logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag);
return False;
}
in_uint8(s, len);
if (len & 0x80)
{
len &= ~0x80;
*length = 0;
while (len--)
next_be(s, *length);
}
else
*length = len;
return s_check(s);
}
| 169,794 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, private);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
Commit Message: crypto: algif_skcipher - Require setkey before accept(2)
Some cipher implementations will crash if you try to use them
without calling setkey first. This patch adds a check so that
the accept(2) call will fail with -ENOKEY if setkey hasn't been
done on the socket yet.
Cc: [email protected]
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
CWE ID: CWE-476 | static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_tfm *tfm = private;
struct crypto_skcipher *skcipher = tfm->skcipher;
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(skcipher);
if (!tfm->has_key)
return -ENOKEY;
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(skcipher),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(skcipher));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, skcipher);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
| 167,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __sys_sendmsg(struct socket *sock, struct msghdr __user *msg,
struct msghdr *msg_sys, unsigned flags,
struct used_address *used_address)
{
struct compat_msghdr __user *msg_compat =
(struct compat_msghdr __user *)msg;
struct sockaddr_storage address;
struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
unsigned char ctl[sizeof(struct cmsghdr) + 20]
__attribute__ ((aligned(sizeof(__kernel_size_t))));
/* 20 is size of ipv6_pktinfo */
unsigned char *ctl_buf = ctl;
int err, ctl_len, iov_size, total_len;
err = -EFAULT;
if (MSG_CMSG_COMPAT & flags) {
if (get_compat_msghdr(msg_sys, msg_compat))
return -EFAULT;
} else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr)))
return -EFAULT;
/* do not move before msg_sys is valid */
err = -EMSGSIZE;
if (msg_sys->msg_iovlen > UIO_MAXIOV)
goto out;
/* Check whether to allocate the iovec area */
err = -ENOMEM;
iov_size = msg_sys->msg_iovlen * sizeof(struct iovec);
if (msg_sys->msg_iovlen > UIO_FASTIOV) {
iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL);
if (!iov)
goto out;
}
/* This will also move the address data into kernel space */
if (MSG_CMSG_COMPAT & flags) {
err = verify_compat_iovec(msg_sys, iov,
(struct sockaddr *)&address,
VERIFY_READ);
} else
err = verify_iovec(msg_sys, iov,
(struct sockaddr *)&address,
VERIFY_READ);
if (err < 0)
goto out_freeiov;
total_len = err;
err = -ENOBUFS;
if (msg_sys->msg_controllen > INT_MAX)
goto out_freeiov;
ctl_len = msg_sys->msg_controllen;
if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
err =
cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
sizeof(ctl));
if (err)
goto out_freeiov;
ctl_buf = msg_sys->msg_control;
ctl_len = msg_sys->msg_controllen;
} else if (ctl_len) {
if (ctl_len > sizeof(ctl)) {
ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
if (ctl_buf == NULL)
goto out_freeiov;
}
err = -EFAULT;
/*
* Careful! Before this, msg_sys->msg_control contains a user pointer.
* Afterwards, it will be a kernel pointer. Thus the compiler-assisted
* checking falls down on this.
*/
if (copy_from_user(ctl_buf,
(void __user __force *)msg_sys->msg_control,
ctl_len))
goto out_freectl;
msg_sys->msg_control = ctl_buf;
}
msg_sys->msg_flags = flags;
if (sock->file->f_flags & O_NONBLOCK)
msg_sys->msg_flags |= MSG_DONTWAIT;
/*
* If this is sendmmsg() and current destination address is same as
* previously succeeded address, omit asking LSM's decision.
* used_address->name_len is initialized to UINT_MAX so that the first
* destination address never matches.
*/
if (used_address && used_address->name_len == msg_sys->msg_namelen &&
!memcmp(&used_address->name, msg->msg_name,
used_address->name_len)) {
err = sock_sendmsg_nosec(sock, msg_sys, total_len);
goto out_freectl;
}
err = sock_sendmsg(sock, msg_sys, total_len);
/*
* If this is sendmmsg() and sending to current destination address was
* successful, remember it.
*/
if (used_address && err >= 0) {
used_address->name_len = msg_sys->msg_namelen;
memcpy(&used_address->name, msg->msg_name,
used_address->name_len);
}
out_freectl:
if (ctl_buf != ctl)
sock_kfree_s(sock->sk, ctl_buf, ctl_len);
out_freeiov:
if (iov != iovstack)
sock_kfree_s(sock->sk, iov, iov_size);
out:
return err;
}
Commit Message: sendmmsg/sendmsg: fix unsafe user pointer access
Dereferencing a user pointer directly from kernel-space without going
through the copy_from_user family of functions is a bad idea. Two of
such usages can be found in the sendmsg code path called from sendmmsg,
added by
commit c71d8ebe7a4496fb7231151cb70a6baa0cb56f9a upstream.
commit 5b47b8038f183b44d2d8ff1c7d11a5c1be706b34 in the 3.0-stable tree.
Usages are performed through memcmp() and memcpy() directly. Fix those
by using the already copied msg_sys structure instead of the __user *msg
structure. Note that msg_sys can be set to NULL by verify_compat_iovec()
or verify_iovec(), which requires additional NULL pointer checks.
Signed-off-by: Mathieu Desnoyers <[email protected]>
Signed-off-by: David Goulet <[email protected]>
CC: Tetsuo Handa <[email protected]>
CC: Anton Blanchard <[email protected]>
CC: David S. Miller <[email protected]>
CC: stable <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int __sys_sendmsg(struct socket *sock, struct msghdr __user *msg,
struct msghdr *msg_sys, unsigned flags,
struct used_address *used_address)
{
struct compat_msghdr __user *msg_compat =
(struct compat_msghdr __user *)msg;
struct sockaddr_storage address;
struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
unsigned char ctl[sizeof(struct cmsghdr) + 20]
__attribute__ ((aligned(sizeof(__kernel_size_t))));
/* 20 is size of ipv6_pktinfo */
unsigned char *ctl_buf = ctl;
int err, ctl_len, iov_size, total_len;
err = -EFAULT;
if (MSG_CMSG_COMPAT & flags) {
if (get_compat_msghdr(msg_sys, msg_compat))
return -EFAULT;
} else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr)))
return -EFAULT;
/* do not move before msg_sys is valid */
err = -EMSGSIZE;
if (msg_sys->msg_iovlen > UIO_MAXIOV)
goto out;
/* Check whether to allocate the iovec area */
err = -ENOMEM;
iov_size = msg_sys->msg_iovlen * sizeof(struct iovec);
if (msg_sys->msg_iovlen > UIO_FASTIOV) {
iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL);
if (!iov)
goto out;
}
/* This will also move the address data into kernel space */
if (MSG_CMSG_COMPAT & flags) {
err = verify_compat_iovec(msg_sys, iov,
(struct sockaddr *)&address,
VERIFY_READ);
} else
err = verify_iovec(msg_sys, iov,
(struct sockaddr *)&address,
VERIFY_READ);
if (err < 0)
goto out_freeiov;
total_len = err;
err = -ENOBUFS;
if (msg_sys->msg_controllen > INT_MAX)
goto out_freeiov;
ctl_len = msg_sys->msg_controllen;
if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
err =
cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
sizeof(ctl));
if (err)
goto out_freeiov;
ctl_buf = msg_sys->msg_control;
ctl_len = msg_sys->msg_controllen;
} else if (ctl_len) {
if (ctl_len > sizeof(ctl)) {
ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
if (ctl_buf == NULL)
goto out_freeiov;
}
err = -EFAULT;
/*
* Careful! Before this, msg_sys->msg_control contains a user pointer.
* Afterwards, it will be a kernel pointer. Thus the compiler-assisted
* checking falls down on this.
*/
if (copy_from_user(ctl_buf,
(void __user __force *)msg_sys->msg_control,
ctl_len))
goto out_freectl;
msg_sys->msg_control = ctl_buf;
}
msg_sys->msg_flags = flags;
if (sock->file->f_flags & O_NONBLOCK)
msg_sys->msg_flags |= MSG_DONTWAIT;
/*
* If this is sendmmsg() and current destination address is same as
* previously succeeded address, omit asking LSM's decision.
* used_address->name_len is initialized to UINT_MAX so that the first
* destination address never matches.
*/
if (used_address && msg_sys->msg_name &&
used_address->name_len == msg_sys->msg_namelen &&
!memcmp(&used_address->name, msg_sys->msg_name,
used_address->name_len)) {
err = sock_sendmsg_nosec(sock, msg_sys, total_len);
goto out_freectl;
}
err = sock_sendmsg(sock, msg_sys, total_len);
/*
* If this is sendmmsg() and sending to current destination address was
* successful, remember it.
*/
if (used_address && err >= 0) {
used_address->name_len = msg_sys->msg_namelen;
if (msg_sys->msg_name)
memcpy(&used_address->name, msg_sys->msg_name,
used_address->name_len);
}
out_freectl:
if (ctl_buf != ctl)
sock_kfree_s(sock->sk, ctl_buf, ctl_len);
out_freeiov:
if (iov != iovstack)
sock_kfree_s(sock->sk, iov, iov_size);
out:
return err;
}
| 165,680 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint32 ResourceTracker::GetLiveObjectsForInstance(
PP_Instance instance) const {
InstanceMap::const_iterator found = instance_map_.find(instance);
if (found == instance_map_.end())
return 0;
return static_cast<uint32>(found->second->resources.size() +
found->second->object_vars.size());
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | uint32 ResourceTracker::GetLiveObjectsForInstance(
PP_Instance instance) const {
InstanceMap::const_iterator found = instance_map_.find(instance);
if (found == instance_map_.end())
return 0;
return static_cast<uint32>(found->second->ref_resources.size() +
found->second->object_vars.size());
}
| 170,418 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int ret;
int copylen;
ret = -EOPNOTSUPP;
if (m->msg_flags&MSG_OOB)
goto read_error;
skb = skb_recv_datagram(sk, flags, 0 , &ret);
if (!skb)
goto read_error;
copylen = skb->len;
if (len < copylen) {
m->msg_flags |= MSG_TRUNC;
copylen = len;
}
ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);
if (ret)
goto out_free;
ret = (flags & MSG_TRUNC) ? skb->len : copylen;
out_free:
skb_free_datagram(sk, skb);
caif_check_flow_release(sk);
return ret;
read_error:
return ret;
}
Commit Message: caif: Fix missing msg_namelen update in caif_seqpkt_recvmsg()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about caif_seqpkt_recvmsg() not filling the msg_name in case it was
set.
Cc: Sjur Braendeland <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int ret;
int copylen;
ret = -EOPNOTSUPP;
if (m->msg_flags&MSG_OOB)
goto read_error;
m->msg_namelen = 0;
skb = skb_recv_datagram(sk, flags, 0 , &ret);
if (!skb)
goto read_error;
copylen = skb->len;
if (len < copylen) {
m->msg_flags |= MSG_TRUNC;
copylen = len;
}
ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);
if (ret)
goto out_free;
ret = (flags & MSG_TRUNC) ? skb->len : copylen;
out_free:
skb_free_datagram(sk, skb);
caif_check_flow_release(sk);
return ret;
read_error:
return ret;
}
| 166,040 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int efx_probe_all(struct efx_nic *efx)
{
int rc;
rc = efx_probe_nic(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create NIC\n");
goto fail1;
}
rc = efx_probe_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create port\n");
goto fail2;
}
efx->rxq_entries = efx->txq_entries = EFX_DEFAULT_DMAQ_SIZE;
rc = efx_probe_channels(efx);
if (rc)
goto fail3;
rc = efx_probe_filters(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create filter tables\n");
goto fail4;
}
return 0;
fail4:
efx_remove_channels(efx);
fail3:
efx_remove_port(efx);
fail2:
efx_remove_nic(efx);
fail1:
return rc;
}
Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size
[ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ]
Currently an skb requiring TSO may not fit within a minimum-size TX
queue. The TX queue selected for the skb may stall and trigger the TX
watchdog repeatedly (since the problem skb will be retried after the
TX reset). This issue is designated as CVE-2012-3412.
Set the maximum number of TSO segments for our devices to 100. This
should make no difference to behaviour unless the actual MSS is less
than about 700. Increase the minimum TX queue size accordingly to
allow for 2 worst-case skbs, so that there will definitely be space
to add an skb after we wake a queue.
To avoid invalidating existing configurations, change
efx_ethtool_set_ringparam() to fix up values that are too small rather
than returning -EINVAL.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
CWE ID: CWE-189 | static int efx_probe_all(struct efx_nic *efx)
{
int rc;
rc = efx_probe_nic(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create NIC\n");
goto fail1;
}
rc = efx_probe_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create port\n");
goto fail2;
}
BUILD_BUG_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_RXQ_MIN_ENT);
if (WARN_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_TXQ_MIN_ENT(efx))) {
rc = -EINVAL;
goto fail3;
}
efx->rxq_entries = efx->txq_entries = EFX_DEFAULT_DMAQ_SIZE;
rc = efx_probe_channels(efx);
if (rc)
goto fail3;
rc = efx_probe_filters(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create filter tables\n");
goto fail4;
}
return 0;
fail4:
efx_remove_channels(efx);
fail3:
efx_remove_port(efx);
fail2:
efx_remove_nic(efx);
fail1:
return rc;
}
| 165,584 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_asntime_into_isotime (unsigned char const **buf, size_t *len,
ksba_isotime_t isotime)
{
struct tag_info ti;
gpg_error_t err;
err = _ksba_ber_parse_tl (buf, len, &ti);
if (err)
;
else if ( !(ti.class == CLASS_UNIVERSAL
&& (ti.tag == TYPE_UTC_TIME || ti.tag == TYPE_GENERALIZED_TIME)
&& !ti.is_constructed) )
err = gpg_error (GPG_ERR_INV_OBJ);
else if (!(err = _ksba_asntime_to_iso (*buf, ti.length,
ti.tag == TYPE_UTC_TIME, isotime)))
parse_skip (buf, len, &ti);
}
Commit Message:
CWE ID: CWE-20 | parse_asntime_into_isotime (unsigned char const **buf, size_t *len,
ksba_isotime_t isotime)
{
struct tag_info ti;
gpg_error_t err;
err = _ksba_ber_parse_tl (buf, len, &ti);
if (err)
;
else if ( !(ti.class == CLASS_UNIVERSAL
&& (ti.tag == TYPE_UTC_TIME || ti.tag == TYPE_GENERALIZED_TIME)
&& !ti.is_constructed) )
err = gpg_error (GPG_ERR_INV_OBJ);
else if (ti.length > *len)
err = gpg_error (GPG_ERR_INV_BER);
else if (!(err = _ksba_asntime_to_iso (*buf, ti.length,
ti.tag == TYPE_UTC_TIME, isotime)))
parse_skip (buf, len, &ti);
}
| 165,030 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
Commit Message:
CWE ID: CWE-119 | static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
if (size > (R_MAX - R_RX_BUF0 - rxbase) * 4) {
D(qemu_log("ethlite packet is too big, size=%x\n", size));
return -1;
}
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
| 164,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LiveSyncTest::SetupMockGaiaResponses() {
username_ = "[email protected]";
password_ = "password";
factory_.reset(new FakeURLFetcherFactory());
factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
factory_->SetFakeResponse(kGetUserInfoUrl, "[email protected]", true);
factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
URLFetcher::set_factory(factory_.get());
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void LiveSyncTest::SetupMockGaiaResponses() {
username_ = "[email protected]";
password_ = "password";
integration_factory_.reset(new URLFetcherFactory());
factory_.reset(new FakeURLFetcherFactory(integration_factory_.get()));
factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
factory_->SetFakeResponse(kGetUserInfoUrl, "[email protected]", true);
factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
URLFetcher::set_factory(factory_.get());
}
| 170,430 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLFormElement::scheduleFormSubmission(FormSubmission* submission) {
DCHECK(submission->method() == FormSubmission::PostMethod ||
submission->method() == FormSubmission::GetMethod);
DCHECK(submission->data());
DCHECK(submission->form());
if (submission->action().isEmpty())
return;
if (document().isSandboxed(SandboxForms)) {
document().addConsoleMessage(ConsoleMessage::create(
SecurityMessageSource, ErrorMessageLevel,
"Blocked form submission to '" + submission->action().elidedString() +
"' because the form's frame is sandboxed and the 'allow-forms' "
"permission is not set."));
return;
}
if (protocolIsJavaScript(submission->action())) {
if (!document().contentSecurityPolicy()->allowFormAction(
submission->action()))
return;
document().frame()->script().executeScriptIfJavaScriptURL(
submission->action(), this);
return;
}
Frame* targetFrame = document().frame()->findFrameForNavigation(
submission->target(), *document().frame());
if (!targetFrame) {
if (!LocalDOMWindow::allowPopUp(*document().frame()) &&
!UserGestureIndicator::utilizeUserGesture())
return;
targetFrame = document().frame();
} else {
submission->clearTarget();
}
if (!targetFrame->host())
return;
UseCounter::count(document(), UseCounter::FormsSubmitted);
if (MixedContentChecker::isMixedFormAction(document().frame(),
submission->action()))
UseCounter::count(document().frame(),
UseCounter::MixedContentFormsSubmitted);
if (targetFrame->isLocalFrame()) {
toLocalFrame(targetFrame)
->navigationScheduler()
.scheduleFormSubmission(&document(), submission);
} else {
FrameLoadRequest frameLoadRequest =
submission->createFrameLoadRequest(&document());
toRemoteFrame(targetFrame)->navigate(frameLoadRequest);
}
}
Commit Message: Enforce form-action CSP even when form.target is present.
BUG=630332
Review-Url: https://codereview.chromium.org/2464123004
Cr-Commit-Position: refs/heads/master@{#429922}
CWE ID: CWE-19 | void HTMLFormElement::scheduleFormSubmission(FormSubmission* submission) {
DCHECK(submission->method() == FormSubmission::PostMethod ||
submission->method() == FormSubmission::GetMethod);
DCHECK(submission->data());
DCHECK(submission->form());
if (submission->action().isEmpty())
return;
if (document().isSandboxed(SandboxForms)) {
document().addConsoleMessage(ConsoleMessage::create(
SecurityMessageSource, ErrorMessageLevel,
"Blocked form submission to '" + submission->action().elidedString() +
"' because the form's frame is sandboxed and the 'allow-forms' "
"permission is not set."));
return;
}
if (!document().contentSecurityPolicy()->allowFormAction(
submission->action())) {
return;
}
if (protocolIsJavaScript(submission->action())) {
document().frame()->script().executeScriptIfJavaScriptURL(
submission->action(), this);
return;
}
Frame* targetFrame = document().frame()->findFrameForNavigation(
submission->target(), *document().frame());
if (!targetFrame) {
if (!LocalDOMWindow::allowPopUp(*document().frame()) &&
!UserGestureIndicator::utilizeUserGesture())
return;
targetFrame = document().frame();
} else {
submission->clearTarget();
}
if (!targetFrame->host())
return;
UseCounter::count(document(), UseCounter::FormsSubmitted);
if (MixedContentChecker::isMixedFormAction(document().frame(),
submission->action()))
UseCounter::count(document().frame(),
UseCounter::MixedContentFormsSubmitted);
if (targetFrame->isLocalFrame()) {
toLocalFrame(targetFrame)
->navigationScheduler()
.scheduleFormSubmission(&document(), submission);
} else {
FrameLoadRequest frameLoadRequest =
submission->createFrameLoadRequest(&document());
toRemoteFrame(targetFrame)->navigate(frameLoadRequest);
}
}
| 172,545 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
Commit Message: Fix compile warning introduced in commit c6247a9
Commit c6247a9 - "Add command line and configuration option to set umask"
introduced a compile warning, although the code would have worked OK.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-200 | set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return 0;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
| 170,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) {
for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();
++it) {
if ((*it)->GetAccountId() == account_id) {
users_.erase(it);
break;
}
}
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) {
for (auto it = users_.cbegin(); it != users_.cend(); ++it) {
if ((*it)->GetAccountId() == account_id) {
users_.erase(it);
break;
}
}
}
| 172,202 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ethertype_print(netdissect_options *ndo,
u_short ether_type, const u_char *p,
u_int length, u_int caplen,
const struct lladdr_info *src, const struct lladdr_info *dst)
{
switch (ether_type) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
return (1);
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
return (1);
case ETHERTYPE_ARP:
case ETHERTYPE_REVARP:
arp_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_DN:
decnet_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_ATALK:
if (ndo->ndo_vflag)
ND_PRINT((ndo, "et1 "));
atalk_print(ndo, p, length);
return (1);
case ETHERTYPE_AARP:
aarp_print(ndo, p, length);
return (1);
case ETHERTYPE_IPX:
ND_PRINT((ndo, "(NOV-ETHII) "));
ipx_print(ndo, p, length);
return (1);
case ETHERTYPE_ISO:
if (length == 0 || caplen == 0) {
ND_PRINT((ndo, " [|osi]"));
return (1);
}
isoclns_print(ndo, p + 1, length - 1, caplen - 1);
return(1);
case ETHERTYPE_PPPOED:
case ETHERTYPE_PPPOES:
case ETHERTYPE_PPPOED2:
case ETHERTYPE_PPPOES2:
pppoe_print(ndo, p, length);
return (1);
case ETHERTYPE_EAPOL:
eap_print(ndo, p, length);
return (1);
case ETHERTYPE_RRCP:
rrcp_print(ndo, p, length, src, dst);
return (1);
case ETHERTYPE_PPP:
if (length) {
ND_PRINT((ndo, ": "));
ppp_print(ndo, p, length);
}
return (1);
case ETHERTYPE_MPCP:
mpcp_print(ndo, p, length);
return (1);
case ETHERTYPE_SLOW:
slow_print(ndo, p, length);
return (1);
case ETHERTYPE_CFM:
case ETHERTYPE_CFM_OLD:
cfm_print(ndo, p, length);
return (1);
case ETHERTYPE_LLDP:
lldp_print(ndo, p, length);
return (1);
case ETHERTYPE_NSH:
nsh_print(ndo, p, length);
return (1);
case ETHERTYPE_LOOPBACK:
loopback_print(ndo, p, length);
return (1);
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
return (1);
case ETHERTYPE_TIPC:
tipc_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_MS_NLB_HB:
msnlb_print(ndo, p);
return (1);
case ETHERTYPE_GEONET_OLD:
case ETHERTYPE_GEONET:
geonet_print(ndo, p, length, src);
return (1);
case ETHERTYPE_CALM_FAST:
calm_fast_print(ndo, p, length, src);
return (1);
case ETHERTYPE_AOE:
aoe_print(ndo, p, length);
return (1);
case ETHERTYPE_MEDSA:
medsa_print(ndo, p, length, caplen, src, dst);
return (1);
case ETHERTYPE_LAT:
case ETHERTYPE_SCA:
case ETHERTYPE_MOPRC:
case ETHERTYPE_MOPDL:
case ETHERTYPE_IEEE1905_1:
/* default_print for now */
default:
return (0);
}
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ethertype_print(netdissect_options *ndo,
u_short ether_type, const u_char *p,
u_int length, u_int caplen,
const struct lladdr_info *src, const struct lladdr_info *dst)
{
switch (ether_type) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
return (1);
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
return (1);
case ETHERTYPE_ARP:
case ETHERTYPE_REVARP:
arp_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_DN:
decnet_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_ATALK:
if (ndo->ndo_vflag)
ND_PRINT((ndo, "et1 "));
atalk_print(ndo, p, length);
return (1);
case ETHERTYPE_AARP:
aarp_print(ndo, p, length);
return (1);
case ETHERTYPE_IPX:
ND_PRINT((ndo, "(NOV-ETHII) "));
ipx_print(ndo, p, length);
return (1);
case ETHERTYPE_ISO:
if (length == 0 || caplen == 0) {
ND_PRINT((ndo, " [|osi]"));
return (1);
}
isoclns_print(ndo, p + 1, length - 1);
return(1);
case ETHERTYPE_PPPOED:
case ETHERTYPE_PPPOES:
case ETHERTYPE_PPPOED2:
case ETHERTYPE_PPPOES2:
pppoe_print(ndo, p, length);
return (1);
case ETHERTYPE_EAPOL:
eap_print(ndo, p, length);
return (1);
case ETHERTYPE_RRCP:
rrcp_print(ndo, p, length, src, dst);
return (1);
case ETHERTYPE_PPP:
if (length) {
ND_PRINT((ndo, ": "));
ppp_print(ndo, p, length);
}
return (1);
case ETHERTYPE_MPCP:
mpcp_print(ndo, p, length);
return (1);
case ETHERTYPE_SLOW:
slow_print(ndo, p, length);
return (1);
case ETHERTYPE_CFM:
case ETHERTYPE_CFM_OLD:
cfm_print(ndo, p, length);
return (1);
case ETHERTYPE_LLDP:
lldp_print(ndo, p, length);
return (1);
case ETHERTYPE_NSH:
nsh_print(ndo, p, length);
return (1);
case ETHERTYPE_LOOPBACK:
loopback_print(ndo, p, length);
return (1);
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
return (1);
case ETHERTYPE_TIPC:
tipc_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_MS_NLB_HB:
msnlb_print(ndo, p);
return (1);
case ETHERTYPE_GEONET_OLD:
case ETHERTYPE_GEONET:
geonet_print(ndo, p, length, src);
return (1);
case ETHERTYPE_CALM_FAST:
calm_fast_print(ndo, p, length, src);
return (1);
case ETHERTYPE_AOE:
aoe_print(ndo, p, length);
return (1);
case ETHERTYPE_MEDSA:
medsa_print(ndo, p, length, caplen, src, dst);
return (1);
case ETHERTYPE_LAT:
case ETHERTYPE_SCA:
case ETHERTYPE_MOPRC:
case ETHERTYPE_MOPDL:
case ETHERTYPE_IEEE1905_1:
/* default_print for now */
default:
return (0);
}
}
| 167,944 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_do_nothing (MyObject *obj, GError **error)
{
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_do_nothing (MyObject *obj, GError **error)
| 165,092 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response DOMHandler::SetFileInputFiles(
std::unique_ptr<protocol::Array<std::string>> files,
Maybe<DOM::NodeId> node_id,
Maybe<DOM::BackendNodeId> backend_node_id,
Maybe<String> in_object_id) {
if (host_) {
for (size_t i = 0; i < files->length(); i++) {
#if defined(OS_WIN)
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
host_->GetProcess()->GetID(),
base::FilePath(base::UTF8ToUTF16(files->get(i))));
#else
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
host_->GetProcess()->GetID(),
base::FilePath(files->get(i)));
#endif // OS_WIN
}
}
return Response::FallThrough();
}
Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles
Bug: 805557
Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f
Reviewed-on: https://chromium-review.googlesource.com/c/1334847
Reviewed-by: Pavel Feldman <[email protected]>
Commit-Queue: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607902}
CWE ID: CWE-254 | Response DOMHandler::SetFileInputFiles(
std::unique_ptr<protocol::Array<std::string>> files,
Maybe<DOM::NodeId> node_id,
Maybe<DOM::BackendNodeId> backend_node_id,
Maybe<String> in_object_id) {
if (!allow_file_access_)
return Response::Error("Not allowed");
if (host_) {
for (size_t i = 0; i < files->length(); i++) {
#if defined(OS_WIN)
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
host_->GetProcess()->GetID(),
base::FilePath(base::UTF8ToUTF16(files->get(i))));
#else
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
host_->GetProcess()->GetID(),
base::FilePath(files->get(i)));
#endif // OS_WIN
}
}
return Response::FallThrough();
}
| 173,113 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ForeignSessionHelper::SetInvalidationsForSessionsEnabled(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
jboolean enabled) {
browser_sync::ProfileSyncService* service =
ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_);
if (!service)
return;
service->SetInvalidationsForSessionsEnabled(enabled);
}
Commit Message: Prefer SyncService over ProfileSyncService in foreign_session_helper
SyncService is the interface, ProfileSyncService is the concrete
implementation. Generally no clients should need to use the conrete
implementation - for one, testing will be much easier once everyone
uses the interface only.
Bug: 924508
Change-Id: Ia210665f8f02512053d1a60d627dea0f22758387
Reviewed-on: https://chromium-review.googlesource.com/c/1461119
Auto-Submit: Marc Treib <[email protected]>
Commit-Queue: Yaron Friedman <[email protected]>
Reviewed-by: Yaron Friedman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#630662}
CWE ID: CWE-254 | void ForeignSessionHelper::SetInvalidationsForSessionsEnabled(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
jboolean enabled) {
syncer::SyncService* service =
ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_);
if (!service)
return;
service->SetInvalidationsForSessionsEnabled(enabled);
}
| 172,058 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Accelerator GetAccelerator(KeyboardCode code, int mask) {
return Accelerator(code, mask & (1 << 0), mask & (1 << 1), mask & (1 << 2));
}
Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans.
BUG=128242
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10399085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | Accelerator GetAccelerator(KeyboardCode code, int mask) {
return Accelerator(code, mask);
}
| 170,907 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
{
ASN1_INTEGER *ret;
int len, j;
if (ai == NULL)
ret = M_ASN1_INTEGER_new();
else
ret = ai;
if (ret == NULL) {
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
goto err;
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (BN_is_negative(bn))
ret->type = V_ASN1_NEG_INTEGER;
else
ret->type = V_ASN1_INTEGER;
if (ret->length < len + 4) {
unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4);
if (!new_data) {
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
goto err;
}
ret->data = new_data;
}
ret->length = BN_bn2bin(bn, ret->data);
/* Correct zero case */
if (!ret->length) {
ret->data[0] = 0;
ret->length = 1;
}
return (ret);
err:
if (ret != ai)
M_ASN1_INTEGER_free(ret);
return (NULL);
}
Commit Message:
CWE ID: CWE-119 | ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
{
ASN1_INTEGER *ret;
int len, j;
if (ai == NULL)
ret = M_ASN1_INTEGER_new();
else
ret = ai;
if (ret == NULL) {
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
goto err;
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (BN_is_negative(bn) && !BN_is_zero(bn))
ret->type = V_ASN1_NEG_INTEGER;
else
ret->type = V_ASN1_INTEGER;
if (ret->length < len + 4) {
unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4);
if (!new_data) {
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
goto err;
}
ret->data = new_data;
}
ret->length = BN_bn2bin(bn, ret->data);
/* Correct zero case */
if (!ret->length) {
ret->data[0] = 0;
ret->length = 1;
}
return (ret);
err:
if (ret != ai)
M_ASN1_INTEGER_free(ret);
return (NULL);
}
| 165,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static u64 __skb_get_nlattr_nest(u64 ctx, u64 A, u64 X, u64 r4, u64 r5)
{
struct sk_buff *skb = (struct sk_buff *)(long) ctx;
struct nlattr *nla;
if (skb_is_nonlinear(skb))
return 0;
if (A > skb->len - sizeof(struct nlattr))
return 0;
nla = (struct nlattr *) &skb->data[A];
if (nla->nla_len > A - skb->len)
return 0;
nla = nla_find_nested(nla, X);
if (nla)
return (void *) nla - (void *) skb->data;
return 0;
}
Commit Message: filter: prevent nla extensions to peek beyond the end of the message
The BPF_S_ANC_NLATTR and BPF_S_ANC_NLATTR_NEST extensions fail to check
for a minimal message length before testing the supplied offset to be
within the bounds of the message. This allows the subtraction of the nla
header to underflow and therefore -- as the data type is unsigned --
allowing far to big offset and length values for the search of the
netlink attribute.
The remainder calculation for the BPF_S_ANC_NLATTR_NEST extension is
also wrong. It has the minuend and subtrahend mixed up, therefore
calculates a huge length value, allowing to overrun the end of the
message while looking for the netlink attribute.
The following three BPF snippets will trigger the bugs when attached to
a UNIX datagram socket and parsing a message with length 1, 2 or 3.
,-[ PoC for missing size check in BPF_S_ANC_NLATTR ]--
| ld #0x87654321
| ldx #42
| ld #nla
| ret a
`---
,-[ PoC for the same bug in BPF_S_ANC_NLATTR_NEST ]--
| ld #0x87654321
| ldx #42
| ld #nlan
| ret a
`---
,-[ PoC for wrong remainder calculation in BPF_S_ANC_NLATTR_NEST ]--
| ; (needs a fake netlink header at offset 0)
| ld #0
| ldx #42
| ld #nlan
| ret a
`---
Fix the first issue by ensuring the message length fulfills the minimal
size constrains of a nla header. Fix the second bug by getting the math
for the remainder calculation right.
Fixes: 4738c1db15 ("[SKFILTER]: Add SKF_ADF_NLATTR instruction")
Fixes: d214c7537b ("filter: add SKF_AD_NLATTR_NEST to look for nested..")
Cc: Patrick McHardy <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189 | static u64 __skb_get_nlattr_nest(u64 ctx, u64 A, u64 X, u64 r4, u64 r5)
{
struct sk_buff *skb = (struct sk_buff *)(long) ctx;
struct nlattr *nla;
if (skb_is_nonlinear(skb))
return 0;
if (skb->len < sizeof(struct nlattr))
return 0;
if (A > skb->len - sizeof(struct nlattr))
return 0;
nla = (struct nlattr *) &skb->data[A];
if (nla->nla_len > skb->len - A)
return 0;
nla = nla_find_nested(nla, X);
if (nla)
return (void *) nla - (void *) skb->data;
return 0;
}
| 166,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GDataCacheMetadataMap::ScanCacheDirectory(
const std::vector<FilePath>& cache_paths,
GDataCache::CacheSubDirectoryType sub_dir_type,
CacheMap* cache_map,
ResourceIdToFilePathMap* processed_file_map) {
DCHECK(cache_map);
DCHECK(processed_file_map);
file_util::FileEnumerator enumerator(
cache_paths[sub_dir_type],
false, // not recursive
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
util::kWildCard);
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension);
int cache_state = GDataCache::CACHE_STATE_NONE;
if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED) {
std::string reason;
if (!IsValidSymbolicLink(current, sub_dir_type, cache_paths, &reason)) {
LOG(WARNING) << "Removing an invalid symlink: " << current.value()
<< ": " << reason;
util::DeleteSymlink(current);
continue;
}
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update pinned state.
iter->second.cache_state =
GDataCache::SetCachePinned(iter->second.cache_state);
processed_file_map->insert(std::make_pair(resource_id, current));
continue;
}
cache_state = GDataCache::SetCachePinned(cache_state);
} else if (sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING) {
std::string reason;
if (!IsValidSymbolicLink(current, sub_dir_type, cache_paths, &reason)) {
LOG(WARNING) << "Removing an invalid symlink: " << current.value()
<< ": " << reason;
util::DeleteSymlink(current);
continue;
}
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter == cache_map->end() || !iter->second.IsDirty()) {
LOG(WARNING) << "Removing an symlink to a non-dirty file: "
<< current.value();
util::DeleteSymlink(current);
continue;
}
processed_file_map->insert(std::make_pair(resource_id, current));
continue;
} else if (sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT ||
sub_dir_type == GDataCache::CACHE_TYPE_TMP) {
FilePath unused;
if (file_util::ReadSymbolicLink(current, &unused)) {
LOG(WARNING) << "Removing a symlink in persistent/tmp directory"
<< current.value();
util::DeleteSymlink(current);
continue;
}
if (extra_extension == util::kMountedArchiveFileExtension) {
DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT);
file_util::Delete(current, false);
} else {
cache_state = GDataCache::SetCachePresent(cache_state);
if (md5 == util::kLocallyModifiedFileExtension) {
if (sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT) {
cache_state |= GDataCache::SetCacheDirty(cache_state);
} else {
LOG(WARNING) << "Removing a dirty file in tmp directory: "
<< current.value();
file_util::Delete(current, false);
continue;
}
}
}
} else {
NOTREACHED() << "Unexpected sub directory type: " << sub_dir_type;
}
cache_map->insert(std::make_pair(
resource_id, GDataCache::CacheEntry(md5, sub_dir_type, cache_state)));
processed_file_map->insert(std::make_pair(resource_id, current));
}
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void GDataCacheMetadataMap::ScanCacheDirectory(
const std::vector<FilePath>& cache_paths,
GDataCache::CacheSubDirectoryType sub_dir_type,
CacheMap* cache_map) {
file_util::FileEnumerator enumerator(
cache_paths[sub_dir_type],
false, // not recursive
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
util::kWildCard);
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension);
int cache_state = GDataCache::CACHE_STATE_NONE;
if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED) {
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update pinned state.
iter->second.cache_state =
GDataCache::SetCachePinned(iter->second.cache_state);
continue;
}
cache_state = GDataCache::SetCachePinned(cache_state);
} else if (sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING) {
// If we're scanning outgoing directory, entry must exist, update its
// dirty state.
// If entry doesn't exist, it's a logic error from previous execution,
// ignore this outgoing symlink and move on.
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update dirty state.
iter->second.cache_state =
GDataCache::SetCacheDirty(iter->second.cache_state);
} else {
NOTREACHED() << "Dirty cache file MUST have actual file blob";
}
continue;
} else if (extra_extension == util::kMountedArchiveFileExtension) {
// Mounted archives in cache should be unmounted upon logout/shutdown.
// But if we encounter a mounted file at start, delete it and create an
// entry with not PRESENT state.
DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT);
file_util::Delete(current, false);
} else {
// Scanning other directories means that cache file is actually present.
cache_state = GDataCache::SetCachePresent(cache_state);
}
cache_map->insert(std::make_pair(
resource_id, GDataCache::CacheEntry(md5, sub_dir_type, cache_state)));
}
}
| 170,868 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TEE_Result syscall_cryp_obj_populate(unsigned long obj,
struct utee_attribute *usr_attrs,
unsigned long attr_count)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *attrs = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_IMPLEMENTED;
attrs = malloc(sizeof(TEE_Attribute) * attr_count);
if (!attrs)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,
attrs);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
attrs, attr_count);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
if (res == TEE_SUCCESS)
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
out:
free(attrs);
return res;
}
Commit Message: svc: check for allocation overflow in syscall_cryp_obj_populate
Without checking for overflow there is a risk of allocating a buffer
with size smaller than anticipated and as a consequence of that it might
lead to a heap based overflow with attacker controlled data written
outside the boundaries of the buffer.
Fixes: OP-TEE-2018-0009: "Integer overflow in crypto system calls"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-119 | TEE_Result syscall_cryp_obj_populate(unsigned long obj,
struct utee_attribute *usr_attrs,
unsigned long attr_count)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *attrs = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_IMPLEMENTED;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size))
return TEE_ERROR_OVERFLOW;
attrs = malloc(alloc_size);
if (!attrs)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,
attrs);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
attrs, attr_count);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
if (res == TEE_SUCCESS)
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
out:
free(attrs);
return res;
}
| 169,469 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void msleep(uint64_t ms) {
usleep(ms * 1000);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static void msleep(uint64_t ms) {
TEMP_FAILURE_RETRY(usleep(ms * 1000));
}
| 173,489 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
Commit Message: floppy: fix div-by-zero in setup_format_params
This fixes a divide by zero error in the setup_format_params function of
the floppy driver.
Two consecutive ioctls can trigger the bug: The first one should set the
drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK
to become zero. Next, the floppy format operation should be called.
A floppy disk is not required to be inserted. An unprivileged user
could trigger the bug if the device is accessible.
The patch checks F_SECT_PER_TRACK for a non-zero value in the
set_geometry function. The proper check should involve a reasonable
upper limit for the .sect and .rate fields, but it could change the
UAPI.
The patch also checks F_SECT_PER_TRACK in the setup_format_params, and
cancels the formatting operation in case of zero.
The bug was found by syzkaller.
Signed-off-by: Denis Efremov <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-369 | static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
| 169,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: P2PQuicStreamTest()
: connection_(
new quic::test::MockQuicConnection(&connection_helper_,
&alarm_factory_,
quic::Perspective::IS_CLIENT)),
session_(connection_) {
session_.Initialize();
stream_ = new P2PQuicStreamImpl(kStreamId, &session_);
stream_->SetDelegate(&delegate_);
session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284 | P2PQuicStreamTest()
: connection_(
new quic::test::MockQuicConnection(&connection_helper_,
&alarm_factory_,
quic::Perspective::IS_CLIENT)),
session_(connection_) {
session_.Initialize();
stream_ = new P2PQuicStreamImpl(kStreamId, &session_, kWriteBufferSize);
stream_->SetDelegate(&delegate_);
session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
}
| 172,264 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize)
{
unsigned char *buf;
assert(bufsize >= 0);
JAS_DBGLOG(100, ("mem_resize(%p, %d)\n", m, bufsize));
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
bufsize) {
JAS_DBGLOG(100, ("mem_resize realloc failed\n"));
return -1;
}
JAS_DBGLOG(100, ("mem_resize realloc succeeded\n"));
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190 | static int mem_resize(jas_stream_memobj_t *m, int bufsize)
static int mem_resize(jas_stream_memobj_t *m, size_t bufsize)
{
unsigned char *buf;
//assert(bufsize >= 0);
JAS_DBGLOG(100, ("mem_resize(%p, %zu)\n", m, bufsize));
if (!bufsize) {
jas_eprintf(
"mem_resize was not really designed to handle a buffer of size 0\n"
"This may not work.\n"
);
}
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
bufsize) {
JAS_DBGLOG(100, ("mem_resize realloc failed\n"));
return -1;
}
JAS_DBGLOG(100, ("mem_resize realloc succeeded\n"));
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
| 168,750 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GBool SplashFTFont::makeGlyph(int c, int xFrac, int yFrac,
SplashGlyphBitmap *bitmap, int x0, int y0, SplashClip *clip, SplashClipResult *clipRes) {
SplashFTFontFile *ff;
FT_Vector offset;
FT_GlyphSlot slot;
FT_UInt gid;
int rowSize;
Guchar *p, *q;
int i;
ff = (SplashFTFontFile *)fontFile;
ff->face->size = sizeObj;
offset.x = (FT_Pos)(int)((SplashCoord)xFrac * splashFontFractionMul * 64);
offset.y = 0;
FT_Set_Transform(ff->face, &matrix, &offset);
slot = ff->face->glyph;
if (ff->codeToGID && c < ff->codeToGIDLen) {
gid = (FT_UInt)ff->codeToGID[c];
} else {
gid = (FT_UInt)c;
}
if (ff->trueType && gid == 0) {
return gFalse;
}
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT)) {
return gFalse;
}
#else
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP
: FT_LOAD_DEFAULT)) {
return gFalse;
}
#endif
FT_Glyph_Metrics *glyphMetrics = &(ff->face->glyph->metrics);
bitmap->x = splashRound(-glyphMetrics->horiBearingX / 64.0);
bitmap->y = splashRound(glyphMetrics->horiBearingY / 64.0);
bitmap->w = splashRound(glyphMetrics->width / 64.0);
bitmap->h = splashRound(glyphMetrics->height / 64.0);
*clipRes = clip->testRect(x0 - bitmap->x,
y0 - bitmap->y,
x0 - bitmap->x + bitmap->w,
y0 - bitmap->y + bitmap->h);
if (*clipRes == splashClipAllOutside) {
bitmap->freeData = gFalse;
return gTrue;
}
if (FT_Render_Glyph(slot, aa ? ft_render_mode_normal
: ft_render_mode_mono)) {
return gFalse;
}
bitmap->x = -slot->bitmap_left;
bitmap->y = slot->bitmap_top;
bitmap->w = slot->bitmap.width;
bitmap->h = slot->bitmap.rows;
bitmap->aa = aa;
if (aa) {
rowSize = bitmap->w;
} else {
rowSize = (bitmap->w + 7) >> 3;
}
bitmap->data = (Guchar *)gmalloc(rowSize * bitmap->h);
bitmap->freeData = gTrue;
for (i = 0, p = bitmap->data, q = slot->bitmap.buffer;
i < bitmap->h;
++i, p += rowSize, q += slot->bitmap.pitch) {
memcpy(p, q, rowSize);
}
return gTrue;
}
Commit Message:
CWE ID: CWE-189 | GBool SplashFTFont::makeGlyph(int c, int xFrac, int yFrac,
SplashGlyphBitmap *bitmap, int x0, int y0, SplashClip *clip, SplashClipResult *clipRes) {
SplashFTFontFile *ff;
FT_Vector offset;
FT_GlyphSlot slot;
FT_UInt gid;
int rowSize;
Guchar *p, *q;
int i;
ff = (SplashFTFontFile *)fontFile;
ff->face->size = sizeObj;
offset.x = (FT_Pos)(int)((SplashCoord)xFrac * splashFontFractionMul * 64);
offset.y = 0;
FT_Set_Transform(ff->face, &matrix, &offset);
slot = ff->face->glyph;
if (ff->codeToGID && c < ff->codeToGIDLen) {
gid = (FT_UInt)ff->codeToGID[c];
} else {
gid = (FT_UInt)c;
}
if (ff->trueType && gid == 0) {
return gFalse;
}
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT)) {
return gFalse;
}
#else
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP
: FT_LOAD_DEFAULT)) {
return gFalse;
}
#endif
FT_Glyph_Metrics *glyphMetrics = &(ff->face->glyph->metrics);
bitmap->x = splashRound(-glyphMetrics->horiBearingX / 64.0);
bitmap->y = splashRound(glyphMetrics->horiBearingY / 64.0);
bitmap->w = splashRound(glyphMetrics->width / 64.0);
bitmap->h = splashRound(glyphMetrics->height / 64.0);
*clipRes = clip->testRect(x0 - bitmap->x,
y0 - bitmap->y,
x0 - bitmap->x + bitmap->w,
y0 - bitmap->y + bitmap->h);
if (*clipRes == splashClipAllOutside) {
bitmap->freeData = gFalse;
return gTrue;
}
if (FT_Render_Glyph(slot, aa ? ft_render_mode_normal
: ft_render_mode_mono)) {
return gFalse;
}
bitmap->x = -slot->bitmap_left;
bitmap->y = slot->bitmap_top;
bitmap->w = slot->bitmap.width;
bitmap->h = slot->bitmap.rows;
bitmap->aa = aa;
if (aa) {
rowSize = bitmap->w;
} else {
rowSize = (bitmap->w + 7) >> 3;
}
bitmap->data = (Guchar *)gmallocn(rowSize, bitmap->h);
bitmap->freeData = gTrue;
for (i = 0, p = bitmap->data, q = slot->bitmap.buffer;
i < bitmap->h;
++i, p += rowSize, q += slot->bitmap.pitch) {
memcpy(p, q, rowSize);
}
return gTrue;
}
| 164,621 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: poly_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
POLYGON *poly;
int npts;
int size;
int isopen;
char *s;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts;
poly = (POLYGON *) palloc0(size); /* zero any holes */
SET_VARSIZE(poly, size);
poly->npts = npts;
if ((!path_decode(FALSE, npts, str, &isopen, &s, &(poly->p[0])))
|| (*s != '\0'))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
make_bound_box(poly);
PG_RETURN_POLYGON_P(poly);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | poly_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
POLYGON *poly;
int npts;
int size;
int base_size;
int isopen;
char *s;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
base_size = sizeof(poly->p[0]) * npts;
size = offsetof(POLYGON, p[0]) + base_size;
/* Check for integer overflow */
if (base_size / npts != sizeof(poly->p[0]) || size <= base_size)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("too many points requested")));
poly = (POLYGON *) palloc0(size); /* zero any holes */
SET_VARSIZE(poly, size);
poly->npts = npts;
if ((!path_decode(FALSE, npts, str, &isopen, &s, &(poly->p[0])))
|| (*s != '\0'))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
make_bound_box(poly);
PG_RETURN_POLYGON_P(poly);
}
| 166,411 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, const png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
| 173,611 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) {
DCHECK(!renderer_process_);
if (base::GetProcId(renderer_process) == renderer_pid_)
renderer_process_ = renderer_process;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) {
| 170,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Splash::vertFlipImage(SplashBitmap *img, int width, int height,
int nComps) {
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
lineBuf = (Guchar *)gmalloc(w);
p0 += width, p1 -= width) {
memcpy(lineBuf, p0, width);
memcpy(p0, p1, width);
memcpy(p1, lineBuf, width);
}
}
Commit Message:
CWE ID: CWE-119 | void Splash::vertFlipImage(SplashBitmap *img, int width, int height,
int nComps) {
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
if (unlikely(img->data == NULL)) {
error(errInternal, -1, "img->data is NULL in Splash::vertFlipImage");
return;
}
w = width * nComps;
lineBuf = (Guchar *)gmalloc(w);
p0 += width, p1 -= width) {
memcpy(lineBuf, p0, width);
memcpy(p0, p1, width);
memcpy(p1, lineBuf, width);
}
}
| 164,736 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string SanitizeRevision(const std::string& revision) {
for (size_t i = 0; i < revision.length(); i++) {
if (!(revision[i] == '@' && i == 0)
&& !(revision[i] >= '0' && revision[i] <= '9')
&& !(revision[i] >= 'a' && revision[i] <= 'z')
&& !(revision[i] >= 'A' && revision[i] <= 'Z')) {
return std::string();
}
}
return revision;
}
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 | std::string SanitizeRevision(const std::string& revision) {
| 172,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btm_sec_pin_code_request (UINT8 *p_bda)
{
tBTM_SEC_DEV_REC *p_dev_rec;
tBTM_CB *p_cb = &btm_cb;
#ifdef PORCHE_PAIRING_CONFLICT
UINT8 default_pin_code_len = 4;
PIN_CODE default_pin_code = {0x30, 0x30, 0x30, 0x30};
#endif
BTM_TRACE_EVENT ("btm_sec_pin_code_request() State: %s, BDA:%04x%08x",
btm_pair_state_descr(btm_cb.pairing_state),
(p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] );
if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
{
if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) &&
(btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) )
{
/* fake this out - porshe carkit issue - */
if(! btm_cb.pin_code_len_saved)
{
btsnd_hcic_pin_code_neg_reply (p_bda);
return;
}
else
{
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code);
return;
}
}
else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ)
|| memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
{
BTM_TRACE_WARNING ("btm_sec_pin_code_request() rejected - state: %s",
btm_pair_state_descr(btm_cb.pairing_state));
#ifdef PORCHE_PAIRING_CONFLICT
/* reply pin code again due to counter in_rand when local initiates pairing */
BTM_TRACE_EVENT ("btm_sec_pin_code_request from remote dev. for local initiated pairing");
if(! btm_cb.pin_code_len_saved)
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, default_pin_code_len, default_pin_code);
}
else
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code);
}
#else
btsnd_hcic_pin_code_neg_reply (p_bda);
#endif
return;
}
}
p_dev_rec = btm_find_or_alloc_dev (p_bda);
/* received PIN code request. must be non-sm4 */
p_dev_rec->sm4 = BTM_SM4_KNOWN;
if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
{
memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN);
btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
/* Make sure we reset the trusted mask to help against attacks */
BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
}
if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED))
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request fixed pin replying");
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code);
return;
}
/* Use the connecting device's CoD for the connection */
if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN))
&& (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) )
memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN);
/* We could have started connection after asking user for the PIN code */
if (btm_cb.pin_code_len != 0)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request bonding sending reply");
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code);
#ifdef PORCHE_PAIRING_CONFLICT
btm_cb.pin_code_len_saved = btm_cb.pin_code_len;
#endif
/* Mark that we forwarded received from the user PIN code */
btm_cb.pin_code_len = 0;
/* We can change mode back right away, that other connection being established */
/* is not forced to be secure - found a FW issue, so we can not do this
btm_restore_mode(); */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
}
/* If pairing disabled OR (no PIN callback and not bonding) */
/* OR we could not allocate entry in the database reject pairing request */
else if (p_cb->pairing_disabled
|| (p_cb->api.p_pin_callback == NULL)
/* OR Microsoft keyboard can for some reason try to establish connection */
/* the only thing we can do here is to shut it up. Normally we will be originator */
/* for keyboard bonding */
|| (!p_dev_rec->is_originator
&& ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL)
&& (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) )
{
BTM_TRACE_WARNING("btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!",
p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
btsnd_hcic_pin_code_neg_reply (p_bda);
}
/* Notify upper layer of PIN request and start expiration timer */
else
{
btm_cb.pin_code_len_saved = 0;
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
/* Pin code request can not come at the same time as connection request */
memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN);
memcpy (p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
/* Check if the name is known */
/* Even if name is not known we might not be able to get one */
/* this is the case when we are already getting something from the */
/* device, so HCI level is flow controlled */
/* Also cannot send remote name request while paging, i.e. connection is not completed */
if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
else
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for remote name");
/* We received PIN code request for the device with unknown name */
/* it is not user friendly just to ask for the PIN without name */
/* try to get name at first */
if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr,
HCI_PAGE_SCAN_REP_MODE_R1,
HCI_MANDATARY_PAGE_SCAN_MODE, 0))
{
p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
p_dev_rec->sec_bd_name[0] = 'f';
p_dev_rec->sec_bd_name[1] = '0';
BTM_TRACE_ERROR ("can not send rmt_name_req?? fake a name and call callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
}
}
return;
}
Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround
Bug: 26551752
Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1
CWE ID: CWE-264 | void btm_sec_pin_code_request (UINT8 *p_bda)
{
tBTM_SEC_DEV_REC *p_dev_rec;
tBTM_CB *p_cb = &btm_cb;
BTM_TRACE_EVENT ("btm_sec_pin_code_request() State: %s, BDA:%04x%08x",
btm_pair_state_descr(btm_cb.pairing_state),
(p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] );
if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
{
if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) &&
(btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) )
{
btsnd_hcic_pin_code_neg_reply (p_bda);
return;
}
else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ)
|| memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
{
BTM_TRACE_WARNING ("btm_sec_pin_code_request() rejected - state: %s",
btm_pair_state_descr(btm_cb.pairing_state));
btsnd_hcic_pin_code_neg_reply (p_bda);
return;
}
}
p_dev_rec = btm_find_or_alloc_dev (p_bda);
/* received PIN code request. must be non-sm4 */
p_dev_rec->sm4 = BTM_SM4_KNOWN;
if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
{
memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN);
btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
/* Make sure we reset the trusted mask to help against attacks */
BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
}
if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED))
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request fixed pin replying");
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code);
return;
}
/* Use the connecting device's CoD for the connection */
if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN))
&& (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) )
memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN);
/* We could have started connection after asking user for the PIN code */
if (btm_cb.pin_code_len != 0)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request bonding sending reply");
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code);
/* Mark that we forwarded received from the user PIN code */
btm_cb.pin_code_len = 0;
/* We can change mode back right away, that other connection being established */
/* is not forced to be secure - found a FW issue, so we can not do this
btm_restore_mode(); */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
}
/* If pairing disabled OR (no PIN callback and not bonding) */
/* OR we could not allocate entry in the database reject pairing request */
else if (p_cb->pairing_disabled
|| (p_cb->api.p_pin_callback == NULL)
/* OR Microsoft keyboard can for some reason try to establish connection */
/* the only thing we can do here is to shut it up. Normally we will be originator */
/* for keyboard bonding */
|| (!p_dev_rec->is_originator
&& ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL)
&& (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) )
{
BTM_TRACE_WARNING("btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!",
p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
btsnd_hcic_pin_code_neg_reply (p_bda);
}
/* Notify upper layer of PIN request and start expiration timer */
else
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
/* Pin code request can not come at the same time as connection request */
memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN);
memcpy (p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
/* Check if the name is known */
/* Even if name is not known we might not be able to get one */
/* this is the case when we are already getting something from the */
/* device, so HCI level is flow controlled */
/* Also cannot send remote name request while paging, i.e. connection is not completed */
if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
else
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for remote name");
/* We received PIN code request for the device with unknown name */
/* it is not user friendly just to ask for the PIN without name */
/* try to get name at first */
if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr,
HCI_PAGE_SCAN_REP_MODE_R1,
HCI_MANDATARY_PAGE_SCAN_MODE, 0))
{
p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
p_dev_rec->sec_bd_name[0] = 'f';
p_dev_rec->sec_bd_name[1] = '0';
BTM_TRACE_ERROR ("can not send rmt_name_req?? fake a name and call callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
}
}
return;
}
| 173,902 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.