instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| 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: mm_answer_pam_init_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
authctxt->user = buffer_get_string(m, NULL);
sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
sshpam_authok = NULL;
buffer_clear(m);
if (sshpam_ctxt != NULL) {
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
buffer_put_int(m, 1);
} else {
buffer_put_int(m, 0);
}
mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
return (0);
}
Commit Message: Don't resend username to PAM; it already has it.
Pointed out by Moritz Jodeit; ok dtucker@
CWE ID: CWE-20
|
mm_answer_pam_init_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
sshpam_authok = NULL;
buffer_clear(m);
if (sshpam_ctxt != NULL) {
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
buffer_put_int(m, 1);
} else {
buffer_put_int(m, 0);
}
mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
return (0);
}
| 166,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: void WtsConsoleSessionProcessDriver::OnChannelConnected() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void WtsConsoleSessionProcessDriver::OnChannelConnected() {
void WtsConsoleSessionProcessDriver::OnChannelConnected(int32 peer_pid) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
}
| 171,554
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg)
{
__be32 *p;
/*
* opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4,
* owner 4 = 32
*/
RESERVE_SPACE(8);
WRITE32(OP_OPEN);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->open_flags);
RESERVE_SPACE(28);
WRITE64(arg->clientid);
WRITE32(16);
WRITEMEM("open id:", 8);
WRITE64(arg->id);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg)
{
__be32 *p;
/*
* opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4,
* owner 4 = 32
*/
RESERVE_SPACE(8);
WRITE32(OP_OPEN);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->fmode);
RESERVE_SPACE(28);
WRITE64(arg->clientid);
WRITE32(16);
WRITEMEM("open id:", 8);
WRITE64(arg->id);
}
| 165,714
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: char *my_asctime(time_t t)
{
struct tm *tm;
char *str;
int len;
tm = localtime(&t);
str = g_strdup(asctime(tm));
len = strlen(str);
if (len > 0) str[len-1] = '\0';
return str;
}
Commit Message: Merge branch 'security' into 'master'
Security
Closes #10
See merge request !17
CWE ID: CWE-416
|
char *my_asctime(time_t t)
{
struct tm *tm;
char *str;
int len;
tm = localtime(&t);
if (tm == NULL)
return g_strdup("???");
str = g_strdup(asctime(tm));
len = strlen(str);
if (len > 0) str[len-1] = '\0';
return str;
}
| 168,056
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED,
int argc, const char **argv)
{
void *cookiefile;
int i, debug = 0;
const char* user;
struct passwd *tpwd = NULL;
uid_t unlinkuid, fsuid;
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS)
pam_syslog(pamh, LOG_ERR, "error determining target user's name");
else {
tpwd = pam_modutil_getpwnam(pamh, user);
if (!tpwd)
pam_syslog(pamh, LOG_ERR, "error determining target user's UID");
else
unlinkuid = tpwd->pw_uid;
}
/* Parse arguments. We don't understand many, so no sense in breaking
* this into a separate function. */
for (i = 0; i < argc; i++) {
if (strcmp(argv[i], "debug") == 0) {
debug = 1;
continue;
}
if (strncmp(argv[i], "xauthpath=", 10) == 0) {
continue;
}
if (strncmp(argv[i], "systemuser=", 11) == 0) {
continue;
}
if (strncmp(argv[i], "targetuser=", 11) == 0) {
continue;
}
pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'",
argv[i]);
}
/* Try to retrieve the name of a file we created when the session was
* opened. */
if (pam_get_data(pamh, DATANAME, (const void**) &cookiefile) == PAM_SUCCESS) {
/* We'll only try to remove the file once. */
if (strlen((char*)cookiefile) > 0) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG, "removing `%s'",
(char*)cookiefile);
}
/* NFS with root_squash requires non-root user */
if (tpwd)
fsuid = setfsuid(unlinkuid);
unlink((char*)cookiefile);
if (tpwd)
setfsuid(fsuid);
*((char*)cookiefile) = '\0';
}
}
return PAM_SUCCESS;
}
Commit Message:
CWE ID:
|
pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED,
int argc, const char **argv)
{
int i, debug = 0;
const char *user;
const void *data;
const char *cookiefile;
struct passwd *tpwd;
uid_t fsuid;
/* Try to retrieve the name of a file we created when
* the session was opened. */
if (pam_get_data(pamh, DATANAME, &data) != PAM_SUCCESS)
return PAM_SUCCESS;
cookiefile = data;
/* Parse arguments. We don't understand many, so
* no sense in breaking this into a separate function. */
for (i = 0; i < argc; i++) {
if (strcmp(argv[i], "debug") == 0) {
debug = 1;
continue;
}
if (strncmp(argv[i], "xauthpath=", 10) == 0)
continue;
if (strncmp(argv[i], "systemuser=", 11) == 0)
continue;
if (strncmp(argv[i], "targetuser=", 11) == 0)
continue;
pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'",
argv[i]);
}
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) {
pam_syslog(pamh, LOG_ERR,
"error determining target user's name");
return PAM_SESSION_ERR;
}
if (!(tpwd = pam_modutil_getpwnam(pamh, user))) {
pam_syslog(pamh, LOG_ERR,
"error determining target user's UID");
return PAM_SESSION_ERR;
}
if (debug)
pam_syslog(pamh, LOG_DEBUG, "removing `%s'", cookiefile);
fsuid = setfsuid(tpwd->pw_uid);
unlink(cookiefile);
setfsuid(fsuid);
return PAM_SUCCESS;
}
| 164,789
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: nfs41_callback_svc(void *vrqstp)
{
struct svc_rqst *rqstp = vrqstp;
struct svc_serv *serv = rqstp->rq_server;
struct rpc_rqst *req;
int error;
DEFINE_WAIT(wq);
set_freezable();
while (!kthread_should_stop()) {
if (try_to_freeze())
continue;
prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE);
spin_lock_bh(&serv->sv_cb_lock);
if (!list_empty(&serv->sv_cb_list)) {
req = list_first_entry(&serv->sv_cb_list,
struct rpc_rqst, rq_bc_list);
list_del(&req->rq_bc_list);
spin_unlock_bh(&serv->sv_cb_lock);
finish_wait(&serv->sv_cb_waitq, &wq);
dprintk("Invoking bc_svc_process()\n");
error = bc_svc_process(serv, req, rqstp);
dprintk("bc_svc_process() returned w/ error code= %d\n",
error);
} else {
spin_unlock_bh(&serv->sv_cb_lock);
schedule();
finish_wait(&serv->sv_cb_waitq, &wq);
}
flush_signals(current);
}
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
nfs41_callback_svc(void *vrqstp)
{
struct svc_rqst *rqstp = vrqstp;
struct svc_serv *serv = rqstp->rq_server;
struct rpc_rqst *req;
int error;
DEFINE_WAIT(wq);
set_freezable();
while (!kthread_freezable_should_stop(NULL)) {
if (signal_pending(current))
flush_signals(current);
prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE);
spin_lock_bh(&serv->sv_cb_lock);
if (!list_empty(&serv->sv_cb_list)) {
req = list_first_entry(&serv->sv_cb_list,
struct rpc_rqst, rq_bc_list);
list_del(&req->rq_bc_list);
spin_unlock_bh(&serv->sv_cb_lock);
finish_wait(&serv->sv_cb_waitq, &wq);
dprintk("Invoking bc_svc_process()\n");
error = bc_svc_process(serv, req, rqstp);
dprintk("bc_svc_process() returned w/ error code= %d\n",
error);
} else {
spin_unlock_bh(&serv->sv_cb_lock);
if (!kthread_should_stop())
schedule();
finish_wait(&serv->sv_cb_waitq, &wq);
}
}
svc_exit_thread(rqstp);
module_put_and_exit(0);
return 0;
}
| 168,137
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
(void) RelinquishUniqueFileResource(memory_info->filename);
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
Commit Message:
CWE ID: CWE-189
|
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
{
(void) RelinquishUniqueFileResource(memory_info->filename);
RelinquishMagickResource(DiskResource,memory_info->length);
}
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
| 168,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: void NavigateOnUIThread(
const GURL& url,
const std::vector<GURL> url_chain,
const Referrer& referrer,
bool has_user_gesture,
const ResourceRequestInfo::WebContentsGetter& wc_getter) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = wc_getter.Run();
if (web_contents) {
NavigationController::LoadURLParams params(url);
params.has_user_gesture = has_user_gesture;
params.referrer = referrer;
params.redirect_chain = url_chain;
web_contents->GetController().LoadURLWithParams(params);
}
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <japhet@chromium.org>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
|
void NavigateOnUIThread(
void NavigateOnUIThread(const GURL& url,
const std::vector<GURL> url_chain,
const Referrer& referrer,
bool has_user_gesture,
const ResourceRequestInfo::WebContentsGetter& wc_getter,
int frame_tree_node_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = wc_getter.Run();
if (web_contents) {
NavigationController::LoadURLParams params(url);
params.has_user_gesture = has_user_gesture;
params.referrer = referrer;
params.redirect_chain = url_chain;
params.frame_tree_node_id = frame_tree_node_id;
web_contents->GetController().LoadURLWithParams(params);
}
}
| 173,024
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer
Bug: 29422020
Bug: 31412859
Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375
(cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2)
CWE ID: CWE-200
|
status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
// update backup buffer
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
| 174,146
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] To avoid divisions by zero / undefined behaviour on shift
Signed-off-by: Young_X <YangX92@hotmail.com>
CWE ID: CWE-369
|
static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
| 169,774
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: omx_vdec::~omx_vdec()
{
m_pmem_info = NULL;
struct v4l2_decoder_cmd dec;
DEBUG_PRINT_HIGH("In OMX vdec Destructor");
if (m_pipe_in) close(m_pipe_in);
if (m_pipe_out) close(m_pipe_out);
m_pipe_in = -1;
m_pipe_out = -1;
DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit");
if (msg_thread_created)
pthread_join(msg_thread_id,NULL);
DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit");
dec.cmd = V4L2_DEC_CMD_STOP;
if (drv_ctx.video_driver_fd >=0 ) {
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec))
DEBUG_PRINT_ERROR("STOP Command failed");
}
if (async_thread_created)
pthread_join(async_thread_id,NULL);
unsubscribe_to_events(drv_ctx.video_driver_fd);
close(drv_ctx.video_driver_fd);
pthread_mutex_destroy(&m_lock);
pthread_mutex_destroy(&c_lock);
sem_destroy(&m_cmd_lock);
if (perf_flag) {
DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME");
dec_time.end();
}
DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd);
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID:
|
omx_vdec::~omx_vdec()
{
m_pmem_info = NULL;
struct v4l2_decoder_cmd dec;
DEBUG_PRINT_HIGH("In OMX vdec Destructor");
if (m_pipe_in) close(m_pipe_in);
if (m_pipe_out) close(m_pipe_out);
m_pipe_in = -1;
m_pipe_out = -1;
DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit");
if (msg_thread_created)
pthread_join(msg_thread_id,NULL);
DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit");
dec.cmd = V4L2_DEC_CMD_STOP;
if (drv_ctx.video_driver_fd >=0 ) {
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec))
DEBUG_PRINT_ERROR("STOP Command failed");
}
if (async_thread_created)
pthread_join(async_thread_id,NULL);
unsubscribe_to_events(drv_ctx.video_driver_fd);
close(drv_ctx.video_driver_fd);
pthread_mutex_destroy(&m_lock);
pthread_mutex_destroy(&c_lock);
pthread_mutex_destroy(&buf_lock);
sem_destroy(&m_cmd_lock);
if (perf_flag) {
DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME");
dec_time.end();
}
DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd);
}
| 173,754
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required,
SyncPromoUI::Source source)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
source_(source),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
| 171,245
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MagickExport void RemoveDuplicateLayers(Image **images,
ExceptionInfo *exception)
{
register Image
*curr,
*next;
RectangleInfo
bounds;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
curr=GetFirstImageInList(*images);
for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next)
{
if ( curr->columns != next->columns || curr->rows != next->rows
|| curr->page.x != next->page.x || curr->page.y != next->page.y )
continue;
bounds=CompareImageBounds(curr,next,CompareAnyLayer,exception);
if ( bounds.x < 0 ) {
/*
the two images are the same, merge time delays and delete one.
*/
size_t time;
time = curr->delay*1000/curr->ticks_per_second;
time += next->delay*1000/next->ticks_per_second;
next->ticks_per_second = 100L;
next->delay = time*curr->ticks_per_second/1000;
next->iterations = curr->iterations;
*images = curr;
(void) DeleteImageFromList(images);
}
}
*images = GetFirstImageInList(*images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629
CWE ID: CWE-369
|
MagickExport void RemoveDuplicateLayers(Image **images,
MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception)
{
RectangleInfo
bounds;
register Image
*image,
*next;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=GetFirstImageInList(*images);
for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next)
{
if ((image->columns != next->columns) || (image->rows != next->rows) ||
(image->page.x != next->page.x) || (image->page.y != next->page.y))
continue;
bounds=CompareImageBounds(image,next,CompareAnyLayer,exception);
if (bounds.x < 0)
{
/*
Two images are the same, merge time delays and delete one.
*/
size_t
time;
time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second);
time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second);
next->ticks_per_second=100L;
next->delay=time*image->ticks_per_second/1000;
next->iterations=image->iterations;
*images=image;
(void) DeleteImageFromList(images);
}
}
*images=GetFirstImageInList(*images);
}
| 169,588
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
|
GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
| 169,171
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DOMWindow::focus(LocalDOMWindow* incumbent_window) {
if (!GetFrame())
return;
Page* page = GetFrame()->GetPage();
if (!page)
return;
DCHECK(incumbent_window);
ExecutionContext* incumbent_execution_context =
incumbent_window->GetExecutionContext();
bool allow_focus = incumbent_execution_context->IsWindowInteractionAllowed();
if (allow_focus) {
incumbent_execution_context->ConsumeWindowInteraction();
} else {
DCHECK(IsMainThread());
allow_focus =
opener() && (opener() != this) &&
(ToDocument(incumbent_execution_context)->domWindow() == opener());
}
if (GetFrame()->IsMainFrame() && allow_focus)
page->GetChromeClient().Focus();
page->GetFocusController().FocusDocumentView(GetFrame(),
true /* notifyEmbedder */);
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
|
void DOMWindow::focus(LocalDOMWindow* incumbent_window) {
if (!GetFrame())
return;
Page* page = GetFrame()->GetPage();
if (!page)
return;
DCHECK(incumbent_window);
ExecutionContext* incumbent_execution_context =
incumbent_window->GetExecutionContext();
bool allow_focus = incumbent_execution_context->IsWindowInteractionAllowed();
if (allow_focus) {
incumbent_execution_context->ConsumeWindowInteraction();
} else {
DCHECK(IsMainThread());
allow_focus =
opener() && (opener() != this) &&
(ToDocument(incumbent_execution_context)->domWindow() == opener());
}
if (GetFrame()->IsMainFrame() && allow_focus)
page->GetChromeClient().Focus(incumbent_window->GetFrame());
page->GetFocusController().FocusDocumentView(GetFrame(),
true /* notifyEmbedder */);
}
| 172,722
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: std::unique_ptr<base::DictionaryValue> ParsePrintSettings(
int command_id,
const base::DictionaryValue* params,
HeadlessPrintSettings* settings) {
if (const base::Value* landscape_value = params->FindKey("landscape"))
settings->landscape = landscape_value->GetBool();
if (const base::Value* display_header_footer_value =
params->FindKey("displayHeaderFooter")) {
settings->display_header_footer = display_header_footer_value->GetBool();
}
if (const base::Value* should_print_backgrounds_value =
params->FindKey("printBackground")) {
settings->should_print_backgrounds =
should_print_backgrounds_value->GetBool();
}
if (const base::Value* scale_value = params->FindKey("scale"))
settings->scale = scale_value->GetDouble();
if (settings->scale > kScaleMaxVal / 100 ||
settings->scale < kScaleMinVal / 100)
return CreateInvalidParamResponse(command_id, "scale");
if (const base::Value* page_ranges_value = params->FindKey("pageRanges"))
settings->page_ranges = page_ranges_value->GetString();
if (const base::Value* ignore_invalid_page_ranges_value =
params->FindKey("ignoreInvalidPageRanges")) {
settings->ignore_invalid_page_ranges =
ignore_invalid_page_ranges_value->GetBool();
}
double paper_width_in_inch = printing::kLetterWidthInch;
if (const base::Value* paper_width_value = params->FindKey("paperWidth"))
paper_width_in_inch = paper_width_value->GetDouble();
double paper_height_in_inch = printing::kLetterHeightInch;
if (const base::Value* paper_height_value = params->FindKey("paperHeight"))
paper_height_in_inch = paper_height_value->GetDouble();
if (paper_width_in_inch <= 0)
return CreateInvalidParamResponse(command_id, "paperWidth");
if (paper_height_in_inch <= 0)
return CreateInvalidParamResponse(command_id, "paperHeight");
settings->paper_size_in_points =
gfx::Size(paper_width_in_inch * printing::kPointsPerInch,
paper_height_in_inch * printing::kPointsPerInch);
double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch;
double margin_top_in_inch = default_margin_in_inch;
double margin_bottom_in_inch = default_margin_in_inch;
double margin_left_in_inch = default_margin_in_inch;
double margin_right_in_inch = default_margin_in_inch;
if (const base::Value* margin_top_value = params->FindKey("marginTop"))
margin_top_in_inch = margin_top_value->GetDouble();
if (const base::Value* margin_bottom_value = params->FindKey("marginBottom"))
margin_bottom_in_inch = margin_bottom_value->GetDouble();
if (const base::Value* margin_left_value = params->FindKey("marginLeft"))
margin_left_in_inch = margin_left_value->GetDouble();
if (const base::Value* margin_right_value = params->FindKey("marginRight"))
margin_right_in_inch = margin_right_value->GetDouble();
if (margin_top_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginTop");
if (margin_bottom_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginBottom");
if (margin_left_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginLeft");
if (margin_right_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginRight");
settings->margins_in_points.top =
margin_top_in_inch * printing::kPointsPerInch;
settings->margins_in_points.bottom =
margin_bottom_in_inch * printing::kPointsPerInch;
settings->margins_in_points.left =
margin_left_in_inch * printing::kPointsPerInch;
settings->margins_in_points.right =
margin_right_in_inch * printing::kPointsPerInch;
return nullptr;
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Jianzhou Feng <jzfeng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20
|
std::unique_ptr<base::DictionaryValue> ParsePrintSettings(
int command_id,
const base::DictionaryValue* params,
HeadlessPrintSettings* settings) {
if (const base::Value* landscape_value = params->FindKey("landscape"))
settings->landscape = landscape_value->GetBool();
if (const base::Value* display_header_footer_value =
params->FindKey("displayHeaderFooter")) {
settings->display_header_footer = display_header_footer_value->GetBool();
}
if (const base::Value* should_print_backgrounds_value =
params->FindKey("printBackground")) {
settings->should_print_backgrounds =
should_print_backgrounds_value->GetBool();
}
if (const base::Value* scale_value = params->FindKey("scale"))
settings->scale = scale_value->GetDouble();
if (settings->scale > kScaleMaxVal / 100 ||
settings->scale < kScaleMinVal / 100)
return CreateInvalidParamResponse(command_id, "scale");
if (const base::Value* page_ranges_value = params->FindKey("pageRanges"))
settings->page_ranges = page_ranges_value->GetString();
if (const base::Value* ignore_invalid_page_ranges_value =
params->FindKey("ignoreInvalidPageRanges")) {
settings->ignore_invalid_page_ranges =
ignore_invalid_page_ranges_value->GetBool();
}
double paper_width_in_inch = printing::kLetterWidthInch;
if (const base::Value* paper_width_value = params->FindKey("paperWidth"))
paper_width_in_inch = paper_width_value->GetDouble();
double paper_height_in_inch = printing::kLetterHeightInch;
if (const base::Value* paper_height_value = params->FindKey("paperHeight"))
paper_height_in_inch = paper_height_value->GetDouble();
if (paper_width_in_inch <= 0)
return CreateInvalidParamResponse(command_id, "paperWidth");
if (paper_height_in_inch <= 0)
return CreateInvalidParamResponse(command_id, "paperHeight");
settings->paper_size_in_points =
gfx::Size(paper_width_in_inch * printing::kPointsPerInch,
paper_height_in_inch * printing::kPointsPerInch);
double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch;
double margin_top_in_inch = default_margin_in_inch;
double margin_bottom_in_inch = default_margin_in_inch;
double margin_left_in_inch = default_margin_in_inch;
double margin_right_in_inch = default_margin_in_inch;
if (const base::Value* margin_top_value = params->FindKey("marginTop"))
margin_top_in_inch = margin_top_value->GetDouble();
if (const base::Value* margin_bottom_value = params->FindKey("marginBottom"))
margin_bottom_in_inch = margin_bottom_value->GetDouble();
if (const base::Value* margin_left_value = params->FindKey("marginLeft"))
margin_left_in_inch = margin_left_value->GetDouble();
if (const base::Value* margin_right_value = params->FindKey("marginRight"))
margin_right_in_inch = margin_right_value->GetDouble();
if (const base::Value* header_template_value =
params->FindKey("headerTemplate")) {
settings->header_template = header_template_value->GetString();
}
if (const base::Value* footer_template_value =
params->FindKey("footerTemplate")) {
settings->footer_template = footer_template_value->GetString();
}
if (margin_top_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginTop");
if (margin_bottom_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginBottom");
if (margin_left_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginLeft");
if (margin_right_in_inch < 0)
return CreateInvalidParamResponse(command_id, "marginRight");
settings->margins_in_points.top =
margin_top_in_inch * printing::kPointsPerInch;
settings->margins_in_points.bottom =
margin_bottom_in_inch * printing::kPointsPerInch;
settings->margins_in_points.left =
margin_left_in_inch * printing::kPointsPerInch;
settings->margins_in_points.right =
margin_right_in_inch * printing::kPointsPerInch;
return nullptr;
}
| 172,901
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Block* BlockGroup::GetBlock() const
{
return &m_block;
}
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 Block* BlockGroup::GetBlock() const
| 174,286
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: size_t OpenMP4SourceUDTA(char *filename)
{
mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));
if (mp4 == NULL) return 0;
memset(mp4, 0, sizeof(mp4object));
#ifdef _WINDOWS
fopen_s(&mp4->mediafp, filename, "rb");
#else
mp4->mediafp = fopen(filename, "rb");
#endif
if (mp4->mediafp)
{
uint32_t qttag, qtsize32, len;
int32_t nest = 0;
uint64_t nestsize[MAX_NEST_LEVEL] = { 0 };
uint64_t lastsize = 0, qtsize;
do
{
len = fread(&qtsize32, 1, 4, mp4->mediafp);
len += fread(&qttag, 1, 4, mp4->mediafp);
if (len == 8)
{
if (!GPMF_VALID_FOURCC(qttag))
{
LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR);
NESTSIZE(lastsize - 8);
continue;
}
qtsize32 = BYTESWAP32(qtsize32);
if (qtsize32 == 1) // 64-bit Atom
{
fread(&qtsize, 1, 8, mp4->mediafp);
qtsize = BYTESWAP64(qtsize) - 8;
}
else
qtsize = qtsize32;
nest++;
if (qtsize < 8) break;
if (nest >= MAX_NEST_LEVEL) break;
nestsize[nest] = qtsize;
lastsize = qtsize;
if (qttag == MAKEID('m', 'd', 'a', 't') ||
qttag == MAKEID('f', 't', 'y', 'p'))
{
LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);
NESTSIZE(qtsize);
continue;
}
if (qttag == MAKEID('G', 'P', 'M', 'F'))
{
mp4->videolength += 1.0;
mp4->metadatalength += 1.0;
mp4->indexcount = (int)mp4->metadatalength;
mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);
mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);
mp4->metasizes[0] = (int)qtsize - 8;
mp4->metaoffsets[0] = ftell(mp4->mediafp);
mp4->metasize_count = 1;
return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.
}
if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms
qttag != MAKEID('u', 'd', 't', 'a'))
{
LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);
NESTSIZE(qtsize);
continue;
}
else
{
NESTSIZE(8);
}
}
} while (len > 0);
}
return (size_t)mp4;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787
|
size_t OpenMP4SourceUDTA(char *filename)
{
mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));
if (mp4 == NULL) return 0;
memset(mp4, 0, sizeof(mp4object));
#ifdef _WINDOWS
fopen_s(&mp4->mediafp, filename, "rb");
#else
mp4->mediafp = fopen(filename, "rb");
#endif
if (mp4->mediafp)
{
uint32_t qttag, qtsize32;
size_t len;
int32_t nest = 0;
uint64_t nestsize[MAX_NEST_LEVEL] = { 0 };
uint64_t lastsize = 0, qtsize;
do
{
len = fread(&qtsize32, 1, 4, mp4->mediafp);
len += fread(&qttag, 1, 4, mp4->mediafp);
if (len == 8)
{
if (!GPMF_VALID_FOURCC(qttag))
{
LongSeek(mp4, lastsize - 8 - 8);
NESTSIZE(lastsize - 8);
continue;
}
qtsize32 = BYTESWAP32(qtsize32);
if (qtsize32 == 1) // 64-bit Atom
{
fread(&qtsize, 1, 8, mp4->mediafp);
qtsize = BYTESWAP64(qtsize) - 8;
}
else
qtsize = qtsize32;
nest++;
if (qtsize < 8) break;
if (nest >= MAX_NEST_LEVEL) break;
nestsize[nest] = qtsize;
lastsize = qtsize;
if (qttag == MAKEID('m', 'd', 'a', 't') ||
qttag == MAKEID('f', 't', 'y', 'p'))
{
LongSeek(mp4, qtsize - 8);
NESTSIZE(qtsize);
continue;
}
if (qttag == MAKEID('G', 'P', 'M', 'F'))
{
mp4->videolength += 1.0;
mp4->metadatalength += 1.0;
mp4->indexcount = (int)mp4->metadatalength;
mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);
mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);
mp4->metasizes[0] = (int)qtsize - 8;
mp4->metaoffsets[0] = ftell(mp4->mediafp);
mp4->metasize_count = 1;
return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.
}
if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms
qttag != MAKEID('u', 'd', 't', 'a'))
{
LongSeek(mp4, qtsize - 8);
NESTSIZE(qtsize);
continue;
}
else
{
NESTSIZE(8);
}
}
} while (len > 0);
}
return (size_t)mp4;
}
| 169,551
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric)
{
NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config);
guint32 mtu = nm_ip4_config_get_mtu (config);
int i;
g_return_val_if_fail (ifindex > 0, FALSE);
g_return_val_if_fail (ifindex > 0, FALSE);
g_return_val_if_fail (config != NULL, FALSE);
/* Addresses */
nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric);
/* Routes */
{
int count = nm_ip4_config_get_num_routes (config);
GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count);
const NMPlatformIP4Route *route;
gboolean success;
for (i = 0; i < count; i++) {
route = nm_ip4_config_get_route (config, i);
/* Don't add the route if it's more specific than one of the subnets
* the device already has an IP address on.
*/
if ( route->gateway == 0
&& nm_ip4_config_destination_is_direct (config, route->network, route->plen))
continue;
g_array_append_vals (routes, route, 1);
}
success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes);
g_array_unref (routes);
return FALSE;
}
/* MTU */
if (mtu && mtu != nm_platform_link_get_mtu (ifindex))
nm_platform_link_set_mtu (ifindex, mtu);
return TRUE;
}
Commit Message:
CWE ID: CWE-20
|
nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric)
{
NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config);
int i;
g_return_val_if_fail (ifindex > 0, FALSE);
g_return_val_if_fail (ifindex > 0, FALSE);
g_return_val_if_fail (config != NULL, FALSE);
/* Addresses */
nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric);
/* Routes */
{
int count = nm_ip4_config_get_num_routes (config);
GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count);
const NMPlatformIP4Route *route;
gboolean success;
for (i = 0; i < count; i++) {
route = nm_ip4_config_get_route (config, i);
/* Don't add the route if it's more specific than one of the subnets
* the device already has an IP address on.
*/
if ( route->gateway == 0
&& nm_ip4_config_destination_is_direct (config, route->network, route->plen))
continue;
g_array_append_vals (routes, route, 1);
}
success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes);
g_array_unref (routes);
return FALSE;
}
return TRUE;
}
| 164,815
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_device(dev_t *pdev, struct archive *a, char *val)
{
#define MAX_PACK_ARGS 3
unsigned long numbers[MAX_PACK_ARGS];
char *p, *dev;
int argc;
pack_t *pack;
dev_t result;
const char *error = NULL;
memset(pdev, 0, sizeof(*pdev));
if ((dev = strchr(val, ',')) != NULL) {
/*
* Device's major/minor are given in a specified format.
* Decode and pack it accordingly.
*/
*dev++ = '\0';
if ((pack = pack_find(val)) == NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown format `%s'", val);
return ARCHIVE_WARN;
}
argc = 0;
while ((p = la_strsep(&dev, ",")) != NULL) {
if (*p == '\0') {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing number");
return ARCHIVE_WARN;
}
numbers[argc++] = (unsigned long)mtree_atol(&p);
if (argc > MAX_PACK_ARGS) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Too many arguments");
return ARCHIVE_WARN;
}
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Not enough arguments");
return ARCHIVE_WARN;
}
result = (*pack)(argc, numbers, &error);
if (error != NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"%s", error);
return ARCHIVE_WARN;
}
} else {
/* file system raw value. */
result = (dev_t)mtree_atol(&val);
}
*pdev = result;
return ARCHIVE_OK;
#undef MAX_PACK_ARGS
}
Commit Message: Fix libarchive/archive_read_support_format_mtree.c:1388:11: error: array subscript is above array bounds
CWE ID: CWE-119
|
parse_device(dev_t *pdev, struct archive *a, char *val)
{
#define MAX_PACK_ARGS 3
unsigned long numbers[MAX_PACK_ARGS];
char *p, *dev;
int argc;
pack_t *pack;
dev_t result;
const char *error = NULL;
memset(pdev, 0, sizeof(*pdev));
if ((dev = strchr(val, ',')) != NULL) {
/*
* Device's major/minor are given in a specified format.
* Decode and pack it accordingly.
*/
*dev++ = '\0';
if ((pack = pack_find(val)) == NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown format `%s'", val);
return ARCHIVE_WARN;
}
argc = 0;
while ((p = la_strsep(&dev, ",")) != NULL) {
if (*p == '\0') {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing number");
return ARCHIVE_WARN;
}
if (argc >= MAX_PACK_ARGS) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Too many arguments");
return ARCHIVE_WARN;
}
numbers[argc++] = (unsigned long)mtree_atol(&p);
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Not enough arguments");
return ARCHIVE_WARN;
}
result = (*pack)(argc, numbers, &error);
if (error != NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"%s", error);
return ARCHIVE_WARN;
}
} else {
/* file system raw value. */
result = (dev_t)mtree_atol(&val);
}
*pdev = result;
return ARCHIVE_OK;
#undef MAX_PACK_ARGS
}
| 167,320
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster::ParseSimpleBlock(long long block_size, long long& pos,
long& len) {
const long long block_start = pos;
const long long block_stop = pos + block_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
#if 0
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return E_FILE_FORMAT_INVALID;
#endif
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
status = CreateBlock(0x23, // simple block id
block_start, block_size,
0); // DiscardPadding
if (status != 0)
return status;
m_pos = block_stop;
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Cluster::ParseSimpleBlock(long long block_size, long long& pos,
long& len) {
const long long block_start = pos;
const long long block_stop = pos + block_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
status = CreateBlock(0x23, // simple block id
block_start, block_size,
0); // DiscardPadding
if (status != 0)
return status;
m_pos = block_stop;
return 0; // success
}
| 173,858
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net_device *dev;
struct net *net = sock_net(skb->sk);
struct nlmsghdr *nlh = NULL;
int idx = 0, s_idx;
s_idx = cb->args[0];
rcu_read_lock();
/* In theory this could be wrapped to 0... */
cb->seq = net->dev_base_seq + br_mdb_rehash_seq;
for_each_netdev_rcu(net, dev) {
if (dev->priv_flags & IFF_EBRIDGE) {
struct br_port_msg *bpm;
if (idx < s_idx)
goto skip;
nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, RTM_GETMDB,
sizeof(*bpm), NLM_F_MULTI);
if (nlh == NULL)
break;
bpm = nlmsg_data(nlh);
bpm->ifindex = dev->ifindex;
if (br_mdb_fill_info(skb, cb, dev) < 0)
goto out;
if (br_rports_fill_info(skb, cb, dev) < 0)
goto out;
cb->args[1] = 0;
nlmsg_end(skb, nlh);
skip:
idx++;
}
}
out:
if (nlh)
nlmsg_end(skb, nlh);
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
Commit Message: bridge: fix mdb info leaks
The bridging code discloses heap and stack bytes via the RTM_GETMDB
netlink interface and via the notify messages send to group RTNLGRP_MDB
afer a successful add/del.
Fix both cases by initializing all unset members/padding bytes with
memset(0).
Cc: Stephen Hemminger <stephen@networkplumber.org>
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-399
|
static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net_device *dev;
struct net *net = sock_net(skb->sk);
struct nlmsghdr *nlh = NULL;
int idx = 0, s_idx;
s_idx = cb->args[0];
rcu_read_lock();
/* In theory this could be wrapped to 0... */
cb->seq = net->dev_base_seq + br_mdb_rehash_seq;
for_each_netdev_rcu(net, dev) {
if (dev->priv_flags & IFF_EBRIDGE) {
struct br_port_msg *bpm;
if (idx < s_idx)
goto skip;
nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, RTM_GETMDB,
sizeof(*bpm), NLM_F_MULTI);
if (nlh == NULL)
break;
bpm = nlmsg_data(nlh);
memset(bpm, 0, sizeof(*bpm));
bpm->ifindex = dev->ifindex;
if (br_mdb_fill_info(skb, cb, dev) < 0)
goto out;
if (br_rports_fill_info(skb, cb, dev) < 0)
goto out;
cb->args[1] = 0;
nlmsg_end(skb, nlh);
skip:
idx++;
}
}
out:
if (nlh)
nlmsg_end(skb, nlh);
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
| 166,052
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: unsigned char *base64decode(const char *buf, size_t *size)
{
if (!buf || !size) return NULL;
size_t len = (*size > 0) ? *size : strlen(buf);
if (len <= 0) return NULL;
unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3);
const char *ptr = buf;
int p = 0;
size_t l = 0;
do {
ptr += strspn(ptr, "\r\n\t ");
if (*ptr == '\0' || ptr >= buf+len) {
break;
}
l = strcspn(ptr, "\r\n\t ");
if (l > 3 && ptr+l <= buf+len) {
p+=base64decode_block(outbuf+p, ptr, l);
ptr += l;
} else {
break;
}
} while (1);
outbuf[p] = 0;
*size = p;
return outbuf;
}
Commit Message: base64: Rework base64decode to handle split encoded data correctly
CWE ID: CWE-125
|
unsigned char *base64decode(const char *buf, size_t *size)
{
if (!buf || !size) return NULL;
size_t len = (*size > 0) ? *size : strlen(buf);
if (len <= 0) return NULL;
unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3);
const char *ptr = buf;
int p = 0;
int wv, w1, w2, w3, w4;
int tmpval[4];
int tmpcnt = 0;
do {
while (ptr < buf+len && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n' || *ptr == '\r')) {
ptr++;
}
if (*ptr == '\0' || ptr >= buf+len) {
break;
}
if ((wv = base64_table[(int)(unsigned char)*ptr++]) == -1) {
continue;
}
tmpval[tmpcnt++] = wv;
if (tmpcnt == 4) {
tmpcnt = 0;
w1 = tmpval[0];
w2 = tmpval[1];
w3 = tmpval[2];
w4 = tmpval[3];
if (w2 >= 0) {
outbuf[p++] = (unsigned char)(((w1 << 2) + (w2 >> 4)) & 0xFF);
}
if (w3 >= 0) {
outbuf[p++] = (unsigned char)(((w2 << 4) + (w3 >> 2)) & 0xFF);
}
if (w4 >= 0) {
outbuf[p++] = (unsigned char)(((w3 << 6) + w4) & 0xFF);
}
}
} while (1);
outbuf[p] = 0;
*size = p;
return outbuf;
}
| 168,416
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
}
Commit Message:
CWE ID: CWE-704
|
znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
if (r_type(pnval) != t_integer)
return gs_note_error(gs_error_typecheck);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
}
| 164,635
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <jmattson@google.com>
Cc: stable@vger.kernel.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-388
|
static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if (is_nmi(intr_info))
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
| 166,854
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: nfs3svc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readlinkargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
nfs3svc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readlinkargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
if (!xdr_argsize_check(rqstp, p))
return 0;
args->buffer = page_address(*(rqstp->rq_next_page++));
return 1;
}
| 168,143
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
GetRenderManager()->set_interstitial_page(interstitial_page);
CancelActiveAndPendingDialogs();
for (auto& observer : observers_)
observer.DidAttachInterstitialPage();
if (frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(
static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
interstitial_page->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
}
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::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(!interstitial_page_ && interstitial_page);
interstitial_page_ = interstitial_page;
CancelActiveAndPendingDialogs();
for (auto& observer : observers_)
observer.DidAttachInterstitialPage();
if (frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(
static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
interstitial_page->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
}
| 172,324
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WorkerProcessLauncherTest::SetUp() {
task_runner_ = new AutoThreadTaskRunner(
message_loop_.message_loop_proxy(),
base::Bind(&WorkerProcessLauncherTest::QuitMainMessageLoop,
base::Unretained(this)));
exit_code_ = STILL_ACTIVE;
launcher_delegate_.reset(new MockProcessLauncherDelegate());
EXPECT_CALL(*launcher_delegate_, Send(_))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(*launcher_delegate_, GetExitCode())
.Times(AnyNumber())
.WillRepeatedly(ReturnPointee(&exit_code_));
EXPECT_CALL(*launcher_delegate_, KillProcess(_))
.Times(AnyNumber())
.WillRepeatedly(Invoke(this, &WorkerProcessLauncherTest::KillProcess));
EXPECT_CALL(ipc_delegate_, OnMessageReceived(_))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void WorkerProcessLauncherTest::SetUp() {
task_runner_ = new AutoThreadTaskRunner(
message_loop_.message_loop_proxy(),
base::Bind(&WorkerProcessLauncherTest::QuitMainMessageLoop,
base::Unretained(this)));
launcher_delegate_.reset(new MockProcessLauncherDelegate());
EXPECT_CALL(*launcher_delegate_, Send(_))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(*launcher_delegate_, GetProcessId())
.Times(AnyNumber())
.WillRepeatedly(ReturnPointee(&client_pid_));
EXPECT_CALL(*launcher_delegate_, IsPermanentError(_))
.Times(AnyNumber())
.WillRepeatedly(ReturnPointee(&permanent_error_));
EXPECT_CALL(*launcher_delegate_, KillProcess(_))
.Times(AnyNumber())
.WillRepeatedly(Invoke(this, &WorkerProcessLauncherTest::KillProcess));
EXPECT_CALL(ipc_delegate_, OnMessageReceived(_))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
}
| 171,552
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: WORD32 ih264d_parse_sei_message(dec_struct_t *ps_dec,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 ui4_payload_type, ui4_payload_size;
UWORD32 u4_bits;
WORD32 i4_status = 0;
do
{
ui4_payload_type = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits)
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_type += 255;
}
ui4_payload_type += u4_bits;
ui4_payload_size = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits)
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_size += 255;
}
ui4_payload_size += u4_bits;
i4_status = ih264d_parse_sei_payload(ps_bitstrm, ui4_payload_type,
ui4_payload_size, ps_dec);
if(i4_status == -1)
{
i4_status = 0;
break;
}
if(i4_status != OK)
return i4_status;
if(ih264d_check_byte_aligned(ps_bitstrm) == 0)
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(0 == u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
while(0 == ih264d_check_byte_aligned(ps_bitstrm))
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
}
}
}
while(ps_bitstrm->u4_ofst < ps_bitstrm->u4_max_ofst);
return (i4_status);
}
Commit Message: Decoder: Increased allocation and added checks in sei parsing.
This prevents heap overflow while parsing sei_message.
Bug: 63122634
Test: ran PoC on unpatched/patched
Change-Id: I61c1ff4ac053a060be8c24da4671db985cac628c
(cherry picked from commit f2b70d353768af8d4ead7f32497be05f197925ef)
CWE ID: CWE-200
|
WORD32 ih264d_parse_sei_message(dec_struct_t *ps_dec,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 ui4_payload_type, ui4_payload_size;
UWORD32 u4_bits;
WORD32 i4_status = 0;
do
{
ui4_payload_type = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits && !EXCEED_OFFSET(ps_bitstrm))
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_type += 255;
}
ui4_payload_type += u4_bits;
ui4_payload_size = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits && !EXCEED_OFFSET(ps_bitstrm))
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_size += 255;
}
ui4_payload_size += u4_bits;
i4_status = ih264d_parse_sei_payload(ps_bitstrm, ui4_payload_type,
ui4_payload_size, ps_dec);
if(i4_status == -1)
{
i4_status = 0;
break;
}
if(i4_status != OK)
return i4_status;
if(ih264d_check_byte_aligned(ps_bitstrm) == 0)
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(0 == u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
while(0 == ih264d_check_byte_aligned(ps_bitstrm)
&& !EXCEED_OFFSET(ps_bitstrm))
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
}
}
}
while(ps_bitstrm->u4_ofst < ps_bitstrm->u4_max_ofst);
return (i4_status);
}
| 174,107
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
n = r->sector_count;
if (n > SCSI_DMA_BUF_SIZE / 512)
n = SCSI_DMA_BUF_SIZE / 512;
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
r->iov.iov_len = n * 512;
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
Commit Message: scsi-disk: commonize iovec creation between reads and writes
Also, consistently use qiov.size instead of iov.iov_len.
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
CWE ID: CWE-119
|
static void scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
n = scsi_init_iovec(r);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
| 169,921
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
exit_code_ = exit_code;
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
| 171,550
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: hb_buffer_ensure (hb_buffer_t *buffer, unsigned int size)
{
unsigned int new_allocated = buffer->allocated;
if (size > new_allocated)
{
while (size > new_allocated)
new_allocated += (new_allocated >> 1) + 8;
if (buffer->pos)
buffer->pos = (hb_internal_glyph_position_t *) realloc (buffer->pos, new_allocated * sizeof (buffer->pos[0]));
if (buffer->out_info != buffer->info)
{
buffer->info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0]));
buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos;
}
else
{
buffer->info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0]));
buffer->out_info = buffer->info;
}
buffer->allocated = new_allocated;
}
}
Commit Message:
CWE ID:
|
hb_buffer_ensure (hb_buffer_t *buffer, unsigned int size)
{
if (unlikely (size > buffer->allocated))
{
if (unlikely (buffer->in_error))
return FALSE;
unsigned int new_allocated = buffer->allocated;
hb_internal_glyph_position_t *new_pos;
hb_internal_glyph_info_t *new_info;
bool separate_out;
separate_out = buffer->out_info != buffer->info;
while (size > new_allocated)
new_allocated += (new_allocated >> 1) + 8;
new_pos = (hb_internal_glyph_position_t *) realloc (buffer->pos, new_allocated * sizeof (buffer->pos[0]));
new_info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0]));
if (unlikely (!new_pos || !new_info))
buffer->in_error = TRUE;
if (likely (new_pos))
buffer->pos = new_pos;
if (likely (new_info))
buffer->info = new_info;
buffer->out_info = separate_out ? (hb_internal_glyph_info_t *) buffer->pos : buffer->info;
if (likely (!buffer->in_error))
buffer->allocated = new_allocated;
}
return likely (!buffer->in_error);
}
| 164,774
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: CStarter::removeDeferredJobs() {
bool ret = true;
if ( this->deferral_tid == -1 ) {
return ( ret );
}
m_deferred_job_update = true;
if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) {
dprintf( D_FULLDEBUG, "Cancelled time deferred execution for "
"Job %d.%d\n",
this->jic->jobCluster(),
this->jic->jobProc() );
this->deferral_tid = -1;
} else {
MyString error = "Failed to cancel deferred execution timer for Job ";
error += this->jic->jobCluster();
error += ".";
error += this->jic->jobProc();
EXCEPT( error.Value() );
ret = false;
}
return ( ret );
}
Commit Message:
CWE ID: CWE-134
|
CStarter::removeDeferredJobs() {
bool ret = true;
if ( this->deferral_tid == -1 ) {
return ( ret );
}
m_deferred_job_update = true;
if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) {
dprintf( D_FULLDEBUG, "Cancelled time deferred execution for "
"Job %d.%d\n",
this->jic->jobCluster(),
this->jic->jobProc() );
this->deferral_tid = -1;
} else {
MyString error = "Failed to cancel deferred execution timer for Job ";
error += this->jic->jobCluster();
error += ".";
error += this->jic->jobProc();
EXCEPT( "%s", error.Value() );
ret = false;
}
return ( ret );
}
| 165,379
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: name_len(netdissect_options *ndo,
const unsigned char *s, const unsigned char *maxbuf)
{
const unsigned char *s0 = s;
unsigned char c;
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
c = *s;
if ((c & 0xC0) == 0xC0)
return(2);
while (*s) {
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
s += (*s) + 1;
}
return(PTR_DIFF(s, s0) + 1);
trunc:
return(-1); /* name goes past the end of the buffer */
}
Commit Message: CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len().
After we advance the pointer by the length value in the buffer, make
sure it points to something in the captured data.
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
|
name_len(netdissect_options *ndo,
const unsigned char *s, const unsigned char *maxbuf)
{
const unsigned char *s0 = s;
unsigned char c;
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
c = *s;
if ((c & 0xC0) == 0xC0)
return(2);
while (*s) {
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
s += (*s) + 1;
ND_TCHECK2(*s, 1);
}
return(PTR_DIFF(s, s0) + 1);
trunc:
return(-1); /* name goes past the end of the buffer */
}
| 167,961
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
MIMETypeCheck mime_type_check) const {
if (ErrorOccurred())
return false;
KURL sheet_url = GetResponse().Url();
if (sheet_url.IsLocalFile()) {
if (parser_context) {
parser_context->Count(WebFeature::kLocalCSSFile);
}
String extension;
int last_dot = sheet_url.LastPathComponent().ReverseFind('.');
if (last_dot != -1)
extension = sheet_url.LastPathComponent().Substring(last_dot + 1);
if (!EqualIgnoringASCIICase(
MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) {
if (parser_context) {
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
if (RuntimeEnabledFeatures::RequireCSSExtensionForFileEnabled()) {
return false;
}
}
}
if (mime_type_check == MIMETypeCheck::kLax)
return true;
AtomicString content_type = HttpContentType();
return content_type.IsEmpty() ||
DeprecatedEqualIgnoringCase(content_type, "text/css") ||
DeprecatedEqualIgnoringCase(content_type,
"application/x-unknown-content-type");
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <mkwst@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Dave Tapuska <dtapuska@chromium.org>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254
|
bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
MIMETypeCheck mime_type_check) const {
if (ErrorOccurred())
return false;
KURL sheet_url = GetResponse().Url();
if (sheet_url.IsLocalFile()) {
if (parser_context) {
parser_context->Count(WebFeature::kLocalCSSFile);
}
String extension;
int last_dot = sheet_url.LastPathComponent().ReverseFind('.');
if (last_dot != -1)
extension = sheet_url.LastPathComponent().Substring(last_dot + 1);
if (!EqualIgnoringASCIICase(
MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) {
if (parser_context) {
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
return false;
}
}
if (mime_type_check == MIMETypeCheck::kLax)
return true;
AtomicString content_type = HttpContentType();
return content_type.IsEmpty() ||
DeprecatedEqualIgnoringCase(content_type, "text/css") ||
DeprecatedEqualIgnoringCase(content_type,
"application/x-unknown-content-type");
}
| 173,186
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 inode *isofs_iget(struct super_block *sb,
unsigned long block,
unsigned long offset)
{
unsigned long hashval;
struct inode *inode;
struct isofs_iget5_callback_data data;
long ret;
if (offset >= 1ul << sb->s_blocksize_bits)
return ERR_PTR(-EINVAL);
data.block = block;
data.offset = offset;
hashval = (block << sb->s_blocksize_bits) | offset;
inode = iget5_locked(sb, hashval, &isofs_iget5_test,
&isofs_iget5_set, &data);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
ret = isofs_read_inode(inode);
if (ret < 0) {
iget_failed(inode);
inode = ERR_PTR(ret);
} else {
unlock_new_inode(inode);
}
}
return inode;
}
Commit Message: isofs: Fix unbounded recursion when processing relocated directories
We did not check relocated directory in any way when processing Rock
Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL
entry pointing to another CL entry leading to possibly unbounded
recursion in kernel code and thus stack overflow or deadlocks (if there
is a loop created from CL entries).
Fix the problem by not allowing CL entry to point to a directory entry
with CL entry (such use makes no good sense anyway) and by checking
whether CL entry doesn't point to itself.
CC: stable@vger.kernel.org
Reported-by: Chris Evans <cevans@google.com>
Signed-off-by: Jan Kara <jack@suse.cz>
CWE ID: CWE-20
|
struct inode *isofs_iget(struct super_block *sb,
struct inode *__isofs_iget(struct super_block *sb,
unsigned long block,
unsigned long offset,
int relocated)
{
unsigned long hashval;
struct inode *inode;
struct isofs_iget5_callback_data data;
long ret;
if (offset >= 1ul << sb->s_blocksize_bits)
return ERR_PTR(-EINVAL);
data.block = block;
data.offset = offset;
hashval = (block << sb->s_blocksize_bits) | offset;
inode = iget5_locked(sb, hashval, &isofs_iget5_test,
&isofs_iget5_set, &data);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
ret = isofs_read_inode(inode, relocated);
if (ret < 0) {
iget_failed(inode);
inode = ERR_PTR(ret);
} else {
unlock_new_inode(inode);
}
}
return inode;
}
| 166,268
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
*/
if (ns_capable(ns->parent, cap_setid))
return true;
return false;
}
Commit Message: userns: Don't let unprivileged users trick privileged users into setting the id_map
When we require privilege for setting /proc/<pid>/uid_map or
/proc/<pid>/gid_map no longer allow an unprivileged user to
open the file and pass it to a privileged program to write
to the file.
Instead when privilege is required require both the opener and the
writer to have the necessary capabilities.
I have tested this code and verified that setting /proc/<pid>/uid_map
fails when an unprivileged user opens the file and a privielged user
attempts to set the mapping, that unprivileged users can still map
their own id, and that a privileged users can still setup an arbitrary
mapping.
Reported-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
CWE ID: CWE-264
|
static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid,
static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
| 166,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: RGBA32 AXNodeObject::colorValue() const {
if (!isHTMLInputElement(getNode()) || !isColorWell())
return AXObject::colorValue();
HTMLInputElement* input = toHTMLInputElement(getNode());
const AtomicString& type = input->getAttribute(typeAttr);
if (!equalIgnoringCase(type, "color"))
return AXObject::colorValue();
Color color;
bool success = color.setFromString(input->value());
DCHECK(success);
return color.rgb();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
RGBA32 AXNodeObject::colorValue() const {
if (!isHTMLInputElement(getNode()) || !isColorWell())
return AXObject::colorValue();
HTMLInputElement* input = toHTMLInputElement(getNode());
const AtomicString& type = input->getAttribute(typeAttr);
if (!equalIgnoringASCIICase(type, "color"))
return AXObject::colorValue();
Color color;
bool success = color.setFromString(input->value());
DCHECK(success);
return color.rgb();
}
| 171,910
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Tracks::~Tracks()
{
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j)
{
Track* const pTrack = *i++;
delete pTrack;
}
delete[] m_trackEntries;
}
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
|
Tracks::~Tracks()
| 174,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: bt_status_t btif_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr,
LINK_KEY link_key,
uint8_t key_type,
uint8_t pin_length)
{
bdstr_t bdstr;
bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type);
ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length);
ret &= btif_config_set_bin(bdstr, "LinkKey", link_key, sizeof(LINK_KEY));
/* write bonded info immediately */
btif_config_flush();
return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20
|
bt_status_t btif_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr,
LINK_KEY link_key,
uint8_t key_type,
uint8_t pin_length)
{
bdstr_t bdstr;
bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type);
ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length);
ret &= btif_config_set_bin(bdstr, "LinkKey", link_key, sizeof(LINK_KEY));
if (is_restricted_mode()) {
BTIF_TRACE_WARNING("%s: '%s' pairing will be removed if unrestricted",
__func__, bdstr);
btif_config_set_int(bdstr, "Restricted", 1);
}
/* write bonded info immediately */
btif_config_flush();
return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
}
| 173,554
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
pipe_buf_get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
out:
kvfree(bufs);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416
|
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len)
goto out_free;
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
if (!pipe_buf_get(pipe, ibuf))
goto out_free;
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
out_free:
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
kvfree(bufs);
return ret;
}
| 170,217
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PrintWebViewHelper::Print(WebKit::WebFrame* frame, WebKit::WebNode* node) {
if (print_web_view_)
return;
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(frame, node, &prepare))
return; // Failed to init print page settings.
int expected_page_count = 0;
bool use_browser_overlays = true;
expected_page_count = prepare->GetExpectedPageCount();
if (expected_page_count)
use_browser_overlays = prepare->ShouldUseBrowserOverlays();
prepare.reset();
if (!expected_page_count) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!GetPrintSettingsFromUser(frame, expected_page_count,
use_browser_overlays)) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!RenderPagesForPrint(frame, node, NULL)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
ResetScriptedPrintCount();
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PrintWebViewHelper::Print(WebKit::WebFrame* frame, WebKit::WebNode* node) {
if (print_web_view_)
return;
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(frame, node, &prepare)) {
DidFinishPrinting(FAIL_PRINT);
return; // Failed to init print page settings.
}
int expected_page_count = 0;
bool use_browser_overlays = true;
expected_page_count = prepare->GetExpectedPageCount();
if (expected_page_count)
use_browser_overlays = prepare->ShouldUseBrowserOverlays();
prepare.reset();
if (!expected_page_count) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!GetPrintSettingsFromUser(frame, expected_page_count,
use_browser_overlays)) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!RenderPagesForPrint(frame, node, NULL)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
ResetScriptedPrintCount();
}
| 170,263
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
}
Commit Message:
CWE ID: CWE-416
|
PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
| 164,971
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr,
const char *funcname, const int line, const char *file)
{
u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
if (pktdata) {
if (pkthdr->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, pkthdr->len, MAXPACKET);
exit(-1);
}
if (pkthdr->len < pkthdr->caplen) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, pkthdr->len, pkthdr->caplen);
exit(-1);
}
}
return pktdata;
}
Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length
Add check for packets that report zero packet length. Example
of fix:
src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null
Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets.
safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0
CWE ID: CWE-125
|
u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr,
const char *funcname, const int line, const char *file)
{
u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
if (pktdata) {
if (pkthdr->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, pkthdr->len, MAXPACKET);
exit(-1);
}
if (!pkthdr->len || pkthdr->len < pkthdr->caplen) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
file, funcname, line, pkthdr->len, pkthdr->caplen);
exit(-1);
}
}
return pktdata;
}
| 168,946
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InspectorNetworkAgent::WillSendRequest(
ExecutionContext* execution_context,
unsigned long identifier,
DocumentLoader* loader,
ResourceRequest& request,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo& initiator_info) {
if (initiator_info.name == FetchInitiatorTypeNames::internal)
return;
if (initiator_info.name == FetchInitiatorTypeNames::document &&
loader->GetSubstituteData().IsValid())
return;
protocol::DictionaryValue* headers =
state_->getObject(NetworkAgentState::kExtraRequestHeaders);
if (headers) {
for (size_t i = 0; i < headers->size(); ++i) {
auto header = headers->at(i);
String value;
if (header.second->asString(&value))
request.SetHTTPHeaderField(AtomicString(header.first),
AtomicString(value));
}
}
request.SetReportRawHeaders(true);
if (state_->booleanProperty(NetworkAgentState::kCacheDisabled, false)) {
if (LoadsFromCacheOnly(request) &&
request.GetRequestContext() != WebURLRequest::kRequestContextInternal) {
request.SetCachePolicy(WebCachePolicy::kBypassCacheLoadOnlyFromCache);
} else {
request.SetCachePolicy(WebCachePolicy::kBypassingCache);
}
request.SetShouldResetAppCache(true);
}
if (state_->booleanProperty(NetworkAgentState::kBypassServiceWorker, false))
request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone);
WillSendRequestInternal(execution_context, identifier, loader, request,
redirect_response, initiator_info);
if (!host_id_.IsEmpty()) {
request.AddHTTPHeaderField(
HTTPNames::X_DevTools_Emulate_Network_Conditions_Client_Id,
AtomicString(host_id_));
}
}
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 <pfeldman@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
|
void InspectorNetworkAgent::WillSendRequest(
ExecutionContext* execution_context,
unsigned long identifier,
DocumentLoader* loader,
ResourceRequest& request,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo& initiator_info,
Resource::Type resource_type) {
if (initiator_info.name == FetchInitiatorTypeNames::internal)
return;
if (initiator_info.name == FetchInitiatorTypeNames::document &&
loader->GetSubstituteData().IsValid())
return;
protocol::DictionaryValue* headers =
state_->getObject(NetworkAgentState::kExtraRequestHeaders);
if (headers) {
for (size_t i = 0; i < headers->size(); ++i) {
auto header = headers->at(i);
String value;
if (header.second->asString(&value))
request.SetHTTPHeaderField(AtomicString(header.first),
AtomicString(value));
}
}
request.SetReportRawHeaders(true);
if (state_->booleanProperty(NetworkAgentState::kCacheDisabled, false)) {
if (LoadsFromCacheOnly(request) &&
request.GetRequestContext() != WebURLRequest::kRequestContextInternal) {
request.SetCachePolicy(WebCachePolicy::kBypassCacheLoadOnlyFromCache);
} else {
request.SetCachePolicy(WebCachePolicy::kBypassingCache);
}
request.SetShouldResetAppCache(true);
}
if (state_->booleanProperty(NetworkAgentState::kBypassServiceWorker, false))
request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone);
InspectorPageAgent::ResourceType type =
InspectorPageAgent::ToResourceType(resource_type);
WillSendRequestInternal(execution_context, identifier, loader, request,
redirect_response, initiator_info, type);
if (!host_id_.IsEmpty()) {
request.AddHTTPHeaderField(
HTTPNames::X_DevTools_Emulate_Network_Conditions_Client_Id,
AtomicString(host_id_));
}
}
| 172,467
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
Commit Message: KEYS: close race between key lookup and freeing
When a key is being garbage collected, it's key->user would get put before
the ->destroy() callback is called, where the key is removed from it's
respective tracking structures.
This leaves a key hanging in a semi-invalid state which leaves a window open
for a different task to try an access key->user. An example is
find_keyring_by_name() which would dereference key->user for a key that is
in the process of being garbage collected (where key->user was freed but
->destroy() wasn't called yet - so it's still present in the linked list).
This would cause either a panic, or corrupt memory.
Fixes CVE-2014-9529.
Signed-off-by: Sasha Levin <sasha.levin@oracle.com>
Signed-off-by: David Howells <dhowells@redhat.com>
CWE ID: CWE-362
|
static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
| 166,783
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ProcessStateChangesUnifiedPlan(
WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan);
handler_->OnModifyTransceivers(
std::move(states.transceiver_states),
action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION);
}
Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl
Bug: 912074
Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8
Reviewed-on: https://chromium-review.googlesource.com/c/1411916
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#622945}
CWE ID: CWE-416
|
void ProcessStateChangesUnifiedPlan(
WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan);
if (handler_) {
handler_->OnModifyTransceivers(
std::move(states.transceiver_states),
action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION);
}
}
| 173,075
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RenderWidgetHostViewAura::WasShown() {
if (!host_->is_hidden())
return;
host_->WasShown();
if (!current_surface_ && host_->is_accelerated_compositing_active() &&
!released_front_lock_.get()) {
released_front_lock_ = GetCompositor()->GetCompositorLock();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
#endif
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewAura::WasShown() {
if (!host_->is_hidden())
return;
host_->WasShown();
if (!current_surface_ && host_->is_accelerated_compositing_active() &&
!released_front_lock_.get()) {
released_front_lock_ = GetCompositor()->GetCompositorLock();
}
#if defined(OS_WIN)
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
#endif
}
| 171,389
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage(
sk_sp<SkImage> image) {
CHECK(image);
DCHECK(!image->isLazyGenerated());
paint_image_ =
CreatePaintImageBuilder()
.set_image(std::move(image), cc::PaintImage::GetNextContentId())
.TakePaintImage();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage(
sk_sp<SkImage> image) {
CHECK(image);
DCHECK(!image->isLazyGenerated());
paint_image_ =
CreatePaintImageBuilder()
.set_image(std::move(image), cc::PaintImage::GetNextContentId())
.TakePaintImage();
}
| 172,602
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
gfx::SizeF contents_size_dip,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_updateScrollState(env,
obj.obj(),
max_scroll_offset.x(),
max_scroll_offset.y(),
contents_size_dip.width(),
contents_size_dip.height(),
page_scale_factor,
min_page_scale_factor,
max_page_scale_factor);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
void AwContents::UpdateScrollState(const gfx::Vector2d& max_scroll_offset,
const gfx::SizeF& contents_size_dip,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_updateScrollState(env,
obj.obj(),
max_scroll_offset.x(),
max_scroll_offset.y(),
contents_size_dip.width(),
contents_size_dip.height(),
page_scale_factor,
min_page_scale_factor,
max_page_scale_factor);
}
| 171,618
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
const KURL& current_src) {
DCHECK(IsMainThread());
return Context()->GetSecurityOrigin() &&
Context()->GetSecurityOrigin()->CanRequest(current_src);
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Reviewed-by: Yutaka Hirano <yhirano@chromium.org>
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20
|
bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
// Test to see if the current media URL taint the origin of the audio context?
return Context()->WouldTaintOrigin(MediaElement()->currentSrc());
}
| 173,148
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {
bloc = *offset;
send(huff->loc[ch], NULL, fout);
*offset = bloc;
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
CWE ID: CWE-119
|
void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {
void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset, int maxoffset) {
bloc = *offset;
send(huff->loc[ch], NULL, fout, maxoffset);
*offset = bloc;
}
| 167,995
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type)
{
if (!exp->ex_layout_types) {
dprintk("%s: export does not support pNFS\n", __func__);
return NULL;
}
if (!(exp->ex_layout_types & (1 << layout_type))) {
dprintk("%s: layout type %d not supported\n",
__func__, layout_type);
return NULL;
}
return nfsd4_layout_ops[layout_type];
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type)
{
if (!exp->ex_layout_types) {
dprintk("%s: export does not support pNFS\n", __func__);
return NULL;
}
if (layout_type >= LAYOUT_TYPE_MAX ||
!(exp->ex_layout_types & (1 << layout_type))) {
dprintk("%s: layout type %d not supported\n",
__func__, layout_type);
return NULL;
}
return nfsd4_layout_ops[layout_type];
}
| 168,144
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps,
struct sock *sk, int tstype)
{
struct sk_buff *skb;
bool tsonly;
if (!sk)
return;
tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
if (!skb_may_tx_timestamp(sk, tsonly))
return;
if (tsonly) {
#ifdef CONFIG_INET
if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
skb = tcp_get_timestamping_opt_stats(sk);
else
#endif
skb = alloc_skb(0, GFP_ATOMIC);
} else {
skb = skb_clone(orig_skb, GFP_ATOMIC);
}
if (!skb)
return;
if (tsonly) {
skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags;
skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
}
if (hwtstamps)
*skb_hwtstamps(skb) = *hwtstamps;
else
skb->tstamp = ktime_get_real();
__skb_complete_tx_timestamp(skb, sk, tstype);
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <zzoru007@gmail.com>
Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Signed-off-by: Willem de Bruijn <willemb@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-125
|
void __skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps,
struct sock *sk, int tstype)
{
struct sk_buff *skb;
bool tsonly, opt_stats = false;
if (!sk)
return;
tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
if (!skb_may_tx_timestamp(sk, tsonly))
return;
if (tsonly) {
#ifdef CONFIG_INET
if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM) {
skb = tcp_get_timestamping_opt_stats(sk);
opt_stats = true;
} else
#endif
skb = alloc_skb(0, GFP_ATOMIC);
} else {
skb = skb_clone(orig_skb, GFP_ATOMIC);
}
if (!skb)
return;
if (tsonly) {
skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags;
skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
}
if (hwtstamps)
*skb_hwtstamps(skb) = *hwtstamps;
else
skb->tstamp = ktime_get_real();
__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
}
| 170,072
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Extension* ExtensionAppItem::GetExtension() const {
const ExtensionService* service =
extensions::ExtensionSystem::Get(profile_)->extension_service();
const Extension* extension = service->GetInstalledExtension(extension_id_);
return extension;
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID:
|
const Extension* ExtensionAppItem::GetExtension() const {
const extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile_);
const Extension* extension = registry->GetInstalledExtension(
extension_id_);
return extension;
}
| 171,723
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id,
chromeos::BluetoothDevice* device) {
VLOG(2) << "Device found on " << adapter_id;
DCHECK(device);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.addBluetoothDevice", device->AsDictionary());
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id,
chromeos::BluetoothDevice* device) {
VLOG(2) << "Device found on " << adapter_id;
DCHECK(device);
SendDeviceNotification(device, NULL);
}
| 170,965
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) {
HANDLE pump_messages_event_for_renderer = NULL;
DuplicateHandle(GetCurrentProcess(), pump_messages_event,
channel_->renderer_handle(),
&pump_messages_event_for_renderer,
0, FALSE, DUPLICATE_SAME_ACCESS);
DCHECK(pump_messages_event_for_renderer != NULL);
Send(new PluginHostMsg_SetWindowlessPumpEvent(
route_id_, pump_messages_event_for_renderer));
}
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 WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) {
HANDLE pump_messages_event_for_renderer = NULL;
sandbox::BrokerDuplicateHandle(pump_messages_event, channel_->peer_pid(),
&pump_messages_event_for_renderer,
SYNCHRONIZE | EVENT_MODIFY_STATE, 0);
DCHECK(pump_messages_event_for_renderer != NULL);
Send(new PluginHostMsg_SetWindowlessPumpEvent(
route_id_, pump_messages_event_for_renderer));
}
| 170,953
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host,
bool is_guest_view_hack)
: host_(RenderWidgetHostImpl::From(host)),
window_(nullptr),
in_shutdown_(false),
in_bounds_changed_(false),
popup_parent_host_view_(nullptr),
popup_child_host_view_(nullptr),
is_loading_(false),
has_composition_text_(false),
background_color_(SK_ColorWHITE),
needs_begin_frames_(false),
needs_flush_input_(false),
added_frame_observer_(false),
cursor_visibility_state_in_renderer_(UNKNOWN),
#if defined(OS_WIN)
legacy_render_widget_host_HWND_(nullptr),
legacy_window_destroyed_(false),
virtual_keyboard_requested_(false),
#endif
has_snapped_to_boundary_(false),
is_guest_view_hack_(is_guest_view_hack),
device_scale_factor_(0.0f),
event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)),
weak_ptr_factory_(this) {
if (!is_guest_view_hack_)
host_->SetView(this);
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
SetOverscrollControllerEnabled(overscroll_enabled);
selection_controller_client_.reset(
new TouchSelectionControllerClientAura(this));
CreateSelectionController();
RenderViewHost* rvh = RenderViewHost::From(host_);
if (rvh) {
ignore_result(rvh->GetWebkitPreferences());
}
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
TBR=jam@chromium.org
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254
|
RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host,
bool is_guest_view_hack)
: host_(RenderWidgetHostImpl::From(host)),
window_(nullptr),
in_shutdown_(false),
in_bounds_changed_(false),
popup_parent_host_view_(nullptr),
popup_child_host_view_(nullptr),
is_loading_(false),
has_composition_text_(false),
background_color_(SK_ColorWHITE),
needs_begin_frames_(false),
needs_flush_input_(false),
added_frame_observer_(false),
cursor_visibility_state_in_renderer_(UNKNOWN),
#if defined(OS_WIN)
legacy_render_widget_host_HWND_(nullptr),
legacy_window_destroyed_(false),
virtual_keyboard_requested_(false),
#endif
has_snapped_to_boundary_(false),
is_guest_view_hack_(is_guest_view_hack),
device_scale_factor_(0.0f),
event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)),
frame_sink_id_(host_->AllocateFrameSinkId(is_guest_view_hack_)),
weak_ptr_factory_(this) {
if (!is_guest_view_hack_)
host_->SetView(this);
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
SetOverscrollControllerEnabled(overscroll_enabled);
selection_controller_client_.reset(
new TouchSelectionControllerClientAura(this));
CreateSelectionController();
RenderViewHost* rvh = RenderViewHost::From(host_);
if (rvh) {
ignore_result(rvh->GetWebkitPreferences());
}
}
| 172,235
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: user_change_icon_file_authorized_cb (Daemon *daemon,
User *user,
GDBusMethodInvocation *context,
gpointer data)
{
g_autofree gchar *filename = NULL;
g_autoptr(GFile) file = NULL;
g_autoptr(GFileInfo) info = NULL;
guint32 mode;
GFileType type;
guint64 size;
filename = g_strdup (data);
if (filename == NULL ||
*filename == '\0') {
g_autofree gchar *dest_path = NULL;
g_autoptr(GFile) dest = NULL;
g_autoptr(GError) error = NULL;
g_clear_pointer (&filename, g_free);
dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL);
dest = g_file_new_for_path (dest_path);
if (!g_file_delete (dest, NULL, &error) &&
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message);
return;
}
goto icon_saved;
}
file = g_file_new_for_path (filename);
info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
return;
}
Commit Message:
CWE ID: CWE-22
|
user_change_icon_file_authorized_cb (Daemon *daemon,
User *user,
GDBusMethodInvocation *context,
gpointer data)
{
g_autofree gchar *filename = NULL;
g_autoptr(GFile) file = NULL;
g_autoptr(GFileInfo) info = NULL;
guint32 mode;
GFileType type;
guint64 size;
filename = g_strdup (data);
if (filename == NULL ||
*filename == '\0') {
g_autofree gchar *dest_path = NULL;
g_autoptr(GFile) dest = NULL;
g_autoptr(GError) error = NULL;
g_clear_pointer (&filename, g_free);
dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL);
dest = g_file_new_for_path (dest_path);
if (!g_file_delete (dest, NULL, &error) &&
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message);
return;
}
goto icon_saved;
}
file = g_file_new_for_path (filename);
g_clear_pointer (&filename, g_free);
/* Canonicalize path so we can call g_str_has_prefix on it
* below without concern for ../ path components moving outside
* the prefix
*/
filename = g_file_get_path (file);
info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
return;
}
| 164,759
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BackendImpl::OnEntryDestroyEnd() {
DecreaseNumRefs();
if (data_->header.num_bytes > max_size_ && !read_only_ &&
(up_ticks_ > kTrimDelay || user_flags_ & kNoRandom))
eviction_.TrimCache(false);
}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <mmenke@chromium.org>
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
|
void BackendImpl::OnEntryDestroyEnd() {
DecreaseNumRefs();
consider_evicting_at_op_end_ = true;
}
void BackendImpl::OnSyncBackendOpComplete() {
if (consider_evicting_at_op_end_) {
if (data_->header.num_bytes > max_size_ && !read_only_ &&
(up_ticks_ > kTrimDelay || user_flags_ & kNoRandom))
eviction_.TrimCache(false);
consider_evicting_at_op_end_ = false;
}
}
| 172,698
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void _modinit(module_t *m)
{
service_named_bind_command("chanserv", &cs_flags);
}
Commit Message: chanserv/flags: make Anope FLAGS compatibility an option
Previously, ChanServ FLAGS behavior could be modified by registering or
dropping the keyword nicks "LIST", "CLEAR", and "MODIFY".
Now, a configuration option is available that when turned on (default),
disables registration of these keyword nicks and enables this
compatibility feature. When turned off, registration of these keyword
nicks is possible, and compatibility to Anope's FLAGS command is
disabled.
Fixes atheme/atheme#397
CWE ID: CWE-284
|
void _modinit(module_t *m)
{
service_named_bind_command("chanserv", &cs_flags);
add_bool_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table, 0, &anope_flags_compat, true);
hook_add_event("nick_can_register");
hook_add_nick_can_register(check_registration_keywords);
hook_add_event("user_can_register");
hook_add_user_can_register(check_registration_keywords);
}
| 167,586
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) {
const DictionaryValue* dict = GetExtensionPref(extension_id);
std::string path;
if (!dict->GetString(kPrefPath, &path))
return FilePath();
return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path)));
}
Commit Message: Coverity: Add a missing NULL check.
BUG=none
TEST=none
CID=16813
Review URL: http://codereview.chromium.org/7216034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) {
const DictionaryValue* dict = GetExtensionPref(extension_id);
if (!dict)
return FilePath();
std::string path;
if (!dict->GetString(kPrefPath, &path))
return FilePath();
return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path)));
}
| 170,309
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftGSM::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nSamplingRate != 8000) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.gsm",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftGSM::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nSamplingRate != 8000) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.gsm",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,208
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cues::LoadCuePoint() const {
const long long stop = m_start + m_size;
if (m_pos >= stop)
return false; // nothing else to do
Init();
IMkvReader* const pReader = m_pSegment->m_pReader;
while (m_pos < stop) {
const long long idpos = m_pos;
long len;
const long long id = ReadUInt(pReader, m_pos, len);
assert(id >= 0); // TODO
assert((m_pos + len) <= stop);
m_pos += len; // consume ID
const long long size = ReadUInt(pReader, m_pos, len);
assert(size >= 0);
assert((m_pos + len) <= stop);
m_pos += len; // consume Size field
assert((m_pos + size) <= stop);
if (id != 0x3B) { // CuePoint ID
m_pos += size; // consume payload
assert(m_pos <= stop);
continue;
}
assert(m_preload_count > 0);
CuePoint* const pCP = m_cue_points[m_count];
assert(pCP);
assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos));
if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos))
return false;
pCP->Load(pReader);
++m_count;
--m_preload_count;
m_pos += size; // consume payload
assert(m_pos <= stop);
return true; // yes, we loaded a cue point
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
bool Cues::LoadCuePoint() const {
const long long stop = m_start + m_size;
if (m_pos >= stop)
return false; // nothing else to do
if (!Init()) {
m_pos = stop;
return false;
}
IMkvReader* const pReader = m_pSegment->m_pReader;
while (m_pos < stop) {
const long long idpos = m_pos;
long len;
const long long id = ReadID(pReader, m_pos, len);
if (id < 0 || (m_pos + len) > stop)
return false;
m_pos += len; // consume ID
const long long size = ReadUInt(pReader, m_pos, len);
if (size < 0 || (m_pos + len) > stop)
return false;
m_pos += len; // consume Size field
if ((m_pos + size) > stop)
return false;
if (id != 0x3B) { // CuePoint ID
m_pos += size; // consume payload
if (m_pos > stop)
return false;
continue;
}
if (m_preload_count < 1)
return false;
CuePoint* const pCP = m_cue_points[m_count];
if (!pCP || (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)))
return false;
if (!pCP->Load(pReader)) {
m_pos = stop;
return false;
}
++m_count;
--m_preload_count;
m_pos += size; // consume payload
if (m_pos > stop)
return false;
return true; // yes, we loaded a cue point
}
}
| 173,831
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext(
struct smb_iconv_handle *ic,
const char *str, size_t len,
charset_t src_charset,
size_t *bytes_consumed)
{
/* it cannot occupy more than 4 bytes in UTF16 format */
uint8_t buf[4];
smb_iconv_t descriptor;
size_t ilen_orig;
size_t ilen;
size_t olen;
char *outbuf;
if ((str[0] & 0x80) == 0) {
*bytes_consumed = 1;
return (codepoint_t)str[0];
}
* This is OK as we only support codepoints up to 1M (U+100000)
*/
ilen_orig = MIN(len, 5);
ilen = ilen_orig;
descriptor = get_conv_handle(ic, src_charset, CH_UTF16);
if (descriptor == (smb_iconv_t)-1) {
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
/*
* this looks a little strange, but it is needed to cope with
* codepoints above 64k (U+1000) which are encoded as per RFC2781.
*/
olen = 2;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 2) {
olen = 4;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 4) {
/* we didn't convert any bytes */
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
olen = 4 - olen;
} else {
olen = 2 - olen;
}
*bytes_consumed = ilen_orig - ilen;
if (olen == 2) {
return (codepoint_t)SVAL(buf, 0);
}
if (olen == 4) {
/* decode a 4 byte UTF16 character manually */
return (codepoint_t)0x10000 +
(buf[2] | ((buf[3] & 0x3)<<8) |
(buf[0]<<10) | ((buf[1] & 0x3)<<18));
}
/* no other length is valid */
return INVALID_CODEPOINT;
}
Commit Message:
CWE ID: CWE-200
|
_PUBLIC_ codepoint_t next_codepoint_handle_ext(
struct smb_iconv_handle *ic,
const char *str, size_t len,
charset_t src_charset,
size_t *bytes_consumed)
{
/* it cannot occupy more than 4 bytes in UTF16 format */
uint8_t buf[4];
smb_iconv_t descriptor;
size_t ilen_orig;
size_t ilen;
size_t olen;
char *outbuf;
if (((str[0] & 0x80) == 0) && (src_charset == CH_DOS ||
src_charset == CH_UNIX ||
src_charset == CH_UTF8)) {
*bytes_consumed = 1;
return (codepoint_t)str[0];
}
* This is OK as we only support codepoints up to 1M (U+100000)
*/
ilen_orig = MIN(len, 5);
ilen = ilen_orig;
descriptor = get_conv_handle(ic, src_charset, CH_UTF16);
if (descriptor == (smb_iconv_t)-1) {
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
/*
* this looks a little strange, but it is needed to cope with
* codepoints above 64k (U+1000) which are encoded as per RFC2781.
*/
olen = 2;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 2) {
olen = 4;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 4) {
/* we didn't convert any bytes */
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
olen = 4 - olen;
} else {
olen = 2 - olen;
}
*bytes_consumed = ilen_orig - ilen;
if (olen == 2) {
return (codepoint_t)SVAL(buf, 0);
}
if (olen == 4) {
/* decode a 4 byte UTF16 character manually */
return (codepoint_t)0x10000 +
(buf[2] | ((buf[3] & 0x3)<<8) |
(buf[0]<<10) | ((buf[1] & 0x3)<<18));
}
/* no other length is valid */
return INVALID_CODEPOINT;
}
| 164,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: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad,
OnDidStartProvisionalLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
OnDocumentOnLoadCompleted)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
OnJavaScriptExecuteResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse,
OnSerializeAsMHTMLResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture,
OnSetHasReceivedUserGesture)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed,
OnStreamHandleConsumed)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
|
bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad,
OnDidStartProvisionalLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
OnDocumentOnLoadCompleted)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
OnJavaScriptExecuteResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse,
OnSerializeAsMHTMLResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture,
OnSetHasReceivedUserGesture)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed,
OnStreamHandleConsumed)
IPC_END_MESSAGE_MAP()
return handled;
}
| 172,717
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftG711::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
return OMX_ErrorUndefined;
}
if(pcmParams->nPortIndex == 0) {
mNumChannels = pcmParams->nChannels;
}
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (mIsMLaw) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711mlaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711alaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftG711::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
return OMX_ErrorUndefined;
}
if(pcmParams->nPortIndex == 0) {
mNumChannels = pcmParams->nChannels;
}
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (mIsMLaw) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711mlaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711alaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,206
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SampleIterator::seekTo(uint32_t sampleIndex) {
ALOGV("seekTo(%d)", sampleIndex);
if (sampleIndex >= mTable->mNumSampleSizes) {
return ERROR_END_OF_STREAM;
}
if (mTable->mSampleToChunkOffset < 0
|| mTable->mChunkOffsetOffset < 0
|| mTable->mSampleSizeOffset < 0
|| mTable->mTimeToSampleCount == 0) {
return ERROR_MALFORMED;
}
if (mInitialized && mCurrentSampleIndex == sampleIndex) {
return OK;
}
if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) {
reset();
}
if (sampleIndex >= mStopChunkSampleIndex) {
status_t err;
if ((err = findChunkRange(sampleIndex)) != OK) {
ALOGE("findChunkRange failed");
return err;
}
}
CHECK(sampleIndex < mStopChunkSampleIndex);
if (mSamplesPerChunk == 0) {
ALOGE("b/22802344");
return ERROR_MALFORMED;
}
uint32_t chunk =
(sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk
+ mFirstChunk;
if (!mInitialized || chunk != mCurrentChunkIndex) {
mCurrentChunkIndex = chunk;
status_t err;
if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) {
ALOGE("getChunkOffset return error");
return err;
}
mCurrentChunkSampleSizes.clear();
uint32_t firstChunkSampleIndex =
mFirstChunkSampleIndex
+ mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk);
for (uint32_t i = 0; i < mSamplesPerChunk; ++i) {
size_t sampleSize;
if ((err = getSampleSizeDirect(
firstChunkSampleIndex + i, &sampleSize)) != OK) {
ALOGE("getSampleSizeDirect return error");
return err;
}
mCurrentChunkSampleSizes.push(sampleSize);
}
}
uint32_t chunkRelativeSampleIndex =
(sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk;
mCurrentSampleOffset = mCurrentChunkOffset;
for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) {
mCurrentSampleOffset += mCurrentChunkSampleSizes[i];
}
mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex];
if (sampleIndex < mTTSSampleIndex) {
mTimeToSampleIndex = 0;
mTTSSampleIndex = 0;
mTTSSampleTime = 0;
mTTSCount = 0;
mTTSDuration = 0;
}
status_t err;
if ((err = findSampleTimeAndDuration(
sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) {
ALOGE("findSampleTime return error");
return err;
}
mCurrentSampleIndex = sampleIndex;
mInitialized = true;
return OK;
}
Commit Message: SampleIterator: clear members on seekTo error
Bug: 31091777
Change-Id: Iddf99d0011961d0fd3d755e57db4365b6a6a1193
(cherry picked from commit 03237ce0f9584c98ccda76c2474a4ae84c763f5b)
CWE ID: CWE-200
|
status_t SampleIterator::seekTo(uint32_t sampleIndex) {
ALOGV("seekTo(%d)", sampleIndex);
if (sampleIndex >= mTable->mNumSampleSizes) {
return ERROR_END_OF_STREAM;
}
if (mTable->mSampleToChunkOffset < 0
|| mTable->mChunkOffsetOffset < 0
|| mTable->mSampleSizeOffset < 0
|| mTable->mTimeToSampleCount == 0) {
return ERROR_MALFORMED;
}
if (mInitialized && mCurrentSampleIndex == sampleIndex) {
return OK;
}
if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) {
reset();
}
if (sampleIndex >= mStopChunkSampleIndex) {
status_t err;
if ((err = findChunkRange(sampleIndex)) != OK) {
ALOGE("findChunkRange failed");
return err;
}
}
CHECK(sampleIndex < mStopChunkSampleIndex);
if (mSamplesPerChunk == 0) {
ALOGE("b/22802344");
return ERROR_MALFORMED;
}
uint32_t chunk =
(sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk
+ mFirstChunk;
if (!mInitialized || chunk != mCurrentChunkIndex) {
status_t err;
if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) {
ALOGE("getChunkOffset return error");
return err;
}
mCurrentChunkSampleSizes.clear();
uint32_t firstChunkSampleIndex =
mFirstChunkSampleIndex
+ mSamplesPerChunk * (chunk - mFirstChunk);
for (uint32_t i = 0; i < mSamplesPerChunk; ++i) {
size_t sampleSize;
if ((err = getSampleSizeDirect(
firstChunkSampleIndex + i, &sampleSize)) != OK) {
ALOGE("getSampleSizeDirect return error");
mCurrentChunkSampleSizes.clear();
return err;
}
mCurrentChunkSampleSizes.push(sampleSize);
}
mCurrentChunkIndex = chunk;
}
uint32_t chunkRelativeSampleIndex =
(sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk;
mCurrentSampleOffset = mCurrentChunkOffset;
for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) {
mCurrentSampleOffset += mCurrentChunkSampleSizes[i];
}
mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex];
if (sampleIndex < mTTSSampleIndex) {
mTimeToSampleIndex = 0;
mTTSSampleIndex = 0;
mTTSSampleTime = 0;
mTTSCount = 0;
mTTSDuration = 0;
}
status_t err;
if ((err = findSampleTimeAndDuration(
sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) {
ALOGE("findSampleTime return error");
return err;
}
mCurrentSampleIndex = sampleIndex;
mInitialized = true;
return OK;
}
| 173,378
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SocketStreamDispatcherHost::OnSSLCertificateError(
net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) {
int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket);
DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id="
<< socket_id;
if (socket_id == content::kNoSocketId) {
LOG(ERROR) << "NoSocketId in OnSSLCertificateError";
return;
}
SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id);
DCHECK(socket_stream_host);
content::GlobalRequestID request_id(-1, socket_id);
SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(),
request_id, ResourceType::SUB_RESOURCE, socket->url(),
render_process_id_, socket_stream_host->render_view_id(), ssl_info,
fatal);
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void SocketStreamDispatcherHost::OnSSLCertificateError(
net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) {
int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket);
DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id="
<< socket_id;
if (socket_id == content::kNoSocketId) {
LOG(ERROR) << "NoSocketId in OnSSLCertificateError";
return;
}
SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id);
DCHECK(socket_stream_host);
content::GlobalRequestID request_id(-1, socket_id);
SSLManager::OnSSLCertificateError(
AsWeakPtr(), request_id, ResourceType::SUB_RESOURCE, socket->url(),
render_process_id_, socket_stream_host->render_view_id(), ssl_info,
fatal);
}
| 170,992
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long long Segment::CreateInstance(IMkvReader* pReader, long long pos,
Segment*& pSegment) {
assert(pReader);
assert(pos >= 0);
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) // error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
for (;;) {
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return id;
pos += len; // consume ID
result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) { // Segment ID
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(pReader, idpos,
pos, size);
if (pSegment == 0)
return -1; // generic error
return 0; // success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; // consume payload
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long long Segment::CreateInstance(IMkvReader* pReader, long long pos,
Segment*& pSegment) {
if (pReader == NULL || pos < 0)
return E_PARSE_FAILED;
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) // error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
for (;;) {
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) { // Segment ID
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(pReader, idpos,
pos, size);
if (pSegment == 0)
return -1; // generic error
return 0; // success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; // consume payload
}
}
| 173,807
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileInfo, getRealPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char buff[MAXPATHLEN];
char *filename;
zend_error_handling error_handling;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
}
if (intern->orig_path) {
filename = intern->orig_path;
} else {
filename = intern->file_name;
}
if (filename && VCWD_REALPATH(filename, buff)) {
#ifdef ZTS
if (VCWD_ACCESS(buff, F_OK)) {
RETVAL_FALSE;
} else
#endif
RETVAL_STRING(buff, 1);
} else {
RETVAL_FALSE;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileInfo, getRealPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char buff[MAXPATHLEN];
char *filename;
zend_error_handling error_handling;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
}
if (intern->orig_path) {
filename = intern->orig_path;
} else {
filename = intern->file_name;
}
if (filename && VCWD_REALPATH(filename, buff)) {
#ifdef ZTS
if (VCWD_ACCESS(buff, F_OK)) {
RETVAL_FALSE;
} else
#endif
RETVAL_STRING(buff, 1);
} else {
RETVAL_FALSE;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,039
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void MaybeStopInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value) &&
enable_auto_ime_shutdown_) {
StopInputMethodDaemon();
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void MaybeStopInputMethodDaemon(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value) &&
enable_auto_ime_shutdown_) {
StopInputMethodDaemon();
}
}
| 170,500
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __btrfs_set_acl(struct btrfs_trans_handle *trans,
struct inode *inode, struct posix_acl *acl, int type)
{
int ret, size = 0;
const char *name;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_equiv_mode(acl, &inode->i_mode);
if (ret < 0)
return ret;
if (ret == 0)
acl = NULL;
}
ret = 0;
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode))
return acl ? -EINVAL : 0;
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out;
}
ret = __btrfs_setxattr(trans, inode, name, value, size, 0);
out:
kfree(value);
if (!ret)
set_cached_acl(inode, type, acl);
return ret;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>
CWE ID: CWE-285
|
static int __btrfs_set_acl(struct btrfs_trans_handle *trans,
struct inode *inode, struct posix_acl *acl, int type)
{
int ret, size = 0;
const char *name;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (ret)
return ret;
}
ret = 0;
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode))
return acl ? -EINVAL : 0;
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out;
}
ret = __btrfs_setxattr(trans, inode, name, value, size, 0);
out:
kfree(value);
if (!ret)
set_cached_acl(inode, type, acl);
return ret;
}
| 166,967
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), nullptr, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Block dotless-i / j + a combining mark
U+0131 (doltess i) and U+0237 (dotless j) are blocked from being
followed by a combining mark in U+0300 block.
Bug: 774842
Test: See the bug
Change-Id: I92aac0e97233184864d060fd0f137a90b042c679
Reviewed-on: https://chromium-review.googlesource.com/767888
Commit-Queue: Jungshik Shin <jshin@chromium.org>
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Cr-Commit-Position: refs/heads/master@{#517605}
CWE ID: CWE-20
|
bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), nullptr, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
// - Disallow dotless i (U+0131) followed by a combining mark.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"(\u0131[\u0300-\u0339]|)"
R"([ijl]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,692
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
Commit Message: Fixed a sanitizer failure in the BMP codec.
Also, added a --debug-level command line option to the imginfo command
for debugging purposes.
CWE ID: CWE-476
|
jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
JAS_DBGLOG(1,
("BMP information: len %d; width %d; height %d; numplanes %d; "
"depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; "
"mincolors %d\n", info->len, info->width, info->height, info->numplanes,
info->depth, info->enctype, info->siz, info->hres, info->vres,
info->numcolors, info->mincolors));
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
| 168,762
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *ReadWBMPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
byte;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
bit;
unsigned short
header;
/*
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);
}
if (ReadBlob(image,2,(unsigned char *) &header) == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header != 0)
ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported");
/*
Initialize image structure.
*/
if (WBMPReadInteger(image,&image->columns) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if (WBMPReadInteger(image,&image->rows) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
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.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 1 : 0);
bit++;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
|
static Image *ReadWBMPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
byte;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
bit;
unsigned short
header;
/*
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);
}
if (ReadBlob(image,2,(unsigned char *) &header) == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header != 0)
ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported");
/*
Initialize image structure.
*/
if (WBMPReadInteger(image,&image->columns) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if (WBMPReadInteger(image,&image->rows) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
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.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 1 : 0);
bit++;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,619
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: pgp_enumerate_blob(sc_card_t *card, pgp_blob_t *blob)
{
const u8 *in;
int r;
if (blob->files != NULL)
return SC_SUCCESS;
if ((r = pgp_read_blob(card, blob)) < 0)
return r;
in = blob->data;
while ((int) blob->len > (in - blob->data)) {
unsigned int cla, tag, tmptag;
size_t len;
const u8 *data = in;
pgp_blob_t *new;
r = sc_asn1_read_tag(&data, blob->len - (in - blob->data),
&cla, &tag, &len);
if (r < 0 || data == NULL) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unexpected end of contents\n");
return SC_ERROR_OBJECT_NOT_VALID;
}
/* undo ASN1's split of tag & class */
for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
cla <<= 8;
}
tag |= cla;
/* Awful hack for composite DOs that have
* a TLV with the DO's id encompassing the
* entire blob. Example: Yubikey Neo */
if (tag == blob->id) {
in = data;
continue;
}
/* create fake file system hierarchy by
* using constructed DOs as DF */
if ((new = pgp_new_blob(card, blob, tag, sc_file_new())) == NULL)
return SC_ERROR_OUT_OF_MEMORY;
pgp_set_blob(new, data, len);
in = data + len;
}
return SC_SUCCESS;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
pgp_enumerate_blob(sc_card_t *card, pgp_blob_t *blob)
{
const u8 *in;
int r;
if (blob->files != NULL)
return SC_SUCCESS;
if ((r = pgp_read_blob(card, blob)) < 0)
return r;
in = blob->data;
while ((int) blob->len > (in - blob->data)) {
unsigned int cla, tag, tmptag;
size_t len;
const u8 *data = in;
pgp_blob_t *new;
if (!in)
return SC_ERROR_OBJECT_NOT_VALID;
r = sc_asn1_read_tag(&data, blob->len - (in - blob->data),
&cla, &tag, &len);
if (r < 0 || data == NULL) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unexpected end of contents\n");
return SC_ERROR_OBJECT_NOT_VALID;
}
if (data + len > blob->data + blob->len)
return SC_ERROR_OBJECT_NOT_VALID;
/* undo ASN1's split of tag & class */
for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
cla <<= 8;
}
tag |= cla;
/* Awful hack for composite DOs that have
* a TLV with the DO's id encompassing the
* entire blob. Example: Yubikey Neo */
if (tag == blob->id) {
in = data;
continue;
}
/* create fake file system hierarchy by
* using constructed DOs as DF */
if ((new = pgp_new_blob(card, blob, tag, sc_file_new())) == NULL)
return SC_ERROR_OUT_OF_MEMORY;
pgp_set_blob(new, data, len);
in = data + len;
}
return SC_SUCCESS;
}
| 169,060
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MessageService::OpenChannelToTab(
int source_process_id, int source_routing_id, int receiver_port_id,
int tab_id, const std::string& extension_id,
const std::string& channel_name) {
content::RenderProcessHost* source =
content::RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
WebContents* contents = NULL;
scoped_ptr<MessagePort> receiver;
if (ExtensionTabUtil::GetTabById(tab_id, profile, true,
NULL, NULL, &contents, NULL)) {
receiver.reset(new ExtensionMessagePort(
contents->GetRenderProcessHost(),
contents->GetRenderViewHost()->GetRoutingID(),
extension_id));
}
if (contents && contents->GetController().NeedsReload()) {
ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id);
port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true);
return;
}
WebContents* source_contents = tab_util::GetWebContentsByID(
source_process_id, source_routing_id);
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue(
source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS));
base::JSONWriter::Write(tab_value.get(), &tab_json);
}
scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json,
receiver.release(),
receiver_port_id,
extension_id,
extension_id,
channel_name));
OpenChannelImpl(params.Pass());
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
void MessageService::OpenChannelToTab(
int source_process_id, int source_routing_id, int receiver_port_id,
int tab_id, const std::string& extension_id,
const std::string& channel_name) {
content::RenderProcessHost* source =
content::RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
WebContents* contents = NULL;
scoped_ptr<MessagePort> receiver;
if (ExtensionTabUtil::GetTabById(tab_id, profile, true,
NULL, NULL, &contents, NULL)) {
receiver.reset(new ExtensionMessagePort(
contents->GetRenderProcessHost(),
contents->GetRenderViewHost()->GetRoutingID(),
extension_id));
}
if (contents && contents->GetController().NeedsReload()) {
ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id);
port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true);
return;
}
WebContents* source_contents = tab_util::GetWebContentsByID(
source_process_id, source_routing_id);
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue(
source_contents));
base::JSONWriter::Write(tab_value.get(), &tab_json);
}
scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json,
receiver.release(),
receiver_port_id,
extension_id,
extension_id,
channel_name));
OpenChannelImpl(params.Pass());
}
| 171,448
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: send_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IESENDPARAMS;
r = -1;
} else {
if (test->protocol->id == Ptcp)
cJSON_AddTrueToObject(j, "tcp");
else if (test->protocol->id == Pudp)
cJSON_AddTrueToObject(j, "udp");
cJSON_AddIntToObject(j, "omit", test->omit);
if (test->server_affinity != -1)
cJSON_AddIntToObject(j, "server_affinity", test->server_affinity);
if (test->duration)
cJSON_AddIntToObject(j, "time", test->duration);
if (test->settings->bytes)
cJSON_AddIntToObject(j, "num", test->settings->bytes);
if (test->settings->blocks)
cJSON_AddIntToObject(j, "blockcount", test->settings->blocks);
if (test->settings->mss)
cJSON_AddIntToObject(j, "MSS", test->settings->mss);
if (test->no_delay)
cJSON_AddTrueToObject(j, "nodelay");
cJSON_AddIntToObject(j, "parallel", test->num_streams);
if (test->reverse)
cJSON_AddTrueToObject(j, "reverse");
if (test->settings->socket_bufsize)
cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize);
if (test->settings->blksize)
cJSON_AddIntToObject(j, "len", test->settings->blksize);
if (test->settings->rate)
cJSON_AddIntToObject(j, "bandwidth", test->settings->rate);
if (test->settings->burst)
cJSON_AddIntToObject(j, "burst", test->settings->burst);
if (test->settings->tos)
cJSON_AddIntToObject(j, "TOS", test->settings->tos);
if (test->settings->flowlabel)
cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel);
if (test->title)
cJSON_AddStringToObject(j, "title", test->title);
if (test->congestion)
cJSON_AddStringToObject(j, "congestion", test->congestion);
if (test->get_server_output)
cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
if (test->debug) {
printf("send_parameters:\n%s\n", cJSON_Print(j));
}
if (JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDPARAMS;
r = -1;
}
cJSON_Delete(j);
}
return r;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
send_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IESENDPARAMS;
r = -1;
} else {
if (test->protocol->id == Ptcp)
cJSON_AddTrueToObject(j, "tcp");
else if (test->protocol->id == Pudp)
cJSON_AddTrueToObject(j, "udp");
cJSON_AddNumberToObject(j, "omit", test->omit);
if (test->server_affinity != -1)
cJSON_AddNumberToObject(j, "server_affinity", test->server_affinity);
if (test->duration)
cJSON_AddNumberToObject(j, "time", test->duration);
if (test->settings->bytes)
cJSON_AddNumberToObject(j, "num", test->settings->bytes);
if (test->settings->blocks)
cJSON_AddNumberToObject(j, "blockcount", test->settings->blocks);
if (test->settings->mss)
cJSON_AddNumberToObject(j, "MSS", test->settings->mss);
if (test->no_delay)
cJSON_AddTrueToObject(j, "nodelay");
cJSON_AddNumberToObject(j, "parallel", test->num_streams);
if (test->reverse)
cJSON_AddTrueToObject(j, "reverse");
if (test->settings->socket_bufsize)
cJSON_AddNumberToObject(j, "window", test->settings->socket_bufsize);
if (test->settings->blksize)
cJSON_AddNumberToObject(j, "len", test->settings->blksize);
if (test->settings->rate)
cJSON_AddNumberToObject(j, "bandwidth", test->settings->rate);
if (test->settings->burst)
cJSON_AddNumberToObject(j, "burst", test->settings->burst);
if (test->settings->tos)
cJSON_AddNumberToObject(j, "TOS", test->settings->tos);
if (test->settings->flowlabel)
cJSON_AddNumberToObject(j, "flowlabel", test->settings->flowlabel);
if (test->title)
cJSON_AddStringToObject(j, "title", test->title);
if (test->congestion)
cJSON_AddStringToObject(j, "congestion", test->congestion);
if (test->get_server_output)
<<<<<<< HEAD
cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
=======
cJSON_AddNumberToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
if (test->udp_counters_64bit)
cJSON_AddNumberToObject(j, "udp_counters_64bit", iperf_get_test_udp_counters_64bit(test));
if (test->no_fq_socket_pacing)
cJSON_AddNumberToObject(j, "no_fq_socket_pacing", iperf_get_no_fq_socket_pacing(test));
cJSON_AddStringToObject(j, "client_version", IPERF_VERSION);
>>>>>>> ed94082... Fix a buffer overflow / heap corruption issue that could occur if a
if (test->debug) {
printf("send_parameters:\n%s\n", cJSON_Print(j));
}
if (JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDPARAMS;
r = -1;
}
cJSON_Delete(j);
}
return r;
}
| 167,316
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileObject, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
/* Do not read the next line to support correct counting with fgetc()
if (!intern->current_line) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
} */
RETURN_LONG(intern->u.file.current_line_num);
} /* }}} */
/* {{{ proto void SplFileObject::next()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
/* Do not read the next line to support correct counting with fgetc()
if (!intern->current_line) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
} */
RETURN_LONG(intern->u.file.current_line_num);
} /* }}} */
/* {{{ proto void SplFileObject::next()
| 167,056
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LauncherView::ShowOverflowMenu() {
#if !defined(OS_MACOSX)
if (!delegate_)
return;
std::vector<LauncherItem> items;
GetOverflowItems(&items);
if (items.empty())
return;
MenuDelegateImpl menu_delegate;
ui::SimpleMenuModel menu_model(&menu_delegate);
for (size_t i = 0; i < items.size(); ++i)
menu_model.AddItem(static_cast<int>(i), delegate_->GetTitle(items[i]));
views::MenuModelAdapter menu_adapter(&menu_model);
overflow_menu_runner_.reset(new views::MenuRunner(menu_adapter.CreateMenu()));
gfx::Rect bounds(overflow_button_->size());
gfx::Point origin;
ConvertPointToScreen(overflow_button_, &origin);
if (overflow_menu_runner_->RunMenuAt(GetWidget(), NULL,
gfx::Rect(origin, size()), views::MenuItemView::TOPLEFT, 0) ==
views::MenuRunner::MENU_DELETED)
return;
Shell::GetInstance()->UpdateShelfVisibility();
if (menu_delegate.activated_command_id() == -1)
return;
LauncherID activated_id = items[menu_delegate.activated_command_id()].id;
LauncherItems::const_iterator window_iter = model_->ItemByID(activated_id);
if (window_iter == model_->items().end())
return; // Window was deleted while menu was up.
delegate_->ItemClicked(*window_iter, ui::EF_NONE);
#endif // !defined(OS_MACOSX)
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void LauncherView::ShowOverflowMenu() {
void LauncherView::ShowOverflowBubble() {
int first_overflow_index = last_visible_index_ + 1;
DCHECK_LT(first_overflow_index, view_model_->view_size() - 1);
if (!overflow_bubble_.get())
overflow_bubble_.reset(new OverflowBubble());
overflow_bubble_->Show(delegate_,
model_,
overflow_button_,
alignment_,
first_overflow_index);
Shell::GetInstance()->UpdateShelfVisibility();
}
| 170,896
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fetch_uidl(char *line, void *data)
{
int i, index;
struct Context *ctx = (struct Context *) data;
struct PopData *pop_data = (struct PopData *) ctx->data;
char *endp = NULL;
errno = 0;
index = strtol(line, &endp, 10);
if (errno)
return -1;
while (*endp == ' ')
endp++;
memmove(line, endp, strlen(endp) + 1);
for (i = 0; i < ctx->msgcount; i++)
if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0)
break;
if (i == ctx->msgcount)
{
mutt_debug(1, "new header %d %s\n", index, line);
if (i >= ctx->hdrmax)
mx_alloc_memory(ctx);
ctx->msgcount++;
ctx->hdrs[i] = mutt_header_new();
ctx->hdrs[i]->data = mutt_str_strdup(line);
}
else if (ctx->hdrs[i]->index != index - 1)
pop_data->clear_cache = true;
ctx->hdrs[i]->refno = index;
ctx->hdrs[i]->index = index - 1;
return 0;
}
Commit Message: Ensure UID in fetch_uidl
CWE ID: CWE-824
|
static int fetch_uidl(char *line, void *data)
{
int i, index;
struct Context *ctx = (struct Context *) data;
struct PopData *pop_data = (struct PopData *) ctx->data;
char *endp = NULL;
errno = 0;
index = strtol(line, &endp, 10);
if (errno)
return -1;
while (*endp == ' ')
endp++;
memmove(line, endp, strlen(endp) + 1);
/* uid must be at least be 1 byte */
if (strlen(line) == 0)
return -1;
for (i = 0; i < ctx->msgcount; i++)
if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0)
break;
if (i == ctx->msgcount)
{
mutt_debug(1, "new header %d %s\n", index, line);
if (i >= ctx->hdrmax)
mx_alloc_memory(ctx);
ctx->msgcount++;
ctx->hdrs[i] = mutt_header_new();
ctx->hdrs[i]->data = mutt_str_strdup(line);
}
else if (ctx->hdrs[i]->index != index - 1)
pop_data->clear_cache = true;
ctx->hdrs[i]->refno = index;
ctx->hdrs[i]->index = index - 1;
return 0;
}
| 169,136
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PepperDeviceEnumerationHostHelperTest()
: ppapi_host_(&sink_, ppapi::PpapiPermissions()),
resource_host_(&ppapi_host_, 12345, 67890),
device_enumeration_(&resource_host_,
&delegate_,
PP_DEVICETYPE_DEV_AUDIOCAPTURE,
GURL("http://example.com")) {}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399
|
PepperDeviceEnumerationHostHelperTest()
: ppapi_host_(&sink_, ppapi::PpapiPermissions()),
resource_host_(&ppapi_host_, 12345, 67890),
device_enumeration_(&resource_host_,
delegate_.AsWeakPtr(),
PP_DEVICETYPE_DEV_AUDIOCAPTURE,
GURL("http://example.com")) {}
| 171,607
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Edition::GetAtomCount() const
{
return m_atoms_count;
}
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
|
int Chapters::Edition::GetAtomCount() const
long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const {
return GetTime(pChapters, m_stop_timecode);
}
| 174,282
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
return updateGraphicBufferInMeta_l(portIndex, graphicBuffer, buffer, header);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
|
status_t OMXNodeInstance::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
return updateGraphicBufferInMeta_l(portIndex, graphicBuffer, buffer, header);
}
| 173,531
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long long Block::GetTime(const Cluster* pCluster) const
{
assert(pCluster);
const long long tc = GetTimeCode(pCluster);
const Segment* const pSegment = pCluster->m_pSegment;
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long ns = tc * scale;
return ns;
}
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 Block::GetTime(const Cluster* pCluster) const
const long long tc = GetTimeCode(pCluster);
const Segment* const pSegment = pCluster->m_pSegment;
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long ns = tc * scale;
return ns;
}
| 174,363
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CuePoint::Load(IMkvReader* pReader)
{
if (m_timecode >= 0) //already loaded
return;
assert(m_track_positions == NULL);
assert(m_track_positions_count == 0);
long long pos_ = -m_timecode;
const long long element_start = pos_;
long long stop;
{
long len;
const long long id = ReadUInt(pReader, pos_, len);
assert(id == 0x3B); //CuePoint ID
if (id != 0x3B)
return;
pos_ += len; //consume ID
const long long size = ReadUInt(pReader, pos_, len);
assert(size >= 0);
pos_ += len; //consume Size field
stop = pos_ + size;
}
const long long element_size = stop - element_start;
long long pos = pos_;
while (pos < stop)
{
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x33) //CueTime ID
m_timecode = UnserializeUInt(pReader, pos, size);
else if (id == 0x37) //CueTrackPosition(s) ID
++m_track_positions_count;
pos += size; //consume payload
assert(pos <= stop);
}
assert(m_timecode >= 0);
assert(m_track_positions_count > 0);
m_track_positions = new TrackPosition[m_track_positions_count];
TrackPosition* p = m_track_positions;
pos = pos_;
while (pos < stop)
{
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x37) //CueTrackPosition(s) ID
{
TrackPosition& tp = *p++;
tp.Parse(pReader, pos, size);
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(size_t(p - m_track_positions) == m_track_positions_count);
m_element_start = element_start;
m_element_size = element_size;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
void CuePoint::Load(IMkvReader* pReader)
assert(m_track_positions == NULL);
assert(m_track_positions_count == 0);
long long pos_ = -m_timecode;
const long long element_start = pos_;
long long stop;
{
long len;
const long long id = ReadUInt(pReader, pos_, len);
assert(id == 0x3B); // CuePoint ID
if (id != 0x3B)
return;
pos_ += len; // consume ID
const long long size = ReadUInt(pReader, pos_, len);
assert(size >= 0);
pos_ += len; // consume Size field
// pos_ now points to start of payload
stop = pos_ + size;
}
const long long element_size = stop - element_start;
long long pos = pos_;
// First count number of track positions
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x33) // CueTime ID
m_timecode = UnserializeUInt(pReader, pos, size);
else if (id == 0x37) // CueTrackPosition(s) ID
++m_track_positions_count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(m_timecode >= 0);
assert(m_track_positions_count > 0);
// os << "CuePoint::Load(cont'd): idpos=" << idpos
// << " timecode=" << m_timecode
// << endl;
m_track_positions = new TrackPosition[m_track_positions_count];
// Now parse track positions
TrackPosition* p = m_track_positions;
pos = pos_;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x37) { // CueTrackPosition(s) ID
TrackPosition& tp = *p++;
tp.Parse(pReader, pos, size);
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(size_t(p - m_track_positions) == m_track_positions_count);
m_element_start = element_start;
m_element_size = element_size;
}
| 174,395
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(imageaffinematrixget)
{
double affine[6];
long type;
zval *options;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
convert_to_double_ex(tmp);
x = Z_DVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
convert_to_double_ex(tmp);
y = Z_DVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
convert_to_double_ex(&options);
angle = Z_DVAL_P(options);
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
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(imageaffinematrixget)
{
double affine[6];
long type;
zval *options;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
x = Z_DVAL(dval);
} else {
x = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
y = Z_DVAL(dval);
} else {
y = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
convert_to_double_ex(&options);
angle = Z_DVAL_P(options);
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
| 166,429
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NuPlayer::GenericSource::setBuffers(
bool audio, Vector<MediaBuffer *> &buffers) {
if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) {
return mVideoTrack.mSource->setBuffers(buffers);
}
return INVALID_OPERATION;
}
Commit Message: Resolve a merge issue between lmp and lmp-mr1+
Change-Id: I336cb003fb7f50fd7d95c30ca47e45530a7ad503
(cherry picked from commit 33f6da1092834f1e4be199cfa3b6310d66b521c0)
(cherry picked from commit bb3a0338b58fafb01ac5b34efc450b80747e71e4)
CWE ID: CWE-119
|
status_t NuPlayer::GenericSource::setBuffers(
bool audio, Vector<MediaBuffer *> &buffers) {
if (mIsSecure && !audio && mVideoTrack.mSource != NULL) {
return mVideoTrack.mSource->setBuffers(buffers);
}
return INVALID_OPERATION;
}
| 174,166
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 clie_5_attach(struct usb_serial *serial)
{
struct usb_serial_port *port;
unsigned int pipe;
int j;
/* TH55 registers 2 ports.
Communication in from the UX50/TH55 uses bulk_in_endpointAddress
from port 0. Communication out to the UX50/TH55 uses
bulk_out_endpointAddress from port 1
Lets do a quick and dirty mapping
*/
/* some sanity check */
if (serial->num_ports < 2)
return -1;
/* port 0 now uses the modified endpoint Address */
port = serial->port[0];
port->bulk_out_endpointAddress =
serial->port[1]->bulk_out_endpointAddress;
pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress);
for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j)
port->write_urbs[j]->pipe = pipe;
return 0;
}
Commit Message: USB: serial: visor: fix crash on detecting device without write_urbs
The visor driver crashes in clie_5_attach() when a specially crafted USB
device without bulk-out endpoint is detected. This fix adds a check that
the device has proper configuration expected by the driver.
Reported-by: Ralf Spenneberg <ralf@spenneberg.net>
Signed-off-by: Vladis Dronov <vdronov@redhat.com>
Fixes: cfb8da8f69b8 ("USB: visor: fix initialisation of UX50/TH55 devices")
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Johan Hovold <johan@kernel.org>
CWE ID:
|
static int clie_5_attach(struct usb_serial *serial)
{
struct usb_serial_port *port;
unsigned int pipe;
int j;
/* TH55 registers 2 ports.
Communication in from the UX50/TH55 uses bulk_in_endpointAddress
from port 0. Communication out to the UX50/TH55 uses
bulk_out_endpointAddress from port 1
Lets do a quick and dirty mapping
*/
/* some sanity check */
if (serial->num_bulk_out < 2) {
dev_err(&serial->interface->dev, "missing bulk out endpoints\n");
return -ENODEV;
}
/* port 0 now uses the modified endpoint Address */
port = serial->port[0];
port->bulk_out_endpointAddress =
serial->port[1]->bulk_out_endpointAddress;
pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress);
for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j)
port->write_urbs[j]->pipe = pipe;
return 0;
}
| 167,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: xsltAttributeComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
xsltStyleItemAttributePtr comp;
#else
xsltStylePreCompPtr comp;
#endif
/*
* <xsl:attribute
* name = { qname }
* namespace = { uri-reference }>
* <!-- Content: template -->
* </xsl:attribute>
*/
if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
return;
#ifdef XSLT_REFACTORED
comp = (xsltStyleItemAttributePtr) xsltNewStylePreComp(style,
XSLT_FUNC_ATTRIBUTE);
#else
comp = xsltNewStylePreComp(style, XSLT_FUNC_ATTRIBUTE);
#endif
if (comp == NULL)
return;
inst->psvi = comp;
comp->inst = inst;
/*
* Attribute "name".
*/
/*
* TODO: Precompile the AVT. See bug #344894.
*/
comp->name = xsltEvalStaticAttrValueTemplate(style, inst,
(const xmlChar *)"name",
NULL, &comp->has_name);
if (! comp->has_name) {
xsltTransformError(NULL, style, inst,
"XSLT-attribute: The attribute 'name' is missing.\n");
style->errors++;
return;
}
/*
* Attribute "namespace".
*/
/*
* TODO: Precompile the AVT. See bug #344894.
*/
comp->ns = xsltEvalStaticAttrValueTemplate(style, inst,
(const xmlChar *)"namespace",
NULL, &comp->has_ns);
if (comp->name != NULL) {
if (xmlValidateQName(comp->name, 0)) {
xsltTransformError(NULL, style, inst,
"xsl:attribute: The value '%s' of the attribute 'name' is "
"not a valid QName.\n", comp->name);
style->errors++;
} else if (xmlStrEqual(comp->name, BAD_CAST "xmlns")) {
xsltTransformError(NULL, style, inst,
"xsl:attribute: The attribute name 'xmlns' is not allowed.\n");
style->errors++;
} else {
const xmlChar *prefix = NULL, *name;
name = xsltSplitQName(style->dict, comp->name, &prefix);
if (prefix != NULL) {
if (comp->has_ns == 0) {
xmlNsPtr ns;
/*
* SPEC XSLT 1.0:
* "If the namespace attribute is not present, then the
* QName is expanded into an expanded-name using the
* namespace declarations in effect for the xsl:element
* element, including any default namespace declaration.
*/
ns = xmlSearchNs(inst->doc, inst, prefix);
if (ns != NULL) {
comp->ns = xmlDictLookup(style->dict, ns->href, -1);
comp->has_ns = 1;
#ifdef XSLT_REFACTORED
comp->nsPrefix = prefix;
comp->name = name;
#endif
} else {
xsltTransformError(NULL, style, inst,
"xsl:attribute: The prefixed QName '%s' "
"has no namespace binding in scope in the "
"stylesheet; this is an error, since the "
"namespace was not specified by the instruction "
"itself.\n", comp->name);
style->errors++;
}
}
}
}
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
|
xsltAttributeComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
xsltStyleItemAttributePtr comp;
#else
xsltStylePreCompPtr comp;
#endif
/*
* <xsl:attribute
* name = { qname }
* namespace = { uri-reference }>
* <!-- Content: template -->
* </xsl:attribute>
*/
if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
return;
#ifdef XSLT_REFACTORED
comp = (xsltStyleItemAttributePtr) xsltNewStylePreComp(style,
XSLT_FUNC_ATTRIBUTE);
#else
comp = xsltNewStylePreComp(style, XSLT_FUNC_ATTRIBUTE);
#endif
if (comp == NULL)
return;
inst->psvi = comp;
comp->inst = inst;
/*
* Attribute "name".
*/
/*
* TODO: Precompile the AVT. See bug #344894.
*/
comp->name = xsltEvalStaticAttrValueTemplate(style, inst,
(const xmlChar *)"name",
NULL, &comp->has_name);
if (! comp->has_name) {
xsltTransformError(NULL, style, inst,
"XSLT-attribute: The attribute 'name' is missing.\n");
style->errors++;
return;
}
/*
* Attribute "namespace".
*/
/*
* TODO: Precompile the AVT. See bug #344894.
*/
comp->ns = xsltEvalStaticAttrValueTemplate(style, inst,
(const xmlChar *)"namespace",
NULL, &comp->has_ns);
if (comp->name != NULL) {
if (xmlValidateQName(comp->name, 0)) {
xsltTransformError(NULL, style, inst,
"xsl:attribute: The value '%s' of the attribute 'name' is "
"not a valid QName.\n", comp->name);
style->errors++;
} else if (xmlStrEqual(comp->name, BAD_CAST "xmlns")) {
xsltTransformError(NULL, style, inst,
"xsl:attribute: The attribute name 'xmlns' is not allowed.\n");
style->errors++;
} else {
const xmlChar *prefix = NULL, *name;
name = xsltSplitQName(style->dict, comp->name, &prefix);
if (prefix != NULL) {
if (comp->has_ns == 0) {
xmlNsPtr ns;
/*
* SPEC XSLT 1.0:
* "If the namespace attribute is not present, then the
* QName is expanded into an expanded-name using the
* namespace declarations in effect for the xsl:element
* element, including any default namespace declaration.
*/
ns = xmlSearchNs(inst->doc, inst, prefix);
if (ns != NULL) {
comp->ns = xmlDictLookup(style->dict, ns->href, -1);
comp->has_ns = 1;
#ifdef XSLT_REFACTORED
comp->nsPrefix = prefix;
comp->name = name;
#else
(void)name; /* Suppress unused variable warning. */
#endif
} else {
xsltTransformError(NULL, style, inst,
"xsl:attribute: The prefixed QName '%s' "
"has no namespace binding in scope in the "
"stylesheet; this is an error, since the "
"namespace was not specified by the instruction "
"itself.\n", comp->name);
style->errors++;
}
}
}
}
}
}
| 173,315
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) {
int rc;
struct ssh_userdata *sshu = NULL;
assert(lua_gettop(L) == 4);
sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2");
while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 3, "filter");
lua_pushvalue(L, 3);
assert(lua_status(L) == LUA_OK);
lua_callk(L, 1, 0, 0, do_session_handshake);
}
if (rc) {
libssh2_session_free(sshu->session);
return luaL_error(L, "Unable to complete libssh2 handshake.");
}
lua_settop(L, 3);
return 1;
}
Commit Message: Avoid a crash (double-free) when SSH connection fails
CWE ID: CWE-415
|
static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) {
int rc;
struct ssh_userdata *sshu = NULL;
assert(lua_gettop(L) == 4);
sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2");
while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 3, "filter");
lua_pushvalue(L, 3);
assert(lua_status(L) == LUA_OK);
lua_callk(L, 1, 0, 0, do_session_handshake);
}
if (rc) {
libssh2_session_free(sshu->session);
sshu->session = NULL;
return luaL_error(L, "Unable to complete libssh2 handshake.");
}
lua_settop(L, 3);
return 1;
}
| 169,856
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static PHP_FUNCTION(gzopen)
{
char *filename;
char *mode;
int filename_len, mode_len;
int flags = REPORT_ERRORS;
php_stream *stream;
long use_include_path = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) {
return;
}
if (use_include_path) {
flags |= USE_PATH;
}
stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC);
if (!stream) {
RETURN_FALSE;
}
php_stream_to_zval(stream, return_value);
}
Commit Message:
CWE ID: CWE-254
|
static PHP_FUNCTION(gzopen)
{
char *filename;
char *mode;
int filename_len, mode_len;
int flags = REPORT_ERRORS;
php_stream *stream;
long use_include_path = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) {
return;
}
if (use_include_path) {
flags |= USE_PATH;
}
stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC);
if (!stream) {
RETURN_FALSE;
}
php_stream_to_zval(stream, return_value);
}
| 165,319
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void TabContentsContainerGtk::DetachTab(TabContents* tab) {
gfx::NativeView widget = tab->web_contents()->GetNativeView();
if (widget) {
GtkWidget* parent = gtk_widget_get_parent(widget);
if (parent) {
DCHECK_EQ(parent, expanded_);
gtk_container_remove(GTK_CONTAINER(expanded_), widget);
}
}
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void TabContentsContainerGtk::DetachTab(TabContents* tab) {
void TabContentsContainerGtk::DetachTab(WebContents* tab) {
gfx::NativeView widget = tab->GetNativeView();
if (widget) {
GtkWidget* parent = gtk_widget_get_parent(widget);
if (parent) {
DCHECK_EQ(parent, expanded_);
gtk_container_remove(GTK_CONTAINER(expanded_), widget);
}
}
}
| 171,515
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 0;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 0;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
|
_exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 1;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 1;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
| 173,290
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 char *print_string( cJSON *item )
{
return print_string_ptr( item->valuestring );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
static char *print_string( cJSON *item )
| 167,309
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), GetExtension()->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
GetExtension()->id(),
GetExtension()->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
const Extension* extension = GetExtension();
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(::switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), extension->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
::switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
extension->id(),
extension->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
| 171,654
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
return(int)sig_recv;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
TEMP_FAILURE_RETRY(recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL));
return(int)sig_recv;
}
| 173,443
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BGD_DECLARE(void) gdImageWebpEx (gdImagePtr im, FILE * outFile, int quality)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out == NULL) {
return;
}
gdImageWebpCtx(im, out, quality);
out->gd_free(out);
}
Commit Message: Fix double-free in gdImageWebPtr()
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org.
CVE-2016-6912
CWE ID: CWE-415
|
BGD_DECLARE(void) gdImageWebpEx (gdImagePtr im, FILE * outFile, int quality)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out == NULL) {
return;
}
_gdImageWebpCtx(im, out, quality);
out->gd_free(out);
}
| 168,818
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DaemonProcess::OnChannelConnected() {
DCHECK(caller_task_runner()->BelongsToCurrentThread());
DeleteAllDesktopSessions();
next_terminal_id_ = 0;
SendToNetwork(
new ChromotingDaemonNetworkMsg_Configuration(serialized_config_));
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void DaemonProcess::OnChannelConnected() {
void DaemonProcess::OnChannelConnected(int32 peer_pid) {
DCHECK(caller_task_runner()->BelongsToCurrentThread());
DeleteAllDesktopSessions();
next_terminal_id_ = 0;
SendToNetwork(
new ChromotingDaemonNetworkMsg_Configuration(serialized_config_));
}
| 171,540
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.