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: gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height) { const unsigned int src_width = src->sx; const unsigned int src_height = src->sy; gdImagePtr tmp_im = NULL; gdImagePtr dst = NULL; /* First, handle the trivial case. */ if (src_width == new_width && src_height == new_height) { return gdImageClone(src); }/* if */ /* Convert to truecolor if it isn't; this code requires it. */ if (!src->trueColor) { gdImagePaletteToTrueColor(src); }/* if */ /* Scale horizontally unless sizes are the same. */ if (src_width == new_width) { tmp_im = src; } else { tmp_im = gdImageCreateTrueColor(new_width, src_height); if (tmp_im == NULL) { return NULL; } gdImageSetInterpolationMethod(tmp_im, src->interpolation_id); _gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL); }/* if .. else*/ /* If vertical sizes match, we're done. */ if (src_height == new_height) { assert(tmp_im != src); return tmp_im; }/* if */ /* Otherwise, we need to scale vertically. */ dst = gdImageCreateTrueColor(new_width, new_height); if (dst != NULL) { gdImageSetInterpolationMethod(dst, src->interpolation_id); _gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL); }/* if */ if (src != tmp_im) { gdFree(tmp_im); }/* if */ return dst; }/* gdImageScaleTwoPass*/ Commit Message: gdImageScaleTwoPass memory leak fix Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and confirmed by @vapier. This bug actually bit me in production and I'm very thankful that it was reported with an easy fix. Fixes #173. CWE ID: CWE-399
gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height) { const unsigned int src_width = src->sx; const unsigned int src_height = src->sy; gdImagePtr tmp_im = NULL; gdImagePtr dst = NULL; /* First, handle the trivial case. */ if (src_width == new_width && src_height == new_height) { return gdImageClone(src); }/* if */ /* Convert to truecolor if it isn't; this code requires it. */ if (!src->trueColor) { gdImagePaletteToTrueColor(src); }/* if */ /* Scale horizontally unless sizes are the same. */ if (src_width == new_width) { tmp_im = src; } else { tmp_im = gdImageCreateTrueColor(new_width, src_height); if (tmp_im == NULL) { return NULL; } gdImageSetInterpolationMethod(tmp_im, src->interpolation_id); _gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL); }/* if .. else*/ /* If vertical sizes match, we're done. */ if (src_height == new_height) { assert(tmp_im != src); return tmp_im; }/* if */ /* Otherwise, we need to scale vertically. */ dst = gdImageCreateTrueColor(new_width, new_height); if (dst != NULL) { gdImageSetInterpolationMethod(dst, src->interpolation_id); _gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL); }/* if */ if (src != tmp_im) { gdImageDestroy(tmp_im); }/* if */ return dst; }/* gdImageScaleTwoPass*/
167,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: GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, buf.c_str() ); } } Commit Message: CWE ID: CWE-134
GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( "%s", buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, "%s", buf.c_str() ); } }
165,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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: 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
void CuePoint::Load(IMkvReader* pReader) { bool CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) // already loaded return true; 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 = ReadID(pReader, pos_, len); if (id != 0x3B) return false; 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 = ReadID(pReader, pos, len); if ((id < 0) || (pos + len > stop)) { return false; } pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); if ((size < 0) || (pos + len > stop)) { return false; } pos += len; // consume Size field if ((pos + size) > stop) { return false; } 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 } if (m_timecode < 0 || m_track_positions_count <= 0) { return false; } m_track_positions = new (std::nothrow) TrackPosition[m_track_positions_count]; if (m_track_positions == NULL) return false; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if (id < 0 || (pos + len) > stop) return false; 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++; if (!tp.Parse(pReader, pos, size)) { return false; } } pos += size; // consume payload if (pos > stop) return false; } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; return true; }
173,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct phy *serdes_simple_xlate(struct device *dev, struct of_phandle_args *args) { struct serdes_ctrl *ctrl = dev_get_drvdata(dev); unsigned int port, idx, i; if (args->args_count != 2) return ERR_PTR(-EINVAL); port = args->args[0]; idx = args->args[1]; for (i = 0; i <= SERDES_MAX; i++) { struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]); if (idx != macro->idx) continue; /* SERDES6G(0) is the only SerDes capable of QSGMII */ if (idx != SERDES6G(0) && macro->port >= 0) return ERR_PTR(-EBUSY); macro->port = port; return ctrl->phys[i]; } return ERR_PTR(-ENODEV); } Commit Message: phy: ocelot-serdes: fix out-of-bounds read Currently, there is an out-of-bounds read on array ctrl->phys, once variable i reaches the maximum array size of SERDES_MAX in the for loop. Fix this by changing the condition in the for loop from i <= SERDES_MAX to i < SERDES_MAX. Addresses-Coverity-ID: 1473966 ("Out-of-bounds read") Addresses-Coverity-ID: 1473959 ("Out-of-bounds read") Fixes: 51f6b410fc22 ("phy: add driver for Microsemi Ocelot SerDes muxing") Reviewed-by: Quentin Schulz <quentin.schulz@bootlin.com> Signed-off-by: Gustavo A. R. Silva <gustavo@embeddedor.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-125
static struct phy *serdes_simple_xlate(struct device *dev, struct of_phandle_args *args) { struct serdes_ctrl *ctrl = dev_get_drvdata(dev); unsigned int port, idx, i; if (args->args_count != 2) return ERR_PTR(-EINVAL); port = args->args[0]; idx = args->args[1]; for (i = 0; i < SERDES_MAX; i++) { struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]); if (idx != macro->idx) continue; /* SERDES6G(0) is the only SerDes capable of QSGMII */ if (idx != SERDES6G(0) && macro->port >= 0) return ERR_PTR(-EBUSY); macro->port = port; return ctrl->phys[i]; } return ERR_PTR(-ENODEV); }
169,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().finalizeStream(blobRegistryContext->url); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->finalizeStream(blobRegistryContext->url); }
170,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, addEmptyDir) { char *dirname; size_t dirname_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dirname, &dirname_len) == FAILURE) { return; } if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory"); return; } phar_mkdir(&phar_obj->archive, dirname, dirname_len); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, addEmptyDir) { char *dirname; size_t dirname_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &dirname, &dirname_len) == FAILURE) { return; } if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory"); return; } phar_mkdir(&phar_obj->archive, dirname, dirname_len); }
165,069
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) { DTLS1_RECORD_DATA *rdata; pitem *item; /* Limit the size of the queue to prevent DOS attacks */ if (pqueue_size(queue->q) >= 100) return 0; rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); item = pitem_new(priority, rdata); if (rdata == NULL || item == NULL) { if (rdata != NULL) OPENSSL_free(rdata); if (item != NULL) pitem_free(item); SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); return(0); } rdata->packet = s->packet; rdata->packet_length = s->packet_length; memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); item->data = rdata; #ifndef OPENSSL_NO_SCTP /* Store bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) { BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif s->packet = NULL; s->packet_length = 0; memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); if (!ssl3_setup_buffers(s)) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); OPENSSL_free(rdata); pitem_free(item); return(0); } /* insert should not fail, since duplicates are dropped */ if (pqueue_insert(queue->q, item) == NULL) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); OPENSSL_free(rdata); pitem_free(item); return(0); } return(1); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <steve@openssl.org> CWE ID: CWE-119
dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) { DTLS1_RECORD_DATA *rdata; pitem *item; /* Limit the size of the queue to prevent DOS attacks */ if (pqueue_size(queue->q) >= 100) return 0; rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); item = pitem_new(priority, rdata); if (rdata == NULL || item == NULL) { if (rdata != NULL) OPENSSL_free(rdata); if (item != NULL) pitem_free(item); SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); return(0); } rdata->packet = s->packet; rdata->packet_length = s->packet_length; memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); item->data = rdata; #ifndef OPENSSL_NO_SCTP /* Store bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) { BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif s->packet = NULL; s->packet_length = 0; memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); if (!ssl3_setup_buffers(s)) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); if (rdata->rbuf.buf != NULL) OPENSSL_free(rdata->rbuf.buf); OPENSSL_free(rdata); pitem_free(item); return(-1); } /* insert should not fail, since duplicates are dropped */ if (pqueue_insert(queue->q, item) == NULL) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); if (rdata->rbuf.buf != NULL) OPENSSL_free(rdata->rbuf.buf); OPENSSL_free(rdata); pitem_free(item); return(-1); } return(1); }
166,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster::GetFirstTime() const { const BlockEntry* pEntry; const long status = GetFirst(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } 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 Cluster::GetFirstTime() const
174,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error) { setDeviceOrientationOverride(error, 0, 0, 0); } Commit Message: DevTools: remove references to modules/device_orientation from core BUG=340221 Review URL: https://codereview.chromium.org/150913003 git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
171,402
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: video_usercopy(struct file *file, unsigned int cmd, unsigned long arg, v4l2_kioctl func) { char sbuf[128]; void *mbuf = NULL; void *parg = NULL; long err = -EINVAL; int is_ext_ctrl; size_t ctrls_size = 0; void __user *user_ptr = NULL; is_ext_ctrl = (cmd == VIDIOC_S_EXT_CTRLS || cmd == VIDIOC_G_EXT_CTRLS || cmd == VIDIOC_TRY_EXT_CTRLS); /* Copy arguments into temp kernel buffer */ switch (_IOC_DIR(cmd)) { case _IOC_NONE: parg = NULL; break; case _IOC_READ: case _IOC_WRITE: case (_IOC_WRITE | _IOC_READ): if (_IOC_SIZE(cmd) <= sizeof(sbuf)) { parg = sbuf; } else { /* too big to allocate from stack */ mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (NULL == mbuf) return -ENOMEM; parg = mbuf; } err = -EFAULT; if (_IOC_DIR(cmd) & _IOC_WRITE) if (copy_from_user(parg, (void __user *)arg, _IOC_SIZE(cmd))) goto out; break; } if (is_ext_ctrl) { struct v4l2_ext_controls *p = parg; /* In case of an error, tell the caller that it wasn't a specific control that caused it. */ p->error_idx = p->count; user_ptr = (void __user *)p->controls; if (p->count) { ctrls_size = sizeof(struct v4l2_ext_control) * p->count; /* Note: v4l2_ext_controls fits in sbuf[] so mbuf is still NULL. */ mbuf = kmalloc(ctrls_size, GFP_KERNEL); err = -ENOMEM; if (NULL == mbuf) goto out_ext_ctrl; err = -EFAULT; if (copy_from_user(mbuf, user_ptr, ctrls_size)) goto out_ext_ctrl; p->controls = mbuf; } } /* call driver */ err = func(file, cmd, parg); if (err == -ENOIOCTLCMD) err = -EINVAL; if (is_ext_ctrl) { struct v4l2_ext_controls *p = parg; p->controls = (void *)user_ptr; if (p->count && err == 0 && copy_to_user(user_ptr, mbuf, ctrls_size)) err = -EFAULT; goto out_ext_ctrl; } if (err < 0) goto out; out_ext_ctrl: /* Copy results into user buffer */ switch (_IOC_DIR(cmd)) { case _IOC_READ: case (_IOC_WRITE | _IOC_READ): if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd))) err = -EFAULT; break; } out: kfree(mbuf); return err; } Commit Message: [media] v4l: Share code between video_usercopy and video_ioctl2 The two functions are mostly identical. They handle the copy_from_user and copy_to_user operations related with V4L2 ioctls and call the real ioctl handler. Create a __video_usercopy function that implements the core of video_usercopy and video_ioctl2, and call that function from both. Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com> Acked-by: Hans Verkuil <hverkuil@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab@redhat.com> CWE ID: CWE-399
video_usercopy(struct file *file, unsigned int cmd, unsigned long arg,
168,916
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "VERSION")) return; reply(nickFromMask(prefix), "VERSION", QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org") .arg(Quassel::buildInfo().plainVersionString) .arg(Quassel::buildInfo().buildDate)); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP VERSION request by %1").arg(prefix)); } else { str.append(tr(" with arguments: %1").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str); } } Commit Message: CWE ID: CWE-399
void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &reply) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { reply = QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org").arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP VERSION request by %1").arg(prefix)); } else { str.append(tr(" with arguments: %1").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str); } }
164,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; if (S_ISDIR(mode)) mode |= S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; } Commit Message: Fix up non-directory creation in SGID directories sgid directories have special semantics, making newly created files in the directory belong to the group of the directory, and newly created subdirectories will also become sgid. This is historically used for group-shared directories. But group directories writable by non-group members should not imply that such non-group members can magically join the group, so make sure to clear the sgid bit on non-directories for non-members (but remember that sgid without group execute means "mandatory locking", just to confuse things even more). Reported-by: Jann Horn <jannh@google.com> Cc: Andy Lutomirski <luto@kernel.org> Cc: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-269
void inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; /* Directories are special, and always inherit S_ISGID */ if (S_ISDIR(mode)) mode |= S_ISGID; else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) && !in_group_p(inode->i_gid) && !capable_wrt_inode_uidgid(dir, CAP_FSETID)) mode &= ~S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; }
169,153
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); } Commit Message: KVM: Don't accept obviously wrong gsi values via KVM_IRQFD We cannot add routes for gsi values >= KVM_MAX_IRQ_ROUTES -- see kvm_set_irq_routing(). Hence, there is no sense in accepting them via KVM_IRQFD. Prevent them from entering the system in the first place. Signed-off-by: Jan H. Schönherr <jschoenh@amazon.de> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-20
kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->gsi >= KVM_MAX_IRQ_ROUTES) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); }
167,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: monitor_init(void) { struct ssh *ssh = active_state; /* XXX */ struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); /* Used to share zlib space across processes */ if (options.compression) { mon->m_zback = mm_create(NULL, MM_MEMSIZE); mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE); /* Compression needs to share state across borders */ ssh_packet_set_compress_hooks(ssh, mon->m_zlib, (ssh_packet_comp_alloc_func *)mm_zalloc, (ssh_packet_comp_free_func *)mm_zfree); } return mon; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
monitor_init(void) { struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); return mon; }
168,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); }
167,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs) { gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern; gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace; int code; uchar k, num_comps; pinst->saved->overprint_mode = pgs->overprint_mode; pinst->saved->overprint = pgs->overprint; num_comps = pgs->device->color_info.num_components; for (k = 0; k < num_comps; k++) { pgs->color_component_map.color_map[k] = pinst->saved->color_component_map.color_map[k]; } code = pcs->type->set_overprint(pcs, pgs); return code; } Commit Message: CWE ID: CWE-704
gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs) { gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern; gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace; int code; uchar k, num_comps; pinst->saved->overprint_mode = pgs->overprint_mode; pinst->saved->overprint = pgs->overprint; num_comps = pgs->device->color_info.num_components; for (k = 0; k < num_comps; k++) { pgs->color_component_map.color_map[k] = pinst->saved->color_component_map.color_map[k]; } code = pcs->type->set_overprint(pcs, pgs); return code; }
164,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AutoFillManager::LogMetricsAboutSubmittedForm( const FormData& form, const FormStructure* submitted_form) { FormStructure* cached_submitted_form; if (!FindCachedForm(form, &cached_submitted_form)) { NOTREACHED(); return; } std::map<std::string, const AutoFillField*> cached_fields; for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) { const AutoFillField* field = cached_submitted_form->field(i); cached_fields[field->FieldSignature()] = field; } for (size_t i = 0; i < submitted_form->field_count(); ++i) { const AutoFillField* field = submitted_form->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); DCHECK(!field_types.empty()); if (field->form_control_type() == ASCIIToUTF16("select-one")) { continue; } metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED); if (field_types.find(EMPTY_TYPE) == field_types.end() && field_types.find(UNKNOWN_TYPE) == field_types.end()) { if (field->is_autofilled()) { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED); } else { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED); AutoFillFieldType heuristic_type = UNKNOWN_TYPE; AutoFillFieldType server_type = NO_SERVER_DATA; std::map<std::string, const AutoFillField*>::const_iterator cached_field = cached_fields.find(field->FieldSignature()); if (cached_field != cached_fields.end()) { heuristic_type = cached_field->second->heuristic_type(); server_type = cached_field->second->server_type(); } if (heuristic_type == UNKNOWN_TYPE) metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN); else if (field_types.count(heuristic_type)) metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH); else metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH); if (server_type == NO_SERVER_DATA) metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN); else if (field_types.count(server_type)) metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH); else metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH); } } } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillManager::LogMetricsAboutSubmittedForm( const FormData& form, const FormStructure* submitted_form) { FormStructure* cached_submitted_form; if (!FindCachedForm(form, &cached_submitted_form)) { NOTREACHED(); return; } std::map<std::string, const AutoFillField*> cached_fields; for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) { const AutoFillField* field = cached_submitted_form->field(i); cached_fields[field->FieldSignature()] = field; } std::string experiment_id = cached_submitted_form->server_experiment_id(); for (size_t i = 0; i < submitted_form->field_count(); ++i) { const AutoFillField* field = submitted_form->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); DCHECK(!field_types.empty()); if (field->form_control_type() == ASCIIToUTF16("select-one")) { continue; } metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED, experiment_id); if (field_types.find(EMPTY_TYPE) == field_types.end() && field_types.find(UNKNOWN_TYPE) == field_types.end()) { if (field->is_autofilled()) { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED, experiment_id); } else { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED, experiment_id); AutoFillFieldType heuristic_type = UNKNOWN_TYPE; AutoFillFieldType server_type = NO_SERVER_DATA; std::map<std::string, const AutoFillField*>::const_iterator cached_field = cached_fields.find(field->FieldSignature()); if (cached_field != cached_fields.end()) { heuristic_type = cached_field->second->heuristic_type(); server_type = cached_field->second->server_type(); } if (heuristic_type == UNKNOWN_TYPE) { metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN, experiment_id); } else if (field_types.count(heuristic_type)) { metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH, experiment_id); } else { metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH, experiment_id); } if (server_type == NO_SERVER_DATA) { metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN, experiment_id); } else if (field_types.count(server_type)) { metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH, experiment_id); } else { metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH, experiment_id); } } } } }
170,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "SetImeConfig: IBus connection is not alive"; return false; } bool is_preload_engines = false; std::vector<std::string> string_list; if ((value.type == ImeConfigValue::kValueTypeStringList) && (section == kGeneralSectionName) && (config_name == kPreloadEnginesConfigName)) { FilterInputMethods(value.string_list_value, &string_list); is_preload_engines = true; } else { string_list = value.string_list_value; } GVariant* variant = NULL; switch (value.type) { case ImeConfigValue::kValueTypeString: variant = g_variant_new_string(value.string_value.c_str()); break; case ImeConfigValue::kValueTypeInt: variant = g_variant_new_int32(value.int_value); break; case ImeConfigValue::kValueTypeBool: variant = g_variant_new_boolean(value.bool_value); break; case ImeConfigValue::kValueTypeStringList: GVariantBuilder variant_builder; g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as")); const size_t size = string_list.size(); // don't use string_list_value. for (size_t i = 0; i < size; ++i) { g_variant_builder_add(&variant_builder, "s", string_list[i].c_str()); } variant = g_variant_builder_end(&variant_builder); break; } if (!variant) { LOG(ERROR) << "SetImeConfig: variant is NULL"; return false; } DCHECK(g_variant_is_floating(variant)); ibus_config_set_value_async(ibus_config_, section.c_str(), config_name.c_str(), variant, -1, // use the default ibus timeout NULL, // cancellable SetImeConfigCallback, g_object_ref(ibus_config_)); if (is_preload_engines) { DLOG(INFO) << "SetImeConfig: " << section << "/" << config_name << ": " << value.ToString(); } return true; } 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
bool SetImeConfig(const std::string& section, // IBusController override. virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "SetImeConfig: IBus connection is not alive"; return false; } bool is_preload_engines = false; std::vector<std::string> string_list; if ((value.type == ImeConfigValue::kValueTypeStringList) && (section == kGeneralSectionName) && (config_name == kPreloadEnginesConfigName)) { FilterInputMethods(value.string_list_value, &string_list); is_preload_engines = true; } else { string_list = value.string_list_value; } GVariant* variant = NULL; switch (value.type) { case ImeConfigValue::kValueTypeString: variant = g_variant_new_string(value.string_value.c_str()); break; case ImeConfigValue::kValueTypeInt: variant = g_variant_new_int32(value.int_value); break; case ImeConfigValue::kValueTypeBool: variant = g_variant_new_boolean(value.bool_value); break; case ImeConfigValue::kValueTypeStringList: GVariantBuilder variant_builder; g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as")); const size_t size = string_list.size(); // don't use string_list_value. for (size_t i = 0; i < size; ++i) { g_variant_builder_add(&variant_builder, "s", string_list[i].c_str()); } variant = g_variant_builder_end(&variant_builder); break; } if (!variant) { LOG(ERROR) << "SetImeConfig: variant is NULL"; return false; } DCHECK(g_variant_is_floating(variant)); ibus_config_set_value_async(ibus_config_, section.c_str(), config_name.c_str(), variant, -1, // use the default ibus timeout NULL, // cancellable SetImeConfigCallback, g_object_ref(ibus_config_)); if (is_preload_engines) { VLOG(1) << "SetImeConfig: " << section << "/" << config_name << ": " << value.ToString(); } return true; }
170,547
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath) : InstallVerifyFrame_Base(NULL, wxID_ANY, _T("")) { mConfig = Config::GetConfig(); prepareDialog(); int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME; wxProgressDialog lPrepareProgress(_("Preparing"), _("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags); BZip lBZip(lDmodFilePath); mTarFilePath = lBZip.Extract(&lPrepareProgress); if (mTarFilePath.Len() != 0) { Tar lTar(mTarFilePath); lTar.ReadHeaders(); wxString lDmodDescription = lTar.getmDmodDescription(); "\n" "The D-Mod will be installed in subdirectory '%s'."), lTar.getInstalledDmodDirectory().c_str()); } else { int lBreakChar = lDmodDescription.Find( '\r' ); if ( lBreakChar <= 0 ) { lBreakChar = lDmodDescription.Find( '\n' ); } mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 ); this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName); } mDmodDescription->SetValue(lDmodDescription); mInstallButton->Enable(true); } Commit Message: CWE ID: CWE-22
InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath) : InstallVerifyFrame_Base(NULL, wxID_ANY, _T("")) { mConfig = Config::GetConfig(); prepareDialog(); int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME; wxProgressDialog lPrepareProgress(_("Preparing"), _("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags); BZip lBZip(lDmodFilePath); mTarFilePath = lBZip.Extract(&lPrepareProgress); if (mTarFilePath.Len() != 0) { Tar lTar(mTarFilePath); if (lTar.ReadHeaders() == 1) { this->EndModal(wxID_CANCEL); return; } wxString lDmodDescription = lTar.getmDmodDescription(); "\n" "The D-Mod will be installed in subdirectory '%s'."), lTar.getInstalledDmodDirectory().c_str()); } else { int lBreakChar = lDmodDescription.Find( '\r' ); if ( lBreakChar <= 0 ) { lBreakChar = lDmodDescription.Find( '\n' ); } mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 ); this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName); } mDmodDescription->SetValue(lDmodDescription); mInstallButton->Enable(true); }
165,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client) : binding_(this), agent_host_(agent_host), client_(client), process_(nullptr), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client) : binding_(this), agent_host_(agent_host), client_(client), process_host_id_(ChildProcessHost::kInvalidUniqueID), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); }
172,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), re->flags | RE_FLAGS_SCAN, NULL, NULL); } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125
int yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), 0, re->flags | RE_FLAGS_SCAN, NULL, NULL); }
168,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SkippedMBMotionComp( VideoDecData *video ) { Vop *prev = video->prevVop; Vop *comp; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int width, width_uv; int32 offset; #ifdef PV_POSTPROC_ON // 2/14/2001 int imv; int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; uint8 *pp_prev1; int mvwidth = video->nMBPerRow << 1; #endif width = video->width; width_uv = width >> 1; ypos = video->mbnum_row << 4 ; xpos = video->mbnum_col << 4 ; offset = (int32)ypos * width + xpos; /* zero motion compensation for previous frame */ /*mby*width + mbx;*/ c_prev = prev->yChan + offset; /*by*width_uv + bx;*/ cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2); /*by*width_uv + bx;*/ cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2); comp = video->currVop; c_comp = comp->yChan + offset; cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2); cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2); /* Copy previous reconstructed frame into the current frame */ PutSKIPPED_MB(c_comp, c_prev, width); PutSKIPPED_B(cu_comp, cu_prev, width_uv); PutSKIPPED_B(cv_comp, cv_prev, width_uv); /* 10/24/2000 post_processing semaphore generation */ #ifdef PV_POSTPROC_ON // 2/14/2001 if (video->postFilterType != PV_NO_POST_PROC) { imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); /* Post-processing mode (copy previous MB) */ pp_prev1 = video->pstprcTypPrv + imv; pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = *pp_prev1; *(pp_dec_y + 1) = *(pp_prev1 + 1); *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth); *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1); /* chrominance */ /*4*MB_in_width*MB_in_height*/ pp_prev1 = video->pstprcTypPrv + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = *pp_prev1; pp_dec_u[size>>8] = pp_prev1[size>>8]; } #endif /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/ return; } Commit Message: Fix NPDs in h263 decoder Bug: 35269635 Test: decoded PoC with and without patch Change-Id: I636a14360c7801cc5bca63c9cb44d1d235df8fd8 (cherry picked from commit 2ad2a92318a3b9daf78ebcdc597085adbf32600d) CWE ID:
void SkippedMBMotionComp( VideoDecData *video ) { Vop *prev = video->prevVop; Vop *comp; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int width, width_uv; int32 offset; #ifdef PV_POSTPROC_ON // 2/14/2001 int imv; int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; uint8 *pp_prev1; int mvwidth = video->nMBPerRow << 1; #endif width = video->width; width_uv = width >> 1; ypos = video->mbnum_row << 4 ; xpos = video->mbnum_col << 4 ; offset = (int32)ypos * width + xpos; /* zero motion compensation for previous frame */ /*mby*width + mbx;*/ c_prev = prev->yChan; if (!c_prev) { ALOGE("b/35269635"); android_errorWriteLog(0x534e4554, "35269635"); return; } c_prev += offset; /*by*width_uv + bx;*/ cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2); /*by*width_uv + bx;*/ cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2); comp = video->currVop; c_comp = comp->yChan + offset; cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2); cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2); /* Copy previous reconstructed frame into the current frame */ PutSKIPPED_MB(c_comp, c_prev, width); PutSKIPPED_B(cu_comp, cu_prev, width_uv); PutSKIPPED_B(cv_comp, cv_prev, width_uv); /* 10/24/2000 post_processing semaphore generation */ #ifdef PV_POSTPROC_ON // 2/14/2001 if (video->postFilterType != PV_NO_POST_PROC) { imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); /* Post-processing mode (copy previous MB) */ pp_prev1 = video->pstprcTypPrv + imv; pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = *pp_prev1; *(pp_dec_y + 1) = *(pp_prev1 + 1); *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth); *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1); /* chrominance */ /*4*MB_in_width*MB_in_height*/ pp_prev1 = video->pstprcTypPrv + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = *pp_prev1; pp_dec_u[size>>8] = pp_prev1[size>>8]; } #endif /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/ return; }
174,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 V8DOMWindow::namedSecurityCheckCustom(v8::Local<v8::Object> host, v8::Local<v8::Value> key, v8::AccessType type, v8::Local<v8::Value>) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Object> window = host->FindInstanceInPrototypeChain(V8DOMWindow::GetTemplate(isolate, worldTypeInMainThread(isolate))); if (window.IsEmpty()) return false; // the frame is gone. DOMWindow* targetWindow = V8DOMWindow::toNative(window); ASSERT(targetWindow); Frame* target = targetWindow->frame(); if (!target) return false; if (target->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) target->loader()->didAccessInitialDocument(); if (key->IsString()) { DEFINE_STATIC_LOCAL(AtomicString, nameOfProtoProperty, ("__proto__", AtomicString::ConstructFromLiteral)); String name = toWebCoreString(key); Frame* childFrame = target->tree()->scopedChild(name); if (type == v8::ACCESS_HAS && childFrame) return true; if (type == v8::ACCESS_GET && childFrame && !host->HasRealNamedProperty(key->ToString()) && name != nameOfProtoProperty) return true; } return BindingSecurity::shouldAllowAccessToFrame(target, DoNotReportSecurityError); } Commit Message: Named access checks on DOMWindow miss navigator The design of the named access check is very fragile. Instead of doing the access check at the same time as the access, we need to check access in a separate operation using different parameters. Worse, we need to implement a part of the access check as a blacklist of dangerous properties. This CL expands the blacklist slightly by adding in the real named properties from the DOMWindow instance to the current list (which included the real named properties of the shadow object). In the longer term, we should investigate whether we can change the V8 API to let us do the access check in the same callback as the property access itself. BUG=237022 Review URL: https://chromiumcodereview.appspot.com/15346002 git-svn-id: svn://svn.chromium.org/blink/trunk@150616 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
bool V8DOMWindow::namedSecurityCheckCustom(v8::Local<v8::Object> host, v8::Local<v8::Value> key, v8::AccessType type, v8::Local<v8::Value>) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Object> window = host->FindInstanceInPrototypeChain(V8DOMWindow::GetTemplate(isolate, worldTypeInMainThread(isolate))); if (window.IsEmpty()) return false; // the frame is gone. DOMWindow* targetWindow = V8DOMWindow::toNative(window); ASSERT(targetWindow); Frame* target = targetWindow->frame(); if (!target) return false; if (target->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) target->loader()->didAccessInitialDocument(); if (key->IsString()) { DEFINE_STATIC_LOCAL(AtomicString, nameOfProtoProperty, ("__proto__", AtomicString::ConstructFromLiteral)); String name = toWebCoreString(key); Frame* childFrame = target->tree()->scopedChild(name); if (type == v8::ACCESS_HAS && childFrame) return true; v8::Handle<v8::String> keyString = key->ToString(); if (type == v8::ACCESS_GET && childFrame && !host->HasRealNamedProperty(keyString) && !window->HasRealNamedProperty(keyString) && name != nameOfProtoProperty) return true; } return BindingSecurity::shouldAllowAccessToFrame(target, DoNotReportSecurityError); }
171,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void reference_32x32_dct_1d(const double in[32], double out[32], int stride) { const double kInvSqrt2 = 0.707106781186547524400844362104; for (int k = 0; k < 32; k++) { out[k] = 0.0; for (int n = 0; n < 32; n++) out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 64.0); if (k == 0) out[k] = out[k] * kInvSqrt2; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void reference_32x32_dct_1d(const double in[32], double out[32], int stride) { void reference_32x32_dct_1d(const double in[32], double out[32]) { const double kInvSqrt2 = 0.707106781186547524400844362104; for (int k = 0; k < 32; k++) { out[k] = 0.0; for (int n = 0; n < 32; n++) out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 64.0); if (k == 0) out[k] = out[k] * kInvSqrt2; } }
174,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) { int i; if (pbi->b_multithreaded_rd) { vpx_free(pbi->mt_current_mb_col); pbi->mt_current_mb_col = NULL ; /* Free above_row buffers. */ if (pbi->mt_yabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_yabove_row[i]); pbi->mt_yabove_row[i] = NULL ; } vpx_free(pbi->mt_yabove_row); pbi->mt_yabove_row = NULL ; } if (pbi->mt_uabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_uabove_row[i]); pbi->mt_uabove_row[i] = NULL ; } vpx_free(pbi->mt_uabove_row); pbi->mt_uabove_row = NULL ; } if (pbi->mt_vabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_vabove_row[i]); pbi->mt_vabove_row[i] = NULL ; } vpx_free(pbi->mt_vabove_row); pbi->mt_vabove_row = NULL ; } /* Free left_col buffers. */ if (pbi->mt_yleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_yleft_col[i]); pbi->mt_yleft_col[i] = NULL ; } vpx_free(pbi->mt_yleft_col); pbi->mt_yleft_col = NULL ; } if (pbi->mt_uleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_uleft_col[i]); pbi->mt_uleft_col[i] = NULL ; } vpx_free(pbi->mt_uleft_col); pbi->mt_uleft_col = NULL ; } if (pbi->mt_vleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_vleft_col[i]); pbi->mt_vleft_col[i] = NULL ; } vpx_free(pbi->mt_vleft_col); pbi->mt_vleft_col = NULL ; } } } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
void vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) void vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) { int i; vpx_free(pbi->mt_current_mb_col); pbi->mt_current_mb_col = NULL; /* Free above_row buffers. */ if (pbi->mt_yabove_row) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_yabove_row[i]); pbi->mt_yabove_row[i] = NULL; } vpx_free(pbi->mt_yabove_row); pbi->mt_yabove_row = NULL; } if (pbi->mt_uabove_row) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_uabove_row[i]); pbi->mt_uabove_row[i] = NULL; } vpx_free(pbi->mt_uabove_row); pbi->mt_uabove_row = NULL; } if (pbi->mt_vabove_row) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_vabove_row[i]); pbi->mt_vabove_row[i] = NULL; } vpx_free(pbi->mt_vabove_row); pbi->mt_vabove_row = NULL; } /* Free left_col buffers. */ if (pbi->mt_yleft_col) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_yleft_col[i]); pbi->mt_yleft_col[i] = NULL; } vpx_free(pbi->mt_yleft_col); pbi->mt_yleft_col = NULL; } if (pbi->mt_uleft_col) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_uleft_col[i]); pbi->mt_uleft_col[i] = NULL; } vpx_free(pbi->mt_uleft_col); pbi->mt_uleft_col = NULL; } if (pbi->mt_vleft_col) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_vleft_col[i]); pbi->mt_vleft_col[i] = NULL; } vpx_free(pbi->mt_vleft_col); pbi->mt_vleft_col = NULL; } }
174,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } else { ALOGE("b/21657957"); return NULL; } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); }
173,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; }
165,661
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void virgl_resource_attach_backing(VirtIOGPU *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_resource_attach_backing att_rb; struct iovec *res_iovs; int ret; VIRTIO_GPU_FILL_CMD(att_rb); trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id); ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs); if (ret != 0) { cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC; return; } virgl_renderer_resource_attach_iov(att_rb.resource_id, res_iovs, att_rb.nr_entries); } Commit Message: CWE ID: CWE-772
static void virgl_resource_attach_backing(VirtIOGPU *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_resource_attach_backing att_rb; struct iovec *res_iovs; int ret; VIRTIO_GPU_FILL_CMD(att_rb); trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id); ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs); if (ret != 0) { cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC; return; } ret = virgl_renderer_resource_attach_iov(att_rb.resource_id, res_iovs, att_rb.nr_entries); if (ret != 0) virtio_gpu_cleanup_mapping_iov(res_iovs, att_rb.nr_entries); }
164,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p, const struct http_conn *htc) { char *q, *r; txt t = htc->rxbuf; if (*p == '\r') p++; hp->nhd = HTTP_HDR_FIRST; hp->conds = 0; r = NULL; /* For FlexeLint */ for (; p < t.e; p = r) { /* Find end of next header */ q = r = p; while (r < t.e) { if (!vct_iscrlf(*r)) { r++; continue; } q = r; assert(r < t.e); r += vct_skipcrlf(r); if (r >= t.e) break; /* If line does not continue: got it. */ if (!vct_issp(*r)) break; /* Clear line continuation LWS to spaces */ while (vct_islws(*q)) *q++ = ' '; } if (q - p > htc->maxhdr) { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } /* Empty header = end of headers */ if (p == q) break; if ((p[0] == 'i' || p[0] == 'I') && (p[1] == 'f' || p[1] == 'F') && p[2] == '-') hp->conds = 1; while (q > p && vct_issp(q[-1])) q--; *q = '\0'; if (hp->nhd < hp->shd) { hp->hdf[hp->nhd] = 0; hp->hd[hp->nhd].b = p; hp->hd[hp->nhd].e = q; WSLH(w, fd, hp, hp->nhd); hp->nhd++; } else { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } } return (0); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] regis.leroy@makina-corpus.com CWE ID:
http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p, const struct http_conn *htc) { char *q, *r; txt t = htc->rxbuf; if (*p == '\r') p++; hp->nhd = HTTP_HDR_FIRST; hp->conds = 0; r = NULL; /* For FlexeLint */ for (; p < t.e; p = r) { /* Find end of next header */ q = r = p; while (r < t.e) { if (!vct_iscrlf(r)) { r++; continue; } q = r; assert(r < t.e); r += vct_skipcrlf(r); if (r >= t.e) break; /* If line does not continue: got it. */ if (!vct_issp(*r)) break; /* Clear line continuation LWS to spaces */ while (vct_islws(*q)) *q++ = ' '; } if (q - p > htc->maxhdr) { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } /* Empty header = end of headers */ if (p == q) break; if ((p[0] == 'i' || p[0] == 'I') && (p[1] == 'f' || p[1] == 'F') && p[2] == '-') hp->conds = 1; while (q > p && vct_issp(q[-1])) q--; *q = '\0'; if (hp->nhd < hp->shd) { hp->hdf[hp->nhd] = 0; hp->hd[hp->nhd].b = p; hp->hd[hp->nhd].e = q; WSLH(w, fd, hp, hp->nhd); hp->nhd++; } else { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } } return (0); }
169,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *jas_malloc(size_t size) { void *result; JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size)); result = malloc(size); JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result)); return result; } Commit Message: Fixed an integer overflow problem. CWE ID: CWE-190
void *jas_malloc(size_t size) { void *result; JAS_DBGLOG(101, ("jas_malloc(%zu)\n", size)); result = malloc(size); JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result)); return result; }
168,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); UpdateText(); } Commit Message: ash: Fix right-alignment of power-status text. It turns out setting ALING_RIGHT on a Label isn't enough to get proper right-aligned text. Label has to be explicitly told that it is multi-lined. BUG=none TEST=none Review URL: https://chromiumcodereview.appspot.com/9918026 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@129898 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); SetMultiLine(true); UpdateText(); }
170,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { return false; } 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
virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { return false; }
170,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeRemoteFrontendURL(const std::string& value) { GURL url(net::UnescapeURLComponent(value, net::UnescapeRule::SPACES | net::UnescapeRule::PATH_SEPARATORS | net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS | net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); std::string path = url.path(); std::vector<std::string> parts = base::SplitString( path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string revision = parts.size() > 2 ? parts[2] : ""; revision = SanitizeRevision(revision); std::string filename = parts.size() ? parts[parts.size() - 1] : ""; if (filename != "devtools.html") filename = "inspector.html"; path = base::StringPrintf("/serve_rev/%s/%s", revision.c_str(), filename.c_str()); std::string sanitized = SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, path, true).spec(); return net::EscapeQueryParamValue(sanitized, false); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeRemoteFrontendURL(const std::string& value) {
172,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } }
167,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cdxl_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt) { CDXLVideoContext *c = avctx->priv_data; AVFrame * const p = data; int ret, w, h, encoding, aligned_width, buf_size = pkt->size; const uint8_t *buf = pkt->data; if (buf_size < 32) return AVERROR_INVALIDDATA; encoding = buf[1] & 7; c->format = buf[1] & 0xE0; w = AV_RB16(&buf[14]); h = AV_RB16(&buf[16]); c->bpp = buf[19]; c->palette_size = AV_RB16(&buf[20]); c->palette = buf + 32; c->video = c->palette + c->palette_size; c->video_size = buf_size - c->palette_size - 32; if (c->palette_size > 512) return AVERROR_INVALIDDATA; if (buf_size < c->palette_size + 32) return AVERROR_INVALIDDATA; if (c->bpp < 1) return AVERROR_INVALIDDATA; if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) { avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_set_dimensions(avctx, w, h)) < 0) return ret; if (c->format == CHUNKY) aligned_width = avctx->width; else aligned_width = FFALIGN(c->avctx->width, 16); c->padded_bits = aligned_width - c->avctx->width; if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) return AVERROR_INVALIDDATA; if (!encoding && c->palette_size && c->bpp <= 8) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { if (c->palette_size != (1 << (c->bpp - 1))) return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_BGR24; } else if (!encoding && c->bpp == 24 && c->format == CHUNKY && !c->palette_size) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else { avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x", encoding, c->bpp, c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->pict_type = AV_PICTURE_TYPE_I; if (encoding) { av_fast_padded_malloc(&c->new_video, &c->new_video_size, h * w + AV_INPUT_BUFFER_PADDING_SIZE); if (!c->new_video) return AVERROR(ENOMEM); if (c->bpp == 8) cdxl_decode_ham8(c, p); else cdxl_decode_ham6(c, p); } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { cdxl_decode_rgb(c, p); } else { cdxl_decode_raw(c, p); } *got_frame = 1; return buf_size; } Commit Message: avcodec/cdxl: Check format parameter Fixes out of array access Fixes: 1378/clusterfuzz-testcase-minimized-5715088008806400 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int cdxl_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt) { CDXLVideoContext *c = avctx->priv_data; AVFrame * const p = data; int ret, w, h, encoding, aligned_width, buf_size = pkt->size; const uint8_t *buf = pkt->data; if (buf_size < 32) return AVERROR_INVALIDDATA; encoding = buf[1] & 7; c->format = buf[1] & 0xE0; w = AV_RB16(&buf[14]); h = AV_RB16(&buf[16]); c->bpp = buf[19]; c->palette_size = AV_RB16(&buf[20]); c->palette = buf + 32; c->video = c->palette + c->palette_size; c->video_size = buf_size - c->palette_size - 32; if (c->palette_size > 512) return AVERROR_INVALIDDATA; if (buf_size < c->palette_size + 32) return AVERROR_INVALIDDATA; if (c->bpp < 1) return AVERROR_INVALIDDATA; if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) { avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_set_dimensions(avctx, w, h)) < 0) return ret; if (c->format == CHUNKY) aligned_width = avctx->width; else aligned_width = FFALIGN(c->avctx->width, 16); c->padded_bits = aligned_width - c->avctx->width; if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) return AVERROR_INVALIDDATA; if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { if (c->palette_size != (1 << (c->bpp - 1))) return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_BGR24; } else if (!encoding && c->bpp == 24 && c->format == CHUNKY && !c->palette_size) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else { avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x", encoding, c->bpp, c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->pict_type = AV_PICTURE_TYPE_I; if (encoding) { av_fast_padded_malloc(&c->new_video, &c->new_video_size, h * w + AV_INPUT_BUFFER_PADDING_SIZE); if (!c->new_video) return AVERROR(ENOMEM); if (c->bpp == 8) cdxl_decode_ham8(c, p); else cdxl_decode_ham6(c, p); } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { cdxl_decode_rgb(c, p); } else { cdxl_decode_raw(c, p); } *got_frame = 1; return buf_size; }
170,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; int hlen = 20; int ttl = 64; uint8_t *pcontent; IPV4Hdr ip4h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip4h.ip_verhl = 4 << 4; ip4h.ip_verhl |= hlen >> 2; ip4h.ip_len = htons(hlen + content_len); ip4h.ip_id = htons(id); ip4h.ip_off = htons(off); if (mf) ip4h.ip_off = htons(IP_MF | off); else ip4h.ip_off = htons(off); ip4h.ip_ttl = ttl; ip4h.ip_proto = IPPROTO_ICMP; ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */ ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */ /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h)); p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p); SET_IPV4_SRC_ADDR(p, &p->src); SET_IPV4_DST_ADDR(p, &p->dst); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, hlen, pcontent, content_len); SET_PKT_LEN(p, hlen + content_len); SCFree(pcontent); p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen); /* Self test. */ if (IPV4_GET_VER(p) != 4) goto error; if (IPV4_GET_HLEN(p) != hlen) goto error; if (IPV4_GET_IPLEN(p) != hlen + content_len) goto error; if (IPV4_GET_IPID(p) != id) goto error; if (IPV4_GET_IPOFFSET(p) != off) goto error; if (IPV4_GET_MF(p) != mf) goto error; if (IPV4_GET_IPTTL(p) != ttl) goto error; if (IPV4_GET_IPPROTO(p) != IPPROTO_ICMP) goto error; return p; error: if (p != NULL) SCFree(p); return NULL; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; int hlen = 20; int ttl = 64; uint8_t *pcontent; IPV4Hdr ip4h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip4h.ip_verhl = 4 << 4; ip4h.ip_verhl |= hlen >> 2; ip4h.ip_len = htons(hlen + content_len); ip4h.ip_id = htons(id); ip4h.ip_off = htons(off); if (mf) ip4h.ip_off = htons(IP_MF | off); else ip4h.ip_off = htons(off); ip4h.ip_ttl = ttl; ip4h.ip_proto = proto; ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */ ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */ /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h)); p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p); SET_IPV4_SRC_ADDR(p, &p->src); SET_IPV4_DST_ADDR(p, &p->dst); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, hlen, pcontent, content_len); SET_PKT_LEN(p, hlen + content_len); SCFree(pcontent); p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen); /* Self test. */ if (IPV4_GET_VER(p) != 4) goto error; if (IPV4_GET_HLEN(p) != hlen) goto error; if (IPV4_GET_IPLEN(p) != hlen + content_len) goto error; if (IPV4_GET_IPID(p) != id) goto error; if (IPV4_GET_IPOFFSET(p) != off) goto error; if (IPV4_GET_MF(p) != mf) goto error; if (IPV4_GET_IPTTL(p) != ttl) goto error; if (IPV4_GET_IPPROTO(p) != proto) goto error; return p; error: if (p != NULL) SCFree(p); return NULL; }
168,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CSSStyleSheet::CanAccessRules() const { if (enable_rule_access_for_inspector_) return true; if (is_inline_stylesheet_) return true; KURL base_url = contents_->BaseURL(); if (base_url.IsEmpty()) return true; Document* document = OwnerDocument(); if (!document) return true; if (document->GetSecurityOrigin()->CanReadContent(base_url)) return true; if (allow_rule_access_from_origin_ && document->GetSecurityOrigin()->CanAccess( allow_rule_access_from_origin_.get())) { return true; } return false; } Commit Message: Disallow access to opaque CSS responses. Bug: 848786 Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec Reviewed-on: https://chromium-review.googlesource.com/1088335 Reviewed-by: Kouhei Ueno <kouhei@chromium.org> Commit-Queue: Matt Falkenhagen <falken@chromium.org> Cr-Commit-Position: refs/heads/master@{#565537} CWE ID: CWE-200
bool CSSStyleSheet::CanAccessRules() const { if (enable_rule_access_for_inspector_) return true; // Opaque responses should never be accessible, mod DevTools. See comments for // IsOpaqueResponseFromServiceWorker(). if (contents_->IsOpaqueResponseFromServiceWorker()) return false; if (is_inline_stylesheet_) return true; KURL base_url = contents_->BaseURL(); if (base_url.IsEmpty()) return true; Document* document = OwnerDocument(); if (!document) return true; if (document->GetSecurityOrigin()->CanReadContent(base_url)) return true; if (allow_rule_access_from_origin_ && document->GetSecurityOrigin()->CanAccess( allow_rule_access_from_origin_.get())) { return true; } return false; }
173,153
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH); Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Malloc = CL_RefMalloc; ri.Free = Z_Free; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_SetDescription = Cvar_SetDescription; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); #if defined __USEA3D && defined __A3D_GEOM hA3Dg_ExportRenderGeom (ret); #endif Com_Printf( "-------------------------------\n"); if ( !ret ) { Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Cvar_Set( "cl_paused", "0" ); } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269
void CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Malloc = CL_RefMalloc; ri.Free = Z_Free; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_SetDescription = Cvar_SetDescription; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); #if defined __USEA3D && defined __A3D_GEOM hA3Dg_ExportRenderGeom (ret); #endif Com_Printf( "-------------------------------\n"); if ( !ret ) { Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Cvar_Set( "cl_paused", "0" ); }
170,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 VarianceTest<VarianceFunctionType>::ZeroTest() { for (int i = 0; i <= 255; ++i) { memset(src_, i, block_size_); for (int j = 0; j <= 255; ++j) { memset(ref_, j, block_size_); unsigned int sse; unsigned int var; REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); EXPECT_EQ(0u, var) << "src values: " << i << "ref values: " << j; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void VarianceTest<VarianceFunctionType>::ZeroTest() { for (int i = 0; i <= 255; ++i) { if (!use_high_bit_depth_) { memset(src_, i, block_size_); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(src_), i << (bit_depth_ - 8), block_size_); #endif // CONFIG_VP9_HIGHBITDEPTH } for (int j = 0; j <= 255; ++j) { if (!use_high_bit_depth_) { memset(ref_, j, block_size_); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(ref_), j << (bit_depth_ - 8), block_size_); #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse; unsigned int var; ASM_REGISTER_STATE_CHECK( var = variance_(src_, width_, ref_, width_, &sse)); EXPECT_EQ(0u, var) << "src values: " << i << " ref values: " << j; } } }
174,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat) { ND_PRINT((ndo, "%u.%u", (EXTRACT_16BITS(dat) >> 8), (EXTRACT_16BITS(dat) & 0xff))); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat) l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat, u_int length) { if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u.%u", (EXTRACT_16BITS(dat) >> 8), (EXTRACT_16BITS(dat) & 0xff))); }
167,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode) { struct nfs_inode *nfsi = NFS_I(inode); struct nfs_open_context *pos, *ctx = NULL; spin_lock(&inode->i_lock); list_for_each_entry(pos, &nfsi->open_files, list) { if (cred != NULL && pos->cred != cred) continue; if ((pos->mode & mode) == mode) { ctx = get_nfs_open_context(pos); break; } } spin_unlock(&inode->i_lock); return ctx; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode) struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, fmode_t mode) { struct nfs_inode *nfsi = NFS_I(inode); struct nfs_open_context *pos, *ctx = NULL; spin_lock(&inode->i_lock); list_for_each_entry(pos, &nfsi->open_files, list) { if (cred != NULL && pos->cred != cred) continue; if ((pos->mode & mode) == mode) { ctx = get_nfs_open_context(pos); break; } } spin_unlock(&inode->i_lock); return ctx; }
165,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) { if (err != OK) { mMetaDataSize = -1ll; mContentType = ""; mSniffedMIME = ""; { sp<DataSource> dataSource = mDataSource; sp<NuCachedSource2> cachedSource = mCachedSource; sp<DataSource> httpSource = mHttpSource; { Mutex::Autolock _l(mDisconnectLock); mDataSource.clear(); mCachedSource.clear(); mHttpSource.clear(); } } cancelPollBuffering(); } notifyPrepared(err); } Commit Message: GenericSource: reset mDrmManagerClient when mDataSource is cleared. Bug: 25070434 Change-Id: Iade3472c496ac42456e42db35e402f7b66416f5b (cherry picked from commit b41fd0d4929f0a89811bafcc4fd944b128f00ce2) CWE ID: CWE-119
void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) { if (err != OK) { mMetaDataSize = -1ll; mContentType = ""; mSniffedMIME = ""; { sp<DataSource> dataSource = mDataSource; sp<NuCachedSource2> cachedSource = mCachedSource; sp<DataSource> httpSource = mHttpSource; { Mutex::Autolock _l(mDisconnectLock); mDataSource.clear(); mDrmManagerClient = NULL; mCachedSource.clear(); mHttpSource.clear(); } } cancelPollBuffering(); } notifyPrepared(err); }
173,969
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SoundTriggerHwService::Module::startRecognition(sound_model_handle_t handle, const sp<IMemory>& dataMemory) { ALOGV("startRecognition() model handle %d", handle); if (!captureHotwordAllowed()) { return PERMISSION_DENIED; } if (dataMemory != 0 && dataMemory->pointer() == NULL) { ALOGE("startRecognition() dataMemory is non-0 but has NULL pointer()"); return BAD_VALUE; } AutoMutex lock(mLock); if (mServiceState == SOUND_TRIGGER_STATE_DISABLED) { return INVALID_OPERATION; } sp<Model> model = getModel(handle); if (model == 0) { return BAD_VALUE; } if ((dataMemory == 0) || (dataMemory->size() < sizeof(struct sound_trigger_recognition_config))) { return BAD_VALUE; } if (model->mState == Model::STATE_ACTIVE) { return INVALID_OPERATION; } struct sound_trigger_recognition_config *config = (struct sound_trigger_recognition_config *)dataMemory->pointer(); config->capture_handle = model->mCaptureIOHandle; config->capture_device = model->mCaptureDevice; status_t status = mHwDevice->start_recognition(mHwDevice, handle, config, SoundTriggerHwService::recognitionCallback, this); if (status == NO_ERROR) { model->mState = Model::STATE_ACTIVE; model->mConfig = *config; } return status; } Commit Message: soundtrigger: add size check on sound model and recogntion data Bug: 30148546 Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0 (cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8) (cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd) CWE ID: CWE-264
status_t SoundTriggerHwService::Module::startRecognition(sound_model_handle_t handle, const sp<IMemory>& dataMemory) { ALOGV("startRecognition() model handle %d", handle); if (!captureHotwordAllowed()) { return PERMISSION_DENIED; } if (dataMemory == 0 || dataMemory->pointer() == NULL) { ALOGE("startRecognition() dataMemory is 0 or has NULL pointer()"); return BAD_VALUE; } struct sound_trigger_recognition_config *config = (struct sound_trigger_recognition_config *)dataMemory->pointer(); if (config->data_offset < sizeof(struct sound_trigger_recognition_config) || config->data_size > (UINT_MAX - config->data_offset) || dataMemory->size() < config->data_offset || config->data_size > (dataMemory->size() - config->data_offset)) { ALOGE("startRecognition() data_size is too big"); return BAD_VALUE; } AutoMutex lock(mLock); if (mServiceState == SOUND_TRIGGER_STATE_DISABLED) { return INVALID_OPERATION; } sp<Model> model = getModel(handle); if (model == 0) { return BAD_VALUE; } if (model->mState == Model::STATE_ACTIVE) { return INVALID_OPERATION; } config->capture_handle = model->mCaptureIOHandle; config->capture_device = model->mCaptureDevice; status_t status = mHwDevice->start_recognition(mHwDevice, handle, config, SoundTriggerHwService::recognitionCallback, this); if (status == NO_ERROR) { model->mState = Model::STATE_ACTIVE; model->mConfig = *config; } return status; }
173,400
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseCDSect(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int r, rl; int s, sl; int cur, l; int count = 0; /* Check 2.6.0 was NXT(0) not RAW */ if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) { SKIP(9); } else return; ctxt->instate = XML_PARSER_CDATA_SECTION; r = CUR_CHAR(rl); if (!IS_CHAR(r)) { xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL); ctxt->instate = XML_PARSER_CONTENT; return; } NEXTL(rl); s = CUR_CHAR(sl); if (!IS_CHAR(s)) { xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL); ctxt->instate = XML_PARSER_CONTENT; return; } NEXTL(sl); cur = CUR_CHAR(l); buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return; } while (IS_CHAR(cur) && ((r != ']') || (s != ']') || (cur != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); return; } buf = tmp; } COPY_BUF(rl,buf,len,r); r = s; rl = sl; s = cur; sl = l; count++; if (count > 50) { GROW; count = 0; } NEXTL(l); cur = CUR_CHAR(l); } buf[len] = 0; ctxt->instate = XML_PARSER_CONTENT; if (cur != '>') { xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED, "CData section not finished\n%.50s\n", buf); xmlFree(buf); return; } NEXTL(l); /* * OK the buffer is to be consumed as cdata. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, buf, len); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, len); } xmlFree(buf); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseCDSect(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int r, rl; int s, sl; int cur, l; int count = 0; /* Check 2.6.0 was NXT(0) not RAW */ if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) { SKIP(9); } else return; ctxt->instate = XML_PARSER_CDATA_SECTION; r = CUR_CHAR(rl); if (!IS_CHAR(r)) { xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL); ctxt->instate = XML_PARSER_CONTENT; return; } NEXTL(rl); s = CUR_CHAR(sl); if (!IS_CHAR(s)) { xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL); ctxt->instate = XML_PARSER_CONTENT; return; } NEXTL(sl); cur = CUR_CHAR(l); buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return; } while (IS_CHAR(cur) && ((r != ']') || (s != ']') || (cur != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); return; } buf = tmp; } COPY_BUF(rl,buf,len,r); r = s; rl = sl; s = cur; sl = l; count++; if (count > 50) { GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return; } count = 0; } NEXTL(l); cur = CUR_CHAR(l); } buf[len] = 0; ctxt->instate = XML_PARSER_CONTENT; if (cur != '>') { xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED, "CData section not finished\n%.50s\n", buf); xmlFree(buf); return; } NEXTL(l); /* * OK the buffer is to be consumed as cdata. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, buf, len); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, len); } xmlFree(buf); }
171,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Chapters::Edition::ExpandAtomsArray() { if (m_atoms_size > m_atoms_count) return true; // nothing else to do const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Chapters::Edition::ExpandAtomsArray() IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = m_start; const long long stop = m_start + m_size; m_timecodeScale = 1000000; m_duration = -1; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x0AD7B1) { // Timecode Scale m_timecodeScale = UnserializeUInt(pReader, pos, size); if (m_timecodeScale <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0489) { // Segment duration const long status = UnserializeFloat(pReader, pos, size, m_duration); if (status < 0) return status; if (m_duration < 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0D80) { // MuxingApp const long status = UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8); if (status) return status; } else if (id == 0x1741) { // WritingApp const long status = UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8); if (status) return status; } else if (id == 0x3BA9) { // Title const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::GetLast() const { if ((m_clusters == NULL) || (m_clusterCount <= 0)) return &m_eos; const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; } 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 Cluster* Segment::GetLast() const const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; }
174,340
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ }
167,038
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url, const FilePath& virtual_path, const FilePath& platform_path) { FilePath::StringType extension = virtual_path.Extension(); if (!extension.empty()) extension = extension.substr(1); // Strip leading ".". scoped_refptr<webkit_blob::ShareableFileReference> shareable_file = webkit_blob::ShareableFileReference::Get(platform_path); if (shareable_file && !ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id_, platform_path)) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( process_id_, platform_path); shareable_file->AddFinalReleaseCallback( base::Bind(&RevokeFilePermission, process_id_)); } std::string mime_type; net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); BlobData::Item item; item.SetToFilePathRange(platform_path, 0, -1, base::Time()); BlobStorageController* controller = blob_storage_context_->controller(); controller->StartBuildingBlob(blob_url); controller->AppendBlobDataItem(blob_url, item); controller->FinishBuildingBlob(blob_url, mime_type); blob_urls_.insert(blob_url.spec()); } Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files We also need to check the read permission and call GrantReadFile() for sandboxed files for CreateSnapshotFile(). BUG=162114 TEST=manual Review URL: https://codereview.chromium.org/11280231 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url, const FileSystemURL& url, const FilePath& platform_path) { FilePath::StringType extension = url.path().Extension(); if (!extension.empty()) extension = extension.substr(1); // Strip leading ".". scoped_refptr<webkit_blob::ShareableFileReference> shareable_file = webkit_blob::ShareableFileReference::Get(platform_path); if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id_, platform_path)) { // If the underlying file system implementation is returning a new // (likely temporary) snapshot file or the file is for sandboxed // filesystems it's ok to grant permission here. // (Note that we have also already checked if the renderer has the // read permission for this file in OnCreateSnapshotFile.) DCHECK(shareable_file || fileapi::SandboxMountPointProvider::CanHandleType(url.type())); ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( process_id_, platform_path); if (shareable_file) { // This will revoke all permissions for the file when the last ref // of the file is dropped (assuming it's ok). shareable_file->AddFinalReleaseCallback( base::Bind(&RevokeFilePermission, process_id_)); } } std::string mime_type; net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); BlobData::Item item; item.SetToFilePathRange(platform_path, 0, -1, base::Time()); BlobStorageController* controller = blob_storage_context_->controller(); controller->StartBuildingBlob(blob_url); controller->AppendBlobDataItem(blob_url, item); controller->FinishBuildingBlob(blob_url, mime_type); blob_urls_.insert(blob_url.spec()); }
171,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vfsmount *collect_mounts(struct path *path) { struct mount *tree; namespace_lock(); tree = copy_tree(real_mount(path->mnt), path->dentry, CL_COPY_ALL | CL_PRIVATE); namespace_unlock(); if (IS_ERR(tree)) return ERR_CAST(tree); return &tree->mnt; } Commit Message: mnt: Fail collect_mounts when applied to unmounted mounts The only users of collect_mounts are in audit_tree.c In audit_trim_trees and audit_add_tree_rule the path passed into collect_mounts is generated from kern_path passed an audit_tree pathname which is guaranteed to be an absolute path. In those cases collect_mounts is obviously intended to work on mounted paths and if a race results in paths that are unmounted when collect_mounts it is reasonable to fail early. The paths passed into audit_tag_tree don't have the absolute path check. But are used to play with fsnotify and otherwise interact with the audit_trees, so again operating only on mounted paths appears reasonable. Avoid having to worry about what happens when we try and audit unmounted filesystems by restricting collect_mounts to mounts that appear in the mount tree. Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> CWE ID:
struct vfsmount *collect_mounts(struct path *path) { struct mount *tree; namespace_lock(); if (!check_mnt(real_mount(path->mnt))) tree = ERR_PTR(-EINVAL); else tree = copy_tree(real_mount(path->mnt), path->dentry, CL_COPY_ALL | CL_PRIVATE); namespace_unlock(); if (IS_ERR(tree)) return ERR_CAST(tree); return &tree->mnt; }
167,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_rpcsec_auth(struct svc_req *rqstp) { gss_ctx_id_t ctx; krb5_context kctx; OM_uint32 maj_stat, min_stat; gss_name_t name; krb5_principal princ; int ret, success; krb5_data *c1, *c2, *realm; gss_buffer_desc gss_str; kadm5_server_handle_t handle; size_t slen; char *sdots; success = 0; handle = (kadm5_server_handle_t)global_server_handle; if (rqstp->rq_cred.oa_flavor != RPCSEC_GSS) return 0; ctx = rqstp->rq_svccred; maj_stat = gss_inquire_context(&min_stat, ctx, NULL, &name, NULL, NULL, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) { krb5_klog_syslog(LOG_ERR, _("check_rpcsec_auth: failed " "inquire_context, stat=%u"), maj_stat); log_badauth(maj_stat, min_stat, rqstp->rq_xprt, NULL); goto fail_name; } kctx = handle->context; ret = gss_to_krb5_name_1(rqstp, kctx, name, &princ, &gss_str); if (ret == 0) goto fail_name; slen = gss_str.length; trunc_name(&slen, &sdots); /* * Since we accept with GSS_C_NO_NAME, the client can authenticate * against the entire kdb. Therefore, ensure that the service * name is something reasonable. */ if (krb5_princ_size(kctx, princ) != 2) goto fail_princ; c1 = krb5_princ_component(kctx, princ, 0); c2 = krb5_princ_component(kctx, princ, 1); realm = krb5_princ_realm(kctx, princ); if (strncmp(handle->params.realm, realm->data, realm->length) == 0 && strncmp("kadmin", c1->data, c1->length) == 0) { if (strncmp("history", c2->data, c2->length) == 0) goto fail_princ; else success = 1; } fail_princ: if (!success) { krb5_klog_syslog(LOG_ERR, _("bad service principal %.*s%s"), (int) slen, (char *) gss_str.value, sdots); } gss_release_buffer(&min_stat, &gss_str); krb5_free_principal(kctx, princ); fail_name: gss_release_name(&min_stat, &name); return success; } Commit Message: Fix kadmind server validation [CVE-2014-9422] [MITKRB5-SA-2015-001] In kadmind's check_rpcsec_auth(), use data_eq_string() instead of strncmp() to check components of the server principal, so that we don't erroneously match left substrings of "kadmin", "history", or the realm. ticket: 8057 (new) target_version: 1.13.1 tags: pullup CWE ID: CWE-284
check_rpcsec_auth(struct svc_req *rqstp) { gss_ctx_id_t ctx; krb5_context kctx; OM_uint32 maj_stat, min_stat; gss_name_t name; krb5_principal princ; int ret, success; krb5_data *c1, *c2, *realm; gss_buffer_desc gss_str; kadm5_server_handle_t handle; size_t slen; char *sdots; success = 0; handle = (kadm5_server_handle_t)global_server_handle; if (rqstp->rq_cred.oa_flavor != RPCSEC_GSS) return 0; ctx = rqstp->rq_svccred; maj_stat = gss_inquire_context(&min_stat, ctx, NULL, &name, NULL, NULL, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) { krb5_klog_syslog(LOG_ERR, _("check_rpcsec_auth: failed " "inquire_context, stat=%u"), maj_stat); log_badauth(maj_stat, min_stat, rqstp->rq_xprt, NULL); goto fail_name; } kctx = handle->context; ret = gss_to_krb5_name_1(rqstp, kctx, name, &princ, &gss_str); if (ret == 0) goto fail_name; slen = gss_str.length; trunc_name(&slen, &sdots); /* * Since we accept with GSS_C_NO_NAME, the client can authenticate * against the entire kdb. Therefore, ensure that the service * name is something reasonable. */ if (krb5_princ_size(kctx, princ) != 2) goto fail_princ; c1 = krb5_princ_component(kctx, princ, 0); c2 = krb5_princ_component(kctx, princ, 1); realm = krb5_princ_realm(kctx, princ); success = data_eq_string(*realm, handle->params.realm) && data_eq_string(*c1, "kadmin") && !data_eq_string(*c2, "history"); fail_princ: if (!success) { krb5_klog_syslog(LOG_ERR, _("bad service principal %.*s%s"), (int) slen, (char *) gss_str.value, sdots); } gss_release_buffer(&min_stat, &gss_str); krb5_free_principal(kctx, princ); fail_name: gss_release_name(&min_stat, &name); return success; }
166,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: void AppControllerImpl::LaunchHomeUrl(const std::string& suffix, LaunchHomeUrlCallback callback) { if (url_prefix_.empty()) { std::move(callback).Run(false, "No URL prefix."); return; } GURL url(url_prefix_ + suffix); if (!url.is_valid()) { std::move(callback).Run(false, "Invalid URL."); return; } arc::mojom::AppInstance* app_instance = arc::ArcServiceManager::Get() ? ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent) : nullptr; if (!app_instance) { std::move(callback).Run(false, "ARC bridge not available."); return; } app_instance->LaunchIntent(url.spec(), display::kDefaultDisplayId); std::move(callback).Run(true, base::nullopt); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void AppControllerImpl::LaunchHomeUrl(const std::string& suffix, void AppControllerService::LaunchHomeUrl(const std::string& suffix, LaunchHomeUrlCallback callback) { if (url_prefix_.empty()) { std::move(callback).Run(false, "No URL prefix."); return; } GURL url(url_prefix_ + suffix); if (!url.is_valid()) { std::move(callback).Run(false, "Invalid URL."); return; } arc::mojom::AppInstance* app_instance = arc::ArcServiceManager::Get() ? ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent) : nullptr; if (!app_instance) { std::move(callback).Run(false, "ARC bridge not available."); return; } app_instance->LaunchIntent(url.spec(), display::kDefaultDisplayId); std::move(callback).Run(true, base::nullopt); }
172,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Chapters::Atom::GetStopTimecode() const { return m_stop_timecode; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Chapters::Atom::GetStopTimecode() const
174,358
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Segment::ParseCues(long long off, long long& pos, long& len) { if (m_pCues) return 0; // success if (off < 0) return -1; long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = m_start + off; if ((total < 0) || (pos >= total)) return 1; // don't bother parsing cues const long long element_start = pos; const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id != 0x0C53BB6B) // Cues ID return E_FILE_FORMAT_INVALID; pos += len; // consume ID assert((segment_stop < 0) || (pos <= segment_stop)); if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); if (size == 0) // weird, although technically not illegal return 1; // done pos += len; // consume length of size of element assert((segment_stop < 0) || (pos <= segment_stop)); const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (element_stop > total)) return 1; // don't bother parsing anymore len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; const long long element_size = element_stop - element_start; m_pCues = new (std::nothrow) Cues(this, pos, size, element_start, element_size); assert(m_pCues); // TODO 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 Segment::ParseCues(long long off, long long& pos, long& len) { if (m_pCues) return 0; // success if (off < 0) return -1; long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = m_start + off; if ((total < 0) || (pos >= total)) return 1; // don't bother parsing cues const long long element_start = pos; const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadID(m_pReader, idpos, len); if (id != 0x0C53BB6B) // Cues ID return E_FILE_FORMAT_INVALID; pos += len; // consume ID assert((segment_stop < 0) || (pos <= segment_stop)); if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); if (size == 0) // weird, although technically not illegal return 1; // done pos += len; // consume length of size of element assert((segment_stop < 0) || (pos <= segment_stop)); const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (element_stop > total)) return 1; // don't bother parsing anymore len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; const long long element_size = element_stop - element_start; m_pCues = new (std::nothrow) Cues(this, pos, size, element_start, element_size); if (m_pCues == NULL) return -1; return 0; // success }
173,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: modifier_init(png_modifier *pm) { memset(pm, 0, sizeof *pm); store_init(&pm->this); pm->modifications = NULL; pm->state = modifier_start; pm->sbitlow = 1U; pm->ngammas = 0; pm->ngamma_tests = 0; pm->gammas = 0; pm->current_gamma = 0; pm->encodings = 0; pm->nencodings = 0; pm->current_encoding = 0; pm->encoding_counter = 0; pm->encoding_ignored = 0; pm->repeat = 0; pm->test_uses_encoding = 0; pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0; pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0; pm->maxcalcG = 0; pm->limit = 4E-3; pm->log8 = pm->log16 = 0; /* Means 'off' */ pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0; pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0; pm->error_indexed = 0; pm->use_update_info = 0; pm->interlace_type = PNG_INTERLACE_NONE; pm->test_standard = 0; pm->test_size = 0; pm->test_transform = 0; pm->use_input_precision = 0; pm->use_input_precision_sbit = 0; pm->use_input_precision_16to8 = 0; pm->calculations_use_input_precision = 0; pm->assume_16_bit_calculations = 0; pm->test_gamma_threshold = 0; pm->test_gamma_transform = 0; pm->test_gamma_sbit = 0; pm->test_gamma_scale16 = 0; pm->test_gamma_background = 0; pm->test_gamma_alpha_mode = 0; pm->test_gamma_expand16 = 0; pm->test_exhaustive = 0; pm->log = 0; /* Rely on the memset for all the other fields - there are no pointers */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
modifier_init(png_modifier *pm) { memset(pm, 0, sizeof *pm); store_init(&pm->this); pm->modifications = NULL; pm->state = modifier_start; pm->sbitlow = 1U; pm->ngammas = 0; pm->ngamma_tests = 0; pm->gammas = 0; pm->current_gamma = 0; pm->encodings = 0; pm->nencodings = 0; pm->current_encoding = 0; pm->encoding_counter = 0; pm->encoding_ignored = 0; pm->repeat = 0; pm->test_uses_encoding = 0; pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0; pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0; pm->maxcalcG = 0; pm->limit = 4E-3; pm->log8 = pm->log16 = 0; /* Means 'off' */ pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0; pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0; pm->error_indexed = 0; pm->use_update_info = 0; pm->interlace_type = PNG_INTERLACE_NONE; pm->test_standard = 0; pm->test_size = 0; pm->test_transform = 0; # ifdef PNG_WRITE_tRNS_SUPPORTED pm->test_tRNS = 1; # else pm->test_tRNS = 0; # endif pm->use_input_precision = 0; pm->use_input_precision_sbit = 0; pm->use_input_precision_16to8 = 0; pm->calculations_use_input_precision = 0; pm->assume_16_bit_calculations = 0; pm->test_gamma_threshold = 0; pm->test_gamma_transform = 0; pm->test_gamma_sbit = 0; pm->test_gamma_scale16 = 0; pm->test_gamma_background = 0; pm->test_gamma_alpha_mode = 0; pm->test_gamma_expand16 = 0; pm->test_lbg = 1; pm->test_lbg_gamma_threshold = 1; pm->test_lbg_gamma_transform = 1; pm->test_lbg_gamma_sbit = 1; pm->test_lbg_gamma_composition = 1; pm->test_exhaustive = 0; pm->log = 0; /* Rely on the memset for all the other fields - there are no pointers */ }
173,670
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) { int new_mi_size; vp9_set_mb_mi(cm, width, height); new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows); if (cm->mi_alloc_size < new_mi_size) { cm->free_mi(cm); if (cm->alloc_mi(cm, new_mi_size)) goto fail; } if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) { free_seg_map(cm); if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols)) goto fail; } if (cm->above_context_alloc_cols < cm->mi_cols) { vpx_free(cm->above_context); cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc( 2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE, sizeof(*cm->above_context)); if (!cm->above_context) goto fail; vpx_free(cm->above_seg_context); cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc( mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context)); if (!cm->above_seg_context) goto fail; cm->above_context_alloc_cols = cm->mi_cols; } return 0; fail: vp9_free_context_buffers(cm); return 1; } Commit Message: DO NOT MERGE libvpx: Cherry-pick 8b4c315 from upstream Description from upstream: vp9_alloc_context_buffers: clear cm->mi* on failure this fixes a crash in vp9_dec_setup_mi() via vp9_init_context_buffers() should decoding continue and the decoder resyncs on a smaller frame Bug: 30593752 Change-Id: Iafbf1c4114062bf796f51a6b03be71328f7bcc69 (cherry picked from commit 737c8493693243838128788fe9c3abc51f17338e) (cherry picked from commit 3e88ffac8c80b76e15286ef8a7b3bd8fa246c761) CWE ID: CWE-20
int vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) { int new_mi_size; vp9_set_mb_mi(cm, width, height); new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows); if (cm->mi_alloc_size < new_mi_size) { cm->free_mi(cm); if (cm->alloc_mi(cm, new_mi_size)) goto fail; } if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) { free_seg_map(cm); if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols)) goto fail; } if (cm->above_context_alloc_cols < cm->mi_cols) { vpx_free(cm->above_context); cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc( 2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE, sizeof(*cm->above_context)); if (!cm->above_context) goto fail; vpx_free(cm->above_seg_context); cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc( mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context)); if (!cm->above_seg_context) goto fail; cm->above_context_alloc_cols = cm->mi_cols; } return 0; fail: vp9_set_mb_mi(cm, 0, 0); vp9_free_context_buffers(cm); return 1; }
173,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettingsPopupView::WebsiteSettingsPopupView( views::View* anchor_view, gfx::NativeView parent_window, Profile* profile, content::WebContents* web_contents, const GURL& url, const content::SSLStatus& ssl) : BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT), web_contents_(web_contents), header_(nullptr), tabbed_pane_(nullptr), permissions_tab_(nullptr), site_data_content_(nullptr), cookie_dialog_link_(nullptr), permissions_content_(nullptr), connection_tab_(nullptr), identity_info_content_(nullptr), certificate_dialog_link_(nullptr), reset_decisions_button_(nullptr), help_center_content_(nullptr), cert_id_(0), help_center_link_(nullptr), connection_info_content_(nullptr), weak_factory_(this) { set_parent_window(parent_window); set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0, kLocationIconVerticalMargin, 0)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int content_column = 0; views::ColumnSet* column_set = layout->AddColumnSet(content_column); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); header_ = new PopupHeaderView(this); layout->StartRow(1, content_column); layout->AddView(header_); layout->AddPaddingRow(1, kHeaderMarginBottom); tabbed_pane_ = new views::TabbedPane(); layout->StartRow(1, content_column); layout->AddView(tabbed_pane_); permissions_tab_ = CreatePermissionsTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_PERMISSIONS, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS), permissions_tab_); connection_tab_ = CreateConnectionTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_CONNECTION, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION), connection_tab_); DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS); tabbed_pane_->set_listener(this); set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft, kPopupMarginBottom, kPopupMarginRight)); views::BubbleDelegateView::CreateBubble(this); presenter_.reset(new WebsiteSettings( this, profile, TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), url, ssl, content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettingsPopupView::WebsiteSettingsPopupView( views::View* anchor_view, gfx::NativeView parent_window, Profile* profile, content::WebContents* web_contents, const GURL& url, const content::SSLStatus& ssl) : content::WebContentsObserver(web_contents), BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT), web_contents_(web_contents), header_(nullptr), tabbed_pane_(nullptr), permissions_tab_(nullptr), site_data_content_(nullptr), cookie_dialog_link_(nullptr), permissions_content_(nullptr), connection_tab_(nullptr), identity_info_content_(nullptr), certificate_dialog_link_(nullptr), reset_decisions_button_(nullptr), help_center_content_(nullptr), cert_id_(0), help_center_link_(nullptr), connection_info_content_(nullptr), weak_factory_(this) { set_parent_window(parent_window); set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0, kLocationIconVerticalMargin, 0)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int content_column = 0; views::ColumnSet* column_set = layout->AddColumnSet(content_column); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); header_ = new PopupHeaderView(this); layout->StartRow(1, content_column); layout->AddView(header_); layout->AddPaddingRow(1, kHeaderMarginBottom); tabbed_pane_ = new views::TabbedPane(); layout->StartRow(1, content_column); layout->AddView(tabbed_pane_); permissions_tab_ = CreatePermissionsTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_PERMISSIONS, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS), permissions_tab_); connection_tab_ = CreateConnectionTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_CONNECTION, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION), connection_tab_); DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS); tabbed_pane_->set_listener(this); set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft, kPopupMarginBottom, kPopupMarginRight)); views::BubbleDelegateView::CreateBubble(this); presenter_.reset(new WebsiteSettings( this, profile, TabSpecificContentSettings::FromWebContents(web_contents), web_contents, url, ssl, content::CertStore::GetInstance())); } void WebsiteSettingsPopupView::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents_->GetMainFrame()) { GetWidget()->Close(); } }
171,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) { Close(); return ERR_ADDRESS_INVALID; } rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len)); if (rv < 0) { int result = MapSystemError(errno); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) { Close(); return ERR_ADDRESS_INVALID; } rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len)); if (rv < 0) { int result = MapSystemError(errno); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; }
171,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < ETH_MAX_L2_HDR_LEN) { l2_hdr->iov_len = 0; return false; } else { l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base); } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } Commit Message: CWE ID: CWE-20
static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < sizeof(struct eth_header)) { l2_hdr->iov_len = 0; return false; } l2_hdr->iov_len = sizeof(struct eth_header); switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) { case ETH_P_VLAN: l2_hdr->iov_len += sizeof(struct vlan_header); break; case ETH_P_DVLAN: l2_hdr->iov_len += 2 * sizeof(struct vlan_header); break; } if (bytes_read < l2_hdr->iov_len) { l2_hdr->iov_len = 0; return false; } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; }
165,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) { int i; int j; int thresh; jpc_fix_t val; jpc_fix_t mag; bool warn; uint_fast32_t mask; if (roishift == 0 && bgshift == 0) { return; } thresh = 1 << roishift; warn = false; for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { val = jas_matrix_get(x, i, j); mag = JAS_ABS(val); if (mag >= thresh) { /* We are dealing with ROI data. */ mag >>= roishift; val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } else { /* We are dealing with non-ROI (i.e., background) data. */ mag <<= bgshift; mask = (1 << numbps) - 1; /* Perform a basic sanity check on the sample value. */ /* Some implementations write garbage in the unused most-significant bit planes introduced by ROI shifting. Here we ensure that any such bits are masked off. */ if (mag & (~mask)) { if (!warn) { jas_eprintf("warning: possibly corrupt code stream\n"); warn = true; } mag &= mask; } val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } } } } Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST. Modified the jpc_tsfb_synthesize function so that it will be a noop for an empty sequence (in order to avoid dereferencing a null pointer). CWE ID: CWE-476
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) { int i; int j; int thresh; jpc_fix_t val; jpc_fix_t mag; bool warn; uint_fast32_t mask; if (roishift < 0) { /* We could instead return an error here. */ /* I do not think it matters much. */ jas_eprintf("warning: forcing negative ROI shift to zero " "(bitstream is probably corrupt)\n"); roishift = 0; } if (roishift == 0 && bgshift == 0) { return; } thresh = 1 << roishift; warn = false; for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { val = jas_matrix_get(x, i, j); mag = JAS_ABS(val); if (mag >= thresh) { /* We are dealing with ROI data. */ mag >>= roishift; val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } else { /* We are dealing with non-ROI (i.e., background) data. */ mag <<= bgshift; mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1; /* Perform a basic sanity check on the sample value. */ /* Some implementations write garbage in the unused most-significant bit planes introduced by ROI shifting. Here we ensure that any such bits are masked off. */ if (mag & (~mask)) { if (!warn) { jas_eprintf("warning: possibly corrupt code stream\n"); warn = true; } mag &= mask; } val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } } } }
168,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context) { IncrementData *data = g_new0 (IncrementData, 1); data->x = x; data->context = context; g_idle_add ((GSourceFunc)do_async_increment, data); } Commit Message: CWE ID: CWE-264
my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context)
165,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) == ustr_host.length()) diacritic_remover_.get()->transliterate(ustr_host); extra_confusable_mapper_.get()->transliterate(ustr_host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr_skeleton; uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton, &status); if (U_FAILURE(status)) return false; std::string skeleton; return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton)); } Commit Message: Map U+04CF to lowercase L as well. U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered in some fonts. If a host name contains it, calculate the confusability skeleton twice, once with the default mapping to 'i' (lowercase I) and the 2nd time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L) also gets it treated as similar to digit 1 because the confusability skeleton of digit 1 is 'l'. Bug: 817247 Test: components_unittests --gtest_filter=*IDN* Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c Reviewed-on: https://chromium-review.googlesource.com/974165 Commit-Queue: Jungshik Shin <jshin@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Reviewed-by: Eric Lawrence <elawrence@chromium.org> Cr-Commit-Position: refs/heads/master@{#551263} CWE ID:
bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(host, 0, USET_SPAN_CONTAINED) == host.length()) diacritic_remover_.get()->transliterate(host); extra_confusable_mapper_.get()->transliterate(host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString skeleton; // Map U+04CF (ӏ) to lowercase L in addition to what uspoof_getSkeleton does // (mapping it to lowercase I). int32_t u04cf_pos; if ((u04cf_pos = host.indexOf(0x4CF)) != -1) { icu::UnicodeString host_alt(host); size_t length = host_alt.length(); char16_t* buffer = host_alt.getBuffer(-1); for (char16_t* uc = buffer + u04cf_pos ; uc < buffer + length; ++uc) { if (*uc == 0x4CF) *uc = 0x6C; // Lowercase L } host_alt.releaseBuffer(length); uspoof_getSkeletonUnicodeString(checker_, 0, host_alt, skeleton, &status); if (U_SUCCESS(status) && LookupMatchInTopDomains(skeleton)) return true; } uspoof_getSkeletonUnicodeString(checker_, 0, host, skeleton, &status); return U_SUCCESS(status) && LookupMatchInTopDomains(skeleton); }
173,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr, struct bgp_nlri *packet) { u_char *pnt; u_char *lim; struct prefix p; int psize; int prefixlen; u_int16_t type; struct rd_as rd_as; struct rd_ip rd_ip; struct prefix_rd prd; u_char *tagpnt; /* Check peer status. */ if (peer->status != Established) return 0; /* Make prefix_rd */ prd.family = AF_UNSPEC; prd.prefixlen = 64; pnt = packet->nlri; lim = pnt + packet->length; for (; pnt < lim; pnt += psize) { /* Clear prefix structure. */ /* Fetch prefix length. */ prefixlen = *pnt++; p.family = AF_INET; psize = PSIZE (prefixlen); if (prefixlen < 88) { zlog_err ("prefix length is less than 88: %d", prefixlen); return -1; } /* Copyr label to prefix. */ tagpnt = pnt;; /* Copy routing distinguisher to rd. */ memcpy (&prd.val, pnt + 3, 8); else if (type == RD_TYPE_IP) zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip), rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen); #endif /* 0 */ if (pnt + psize > lim) return -1; if (attr) bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN, ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0); else return -1; } p.prefixlen = prefixlen - 88; memcpy (&p.u.prefix, pnt + 11, psize - 11); #if 0 if (type == RD_TYPE_AS) } Commit Message: CWE ID: CWE-119
bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr, struct bgp_nlri *packet) { u_char *pnt; u_char *lim; struct prefix p; int psize; int prefixlen; u_int16_t type; struct rd_as rd_as; struct rd_ip rd_ip; struct prefix_rd prd; u_char *tagpnt; /* Check peer status. */ if (peer->status != Established) return 0; /* Make prefix_rd */ prd.family = AF_UNSPEC; prd.prefixlen = 64; pnt = packet->nlri; lim = pnt + packet->length; #define VPN_PREFIXLEN_MIN_BYTES (3 + 8) /* label + RD */ for (; pnt < lim; pnt += psize) { /* Clear prefix structure. */ /* Fetch prefix length. */ prefixlen = *pnt++; p.family = afi2family (packet->afi); psize = PSIZE (prefixlen); /* sanity check against packet data */ if (prefixlen < VPN_PREFIXLEN_MIN_BYTES*8 || (pnt + psize) > lim) { zlog_err ("prefix length (%d) is less than 88" " or larger than received (%u)", prefixlen, (uint)(lim-pnt)); return -1; } /* sanity check against storage for the IP address portion */ if ((psize - VPN_PREFIXLEN_MIN_BYTES) > (ssize_t) sizeof(p.u)) { zlog_err ("prefix length (%d) exceeds prefix storage (%zu)", prefixlen - VPN_PREFIXLEN_MIN_BYTES*8, sizeof(p.u)); return -1; } /* Sanity check against max bitlen of the address family */ if ((psize - VPN_PREFIXLEN_MIN_BYTES) > prefix_blen (&p)) { zlog_err ("prefix length (%d) exceeds family (%u) max byte length (%u)", prefixlen - VPN_PREFIXLEN_MIN_BYTES*8, p.family, prefix_blen (&p)); return -1; } /* Copyr label to prefix. */ tagpnt = pnt; /* Copy routing distinguisher to rd. */ memcpy (&prd.val, pnt + 3, 8); else if (type == RD_TYPE_IP) zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip), rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen); #endif /* 0 */ if (pnt + psize > lim) return -1; if (attr) bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN, ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0); else return -1; } p.prefixlen = prefixlen - VPN_PREFIXLEN_MIN_BYTES*8; memcpy (&p.u.prefix, pnt + VPN_PREFIXLEN_MIN_BYTES, psize - VPN_PREFIXLEN_MIN_BYTES); #if 0 if (type == RD_TYPE_AS) }
165,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error) { guint32 val; GArray *array; array = g_array_new (FALSE, TRUE, sizeof (guint32)); while (reqlen > 0) { val = 42; g_array_append_val (array, val); val = 26; g_array_append_val (array, val); reqlen--; } val = 2; g_array_append_val (array, val); *ret = array; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error)
165,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void serial_update_parameters(SerialState *s) { int speed, parity, data_bits, stop_bits, frame_size; QEMUSerialSetParams ssp; if (s->divider == 0) return; /* Start bit. */ frame_size = 1; /* Parity bit. */ frame_size++; if (s->lcr & 0x10) parity = 'E'; else parity = 'O'; } else { parity = 'N'; } Commit Message: CWE ID: CWE-369
static void serial_update_parameters(SerialState *s) { int speed, parity, data_bits, stop_bits, frame_size; QEMUSerialSetParams ssp; if (s->divider == 0 || s->divider > s->baudbase) { return; } /* Start bit. */ frame_size = 1; /* Parity bit. */ frame_size++; if (s->lcr & 0x10) parity = 'E'; else parity = 'O'; } else { parity = 'N'; }
164,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: static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { memmove(s+j, s+qs, blen - qs); j += blen - qs; } buffer_string_set_length(b, j); return qs; } Commit Message: [core] fix abort in http-parseopts (fixes #2945) fix abort in server.http-parseopts with url-path-2f-decode enabled (thx stze) x-ref: "Security - SIGABRT during GET request handling with url-path-2f-decode enabled" https://redmine.lighttpd.net/issues/2945 CWE ID: CWE-190
static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { const int qslen = blen - qs; memmove(s+j, s+qs, (size_t)qslen); qs = j; j += qslen; } buffer_string_set_length(b, j); return qs; }
169,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UninstallExtension(ExtensionService* service, const std::string& id) { if (service && service->GetInstalledExtension(id)) { service->UninstallExtension(id, extensions::UNINSTALL_REASON_SYNC, base::Bind(&base::DoNothing), NULL); } } 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:
void UninstallExtension(ExtensionService* service, const std::string& id) { if (service) { ExtensionService::UninstallExtensionHelper( service, id, extensions::UNINSTALL_REASON_SYNC); } }
171,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: static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char *pt; unsigned char l, lg, n = 0; int fac_national_digis_received = 0; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: if (*p == FAC_NATIONAL_RAND) facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF); p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_NATIONAL_DEST_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN); facilities->source_ndigis = 1; } } else if (*p == FAC_NATIONAL_SRC_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN); facilities->dest_ndigis = 1; } } else if (*p == FAC_NATIONAL_FAIL_CALL) { memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN); } else if (*p == FAC_NATIONAL_FAIL_ADD) { memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN); } else if (*p == FAC_NATIONAL_DIGIS) { fac_national_digis_received = 1; facilities->source_ndigis = 0; facilities->dest_ndigis = 0; for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) { if (pt[6] & AX25_HBIT) memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN); else memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN); } } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; } Commit Message: ROSE: prevent heap corruption with bad facilities When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for a remote host to provide more digipeaters than expected, resulting in heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and abort facilities parsing on failure. Additionally, when parsing the FAC_CCITT_DEST_NSAP and FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length of less than 10, resulting in an underflow in a memcpy size, causing a kernel panic due to massive heap corruption. A length of greater than 20 results in a stack overflow of the callsign array. Abort facilities parsing on these invalid length values. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Cc: stable@kernel.org Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char *pt; unsigned char l, lg, n = 0; int fac_national_digis_received = 0; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: if (*p == FAC_NATIONAL_RAND) facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF); p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_NATIONAL_DEST_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN); facilities->source_ndigis = 1; } } else if (*p == FAC_NATIONAL_SRC_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN); facilities->dest_ndigis = 1; } } else if (*p == FAC_NATIONAL_FAIL_CALL) { memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN); } else if (*p == FAC_NATIONAL_FAIL_ADD) { memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN); } else if (*p == FAC_NATIONAL_DIGIS) { fac_national_digis_received = 1; facilities->source_ndigis = 0; facilities->dest_ndigis = 0; for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) { if (pt[6] & AX25_HBIT) { if (facilities->dest_ndigis >= ROSE_MAX_DIGIS) return -1; memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN); } else { if (facilities->source_ndigis >= ROSE_MAX_DIGIS) return -1; memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN); } } } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
165,673
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HTMLFormControlElement::updateVisibleValidationMessage() { Page* page = document().page(); if (!page) return; String message; if (layoutObject() && willValidate()) message = validationMessage().stripWhiteSpace(); m_hasValidationMessage = true; ValidationMessageClient* client = &page->validationMessageClient(); TextDirection messageDir = LTR; TextDirection subMessageDir = LTR; String subMessage = validationSubMessage().stripWhiteSpace(); if (message.isEmpty()) client->hideValidationMessage(*this); else findCustomValidationMessageTextDirection(message, messageDir, subMessage, subMessageDir); client->showValidationMessage(*this, message, messageDir, subMessage, subMessageDir); } Commit Message: Form validation: Do not show validation bubble if the page is invisible. BUG=673163 Review-Url: https://codereview.chromium.org/2572813003 Cr-Commit-Position: refs/heads/master@{#438476} CWE ID: CWE-1021
void HTMLFormControlElement::updateVisibleValidationMessage() { Page* page = document().page(); if (!page || !page->isPageVisible()) return; String message; if (layoutObject() && willValidate()) message = validationMessage().stripWhiteSpace(); m_hasValidationMessage = true; ValidationMessageClient* client = &page->validationMessageClient(); TextDirection messageDir = LTR; TextDirection subMessageDir = LTR; String subMessage = validationSubMessage().stripWhiteSpace(); if (message.isEmpty()) client->hideValidationMessage(*this); else findCustomValidationMessageTextDirection(message, messageDir, subMessage, subMessageDir); client->showValidationMessage(*this, message, messageDir, subMessage, subMessageDir); }
172,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters* Segment::GetChapters() const { return m_pChapters; } 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 Chapters* Segment::GetChapters() const
174,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: CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info) { AliasInfo *alias; unsigned i, num_key_aliases; struct xkb_key_alias *key_aliases; /* * Do some sanity checking on the aliases. We can't do it before * because keys and their aliases may be added out-of-order. */ num_key_aliases = 0; darray_foreach(alias, info->aliases) { /* Check that ->real is a key. */ if (!XkbKeyByName(keymap, alias->real, false)) { log_vrb(info->ctx, 5, "Attempt to alias %s to non-existent key %s; Ignored\n", KeyNameText(info->ctx, alias->alias), KeyNameText(info->ctx, alias->real)); alias->real = XKB_ATOM_NONE; continue; } /* Check that ->alias is not a key. */ if (XkbKeyByName(keymap, alias->alias, false)) { log_vrb(info->ctx, 5, "Attempt to create alias with the name of a real key; " "Alias \"%s = %s\" ignored\n", KeyNameText(info->ctx, alias->alias), KeyNameText(info->ctx, alias->real)); alias->real = XKB_ATOM_NONE; continue; } num_key_aliases++; } /* Copy key aliases. */ key_aliases = NULL; if (num_key_aliases > 0) { key_aliases = calloc(num_key_aliases, sizeof(*key_aliases)); if (!key_aliases) return false; } i = 0; darray_foreach(alias, info->aliases) { if (alias->real != XKB_ATOM_NONE) { key_aliases[i].alias = alias->alias; key_aliases[i].real = alias->real; i++; } } keymap->num_key_aliases = num_key_aliases; keymap->key_aliases = key_aliases; return true; } Commit Message: keycodes: don't try to copy zero key aliases Move the aliases copy to within the (num_key_aliases > 0) block. Passing info->aliases into this fuction with invalid aliases will cause log messages but num_key_aliases stays on 0. The key_aliases array is never allocated and remains NULL. We then loop through the aliases, causing a null-pointer dereference. Signed-off-by: Peter Hutterer <peter.hutterer@who-t.net> CWE ID: CWE-476
CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info) { AliasInfo *alias; unsigned i, num_key_aliases; struct xkb_key_alias *key_aliases; /* * Do some sanity checking on the aliases. We can't do it before * because keys and their aliases may be added out-of-order. */ num_key_aliases = 0; darray_foreach(alias, info->aliases) { /* Check that ->real is a key. */ if (!XkbKeyByName(keymap, alias->real, false)) { log_vrb(info->ctx, 5, "Attempt to alias %s to non-existent key %s; Ignored\n", KeyNameText(info->ctx, alias->alias), KeyNameText(info->ctx, alias->real)); alias->real = XKB_ATOM_NONE; continue; } /* Check that ->alias is not a key. */ if (XkbKeyByName(keymap, alias->alias, false)) { log_vrb(info->ctx, 5, "Attempt to create alias with the name of a real key; " "Alias \"%s = %s\" ignored\n", KeyNameText(info->ctx, alias->alias), KeyNameText(info->ctx, alias->real)); alias->real = XKB_ATOM_NONE; continue; } num_key_aliases++; } /* Copy key aliases. */ key_aliases = NULL; if (num_key_aliases > 0) { key_aliases = calloc(num_key_aliases, sizeof(*key_aliases)); if (!key_aliases) return false; i = 0; darray_foreach(alias, info->aliases) { if (alias->real != XKB_ATOM_NONE) { key_aliases[i].alias = alias->alias; key_aliases[i].real = alias->real; i++; } } } keymap->num_key_aliases = num_key_aliases; keymap->key_aliases = key_aliases; return true; }
169,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: pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES) || (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) { return -1; } req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); } Commit Message: CWE ID: CWE-125
pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); }
164,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; DOMArrayBuffer* result = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); if (finished_loading_) { array_buffer_result_ = result; AdjustReportedMemoryUsageToV8( -1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); } return result; } Commit Message: FileReader: Make a copy of the ArrayBuffer when returning partial results. This is to avoid accidentally ending up with multiple references to the same underlying ArrayBuffer. The extra performance overhead of this is minimal as usage of partial results is very rare anyway (as can be seen on https://www.chromestatus.com/metrics/feature/timeline/popularity/2158). Bug: 936448 Change-Id: Icd1081adc1c889829fe7fa4af9cf4440097e8854 Reviewed-on: https://chromium-review.googlesource.com/c/1492873 Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Reviewed-by: Adam Klein <adamk@chromium.org> Cr-Commit-Position: refs/heads/master@{#636251} CWE ID: CWE-416
DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; if (!finished_loading_) { return DOMArrayBuffer::Create( ArrayBuffer::Create(raw_data_->Data(), raw_data_->ByteLength())); } array_buffer_result_ = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); AdjustReportedMemoryUsageToV8(-1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); return array_buffer_result_; }
173,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: delete_principal_2_svc(dprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->princ, NULL)) { ret.code = KADM5_AUTH_DELETE; log_unauth("kadm5_delete_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_delete_principal((void *)handle, arg->princ); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
delete_principal_2_svc(dprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->princ, NULL)) { ret.code = KADM5_AUTH_DELETE; log_unauth("kadm5_delete_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_delete_principal((void *)handle, arg->princ); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!ext4_handle_valid(handle)) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; } Commit Message: ext4: make orphan functions be no-op in no-journal mode Instead of checking whether the handle is valid, we check if journal is enabled. This avoids taking the s_orphan_lock mutex in all cases when there is no journal in use, including the error paths where ext4_orphan_del() is called with a handle set to NULL. Signed-off-by: Anatol Pomozov <anatol.pomozov@gmail.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID: CWE-20
int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!EXT4_SB(sb)->s_journal) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; }
166,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } Commit Message: Moved EOF check. CWE ID: CWE-20
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
170,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::GetNext( const BlockEntry* pCurr, const BlockEntry*& pNext) const { assert(pCurr); assert(m_entries); assert(m_entries_count > 0); size_t idx = pCurr->GetIndex(); assert(idx < size_t(m_entries_count)); assert(m_entries[idx] == pCurr); ++idx; if (idx >= size_t(m_entries_count)) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pNext = NULL; return status; } if (status > 0) { pNext = NULL; return 0; } assert(m_entries); assert(m_entries_count > 0); assert(idx < size_t(m_entries_count)); } pNext = m_entries[idx]; assert(pNext); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetNext( size_t idx = pCurr->GetIndex(); assert(idx < size_t(m_entries_count)); assert(m_entries[idx] == pCurr); ++idx; if (idx >= size_t(m_entries_count)) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) { // error pNext = NULL; return status; } if (status > 0) { pNext = NULL; return 0; } assert(m_entries); assert(m_entries_count > 0); assert(idx < size_t(m_entries_count)); } pNext = m_entries[idx]; assert(pNext); return 0; }
174,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OTRBrowserContextImpl::OTRBrowserContextImpl( BrowserContextImpl* original, BrowserContextIODataImpl* original_io_data) : BrowserContext(new OTRBrowserContextIODataImpl(original_io_data)), original_context_(original), weak_ptr_factory_(this) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); } Commit Message: CWE ID: CWE-20
OTRBrowserContextImpl::OTRBrowserContextImpl( BrowserContextImpl* original, BrowserContextIODataImpl* original_io_data) : BrowserContext(new OTRBrowserContextIODataImpl(original_io_data)), original_context_(original) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); }
165,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: init_device (u2fh_devs * devs, struct u2fdevice *dev) { unsigned char resp[1024]; unsigned char nonce[8]; if (obtain_nonce(nonce) != 0) { return U2FH_TRANSPORT_ERROR; } size_t resplen = sizeof (resp); dev->cid = CID_BROADCAST; if (u2fh_sendrecv (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, &resplen) == U2FH_OK) { U2FHID_INIT_RESP initresp; if (resplen > sizeof (initresp)) { return U2FH_MEMORY_ERROR; } memcpy (&initresp, resp, resplen); dev->cid = initresp.cid; dev->versionInterface = initresp.versionInterface; dev->versionMajor = initresp.versionMajor; dev->versionMinor = initresp.versionMinor; dev->capFlags = initresp.capFlags; } else { return U2FH_TRANSPORT_ERROR; } return U2FH_OK; } Commit Message: fix filling out of initresp CWE ID: CWE-119
init_device (u2fh_devs * devs, struct u2fdevice *dev) { unsigned char resp[1024]; unsigned char nonce[8]; if (obtain_nonce(nonce) != 0) { return U2FH_TRANSPORT_ERROR; } size_t resplen = sizeof (resp); dev->cid = CID_BROADCAST; if (u2fh_sendrecv (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, &resplen) == U2FH_OK) { int offs = sizeof (nonce); /* the response has to be atleast 17 bytes, if it's more we discard that */ if (resplen < 17) { return U2FH_SIZE_ERROR; } /* incoming and outgoing nonce has to match */ if (memcmp (nonce, resp, sizeof (nonce)) != 0) { return U2FH_TRANSPORT_ERROR; } dev->cid = resp[offs] << 24 | resp[offs + 1] << 16 | resp[offs + 2] << 8 | resp[offs + 3]; offs += 4; dev->versionInterface = resp[offs++]; dev->versionMajor = resp[offs++]; dev->versionMinor = resp[offs++]; dev->versionBuild = resp[offs++]; dev->capFlags = resp[offs++]; } else { return U2FH_TRANSPORT_ERROR; } return U2FH_OK; }
169,721
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err = -EIO; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) goto out; symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out: up_read(&iinfo->i_data_sem); SetPageError(page); kunmap(page); unlock_page(page); return err; } Commit Message: udf: Verify symlink size before loading it UDF specification allows arbitrarily large symlinks. However we support only symlinks at most one block large. Check the length of the symlink so that we don't access memory beyond end of the symlink block. CC: stable@vger.kernel.org Reported-by: Carl Henrik Lunde <chlunde@gmail.com> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-119
static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; }
169,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sock_send_all(int sock_fd, const uint8_t* buf, int len) { int s = len; int ret; while(s) { do ret = send(sock_fd, buf, s, 0); while(ret < 0 && errno == EINTR); if(ret <= 0) { BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret); return -1; } buf += ret; s -= ret; } return len; } 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
int sock_send_all(int sock_fd, const uint8_t* buf, int len) { int s = len; int ret; while(s) { do ret = TEMP_FAILURE_RETRY(send(sock_fd, buf, s, 0)); while(ret < 0 && errno == EINTR); if(ret <= 0) { BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret); return -1; } buf += ret; s -= ret; } return len; }
173,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ShellMainDelegate::ShellMainDelegate() { } Commit Message: Fix content_shell with network service enabled not loading pages. This regressed in my earlier cl r528763. This is a reland of r547221. Bug: 833612 Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b Reviewed-on: https://chromium-review.googlesource.com/1064702 Reviewed-by: Jay Civelli <jcivelli@chromium.org> Commit-Queue: John Abd-El-Malek <jam@chromium.org> Cr-Commit-Position: refs/heads/master@{#560011} CWE ID: CWE-264
ShellMainDelegate::ShellMainDelegate() {
172,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster::GetTime() const { const long long tc = GetTimeCode(); if (tc < 0) return tc; const SegmentInfo* const pInfo = m_pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long t = m_timecode * scale; return t; } 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 Cluster::GetTime() const
174,362
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DataReductionProxySettings::InitPrefMembers() { DCHECK(thread_checker_.CalledOnValidThread()); spdy_proxy_auth_enabled_.Init( prefs::kDataSaverEnabled, GetOriginalProfilePrefs(), base::Bind(&DataReductionProxySettings::OnProxyEnabledPrefChange, base::Unretained(this))); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void DataReductionProxySettings::InitPrefMembers() {
172,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DownloadController::StartAndroidDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = wc_getter.Run(); if (!web_contents) { LOG(ERROR) << "Download failed on URL:" << info.url.spec(); return; } AcquireFileAccessPermission( web_contents, base::Bind(&DownloadController::StartAndroidDownloadInternal, base::Unretained(this), wc_getter, must_download, info)); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void DownloadController::StartAndroidDownload(
171,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */ { va_list va; char *message = NULL; va_start(va, format); zend_vspprintf(&message, 0, format, va); if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) { zend_throw_error(exception_ce, message); } else { zend_error(E_ERROR, "%s", message); } efree(message); va_end(va); } /* }}} */ Commit Message: Use format string CWE ID: CWE-134
static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */ { va_list va; char *message = NULL; va_start(va, format); zend_vspprintf(&message, 0, format, va); if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) { zend_throw_error(exception_ce, "%s", message); } else { zend_error(E_ERROR, "%s", message); } efree(message); va_end(va); } /* }}} */
167,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: zsetdevice(i_ctx_t *i_ctx_p) { gx_device *dev = gs_currentdevice(igs); os_ptr op = osp; int code = 0; check_write_type(*op, t_device); if (dev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != dev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; } Commit Message: CWE ID:
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *odev = NULL, *dev = gs_currentdevice(igs); os_ptr op = osp; int code = dev_proc(dev, dev_spec_op)(dev, gxdso_current_output_device, (void *)&odev, 0); if (code < 0) return code; check_write_type(*op, t_device); if (odev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != odev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
164,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IsSystemModal(aura::Window* window) { return window->transient_parent() && window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; } Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs. BUG=130420 TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient Review URL: https://chromiumcodereview.appspot.com/10514012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool IsSystemModal(aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; }
170,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CrosLibrary::TestApi::SetSystemLibrary( SystemLibrary* library, bool own) { library_->system_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetSystemLibrary(
170,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); }
167,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sig_server_setup_fill_chatnet(IRC_SERVER_CONNECT_REC *conn, IRC_CHATNET_REC *ircnet) { if (!IS_IRC_SERVER_CONNECT(conn)) return; g_return_if_fail(IS_IRCNET(ircnet)); if (ircnet->alternate_nick != NULL) { g_free_and_null(conn->alternate_nick); conn->alternate_nick = g_strdup(ircnet->alternate_nick); } if (ircnet->usermode != NULL) { g_free_and_null(conn->usermode); conn->usermode = g_strdup(ircnet->usermode); } if (ircnet->max_kicks > 0) conn->max_kicks = ircnet->max_kicks; if (ircnet->max_msgs > 0) conn->max_msgs = ircnet->max_msgs; if (ircnet->max_modes > 0) conn->max_modes = ircnet->max_modes; if (ircnet->max_whois > 0) conn->max_whois = ircnet->max_whois; if (ircnet->max_cmds_at_once > 0) conn->max_cmds_at_once = ircnet->max_cmds_at_once; if (ircnet->cmd_queue_speed > 0) conn->cmd_queue_speed = ircnet->cmd_queue_speed; if (ircnet->max_query_chans > 0) conn->max_query_chans = ircnet->max_query_chans; /* Validate the SASL parameters filled by sig_chatnet_read() or cmd_network_add */ conn->sasl_mechanism = SASL_MECHANISM_NONE; conn->sasl_username = NULL; conn->sasl_password = NULL; if (ircnet->sasl_mechanism != NULL) { if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "plain")) { /* The PLAIN method needs both the username and the password */ conn->sasl_mechanism = SASL_MECHANISM_PLAIN; if (ircnet->sasl_username != NULL && *ircnet->sasl_username && ircnet->sasl_password != NULL && *ircnet->sasl_password) { conn->sasl_username = ircnet->sasl_username; conn->sasl_password = ircnet->sasl_password; } else g_warning("The fields sasl_username and sasl_password are either missing or empty"); } else if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "external")) { conn->sasl_mechanism = SASL_MECHANISM_EXTERNAL; } else g_warning("Unsupported SASL mechanism \"%s\" selected", ircnet->sasl_mechanism); } } Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect copy sasl username and password values CWE ID: CWE-416
static void sig_server_setup_fill_chatnet(IRC_SERVER_CONNECT_REC *conn, IRC_CHATNET_REC *ircnet) { if (!IS_IRC_SERVER_CONNECT(conn)) return; g_return_if_fail(IS_IRCNET(ircnet)); if (ircnet->alternate_nick != NULL) { g_free_and_null(conn->alternate_nick); conn->alternate_nick = g_strdup(ircnet->alternate_nick); } if (ircnet->usermode != NULL) { g_free_and_null(conn->usermode); conn->usermode = g_strdup(ircnet->usermode); } if (ircnet->max_kicks > 0) conn->max_kicks = ircnet->max_kicks; if (ircnet->max_msgs > 0) conn->max_msgs = ircnet->max_msgs; if (ircnet->max_modes > 0) conn->max_modes = ircnet->max_modes; if (ircnet->max_whois > 0) conn->max_whois = ircnet->max_whois; if (ircnet->max_cmds_at_once > 0) conn->max_cmds_at_once = ircnet->max_cmds_at_once; if (ircnet->cmd_queue_speed > 0) conn->cmd_queue_speed = ircnet->cmd_queue_speed; if (ircnet->max_query_chans > 0) conn->max_query_chans = ircnet->max_query_chans; /* Validate the SASL parameters filled by sig_chatnet_read() or cmd_network_add */ conn->sasl_mechanism = SASL_MECHANISM_NONE; conn->sasl_username = NULL; conn->sasl_password = NULL; if (ircnet->sasl_mechanism != NULL) { if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "plain")) { /* The PLAIN method needs both the username and the password */ conn->sasl_mechanism = SASL_MECHANISM_PLAIN; if (ircnet->sasl_username != NULL && *ircnet->sasl_username && ircnet->sasl_password != NULL && *ircnet->sasl_password) { conn->sasl_username = g_strdup(ircnet->sasl_username); conn->sasl_password = g_strdup(ircnet->sasl_password); } else g_warning("The fields sasl_username and sasl_password are either missing or empty"); } else if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "external")) { conn->sasl_mechanism = SASL_MECHANISM_EXTERNAL; } else g_warning("Unsupported SASL mechanism \"%s\" selected", ircnet->sasl_mechanism); } }
169,644
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length, l2info.caplen); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; }
167,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 svc_rdma_xdr_encode_write_list(struct rpcrdma_msg *rmsgp, int chunks) { struct rpcrdma_write_array *ary; /* no read-list */ rmsgp->rm_body.rm_chunks[0] = xdr_zero; /* write-array discrim */ ary = (struct rpcrdma_write_array *) &rmsgp->rm_body.rm_chunks[1]; ary->wc_discrim = xdr_one; ary->wc_nchunks = cpu_to_be32(chunks); /* write-list terminator */ ary->wc_array[chunks].wc_target.rs_handle = xdr_zero; /* reply-array discriminator */ ary->wc_array[chunks].wc_target.rs_length = xdr_zero; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
void svc_rdma_xdr_encode_write_list(struct rpcrdma_msg *rmsgp, int chunks)
168,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tight_fill_palette(VncState *vs, int x, int y, size_t count, uint32_t *bg, uint32_t *fg, VncPalette **palette) { int max; max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor; if (max < 2 && count >= tight_conf[vs->tight.compression].mono_min_rect_size) { max = 2; } if (max >= 256) { max = 256; } switch(vs->clientds.pf.bytes_per_pixel) { case 4: return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette); case 2: return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette); default: max = 2; return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette); } return 0; } Commit Message: CWE ID: CWE-125
static int tight_fill_palette(VncState *vs, int x, int y, size_t count, uint32_t *bg, uint32_t *fg, VncPalette **palette) { int max; max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor; if (max < 2 && count >= tight_conf[vs->tight.compression].mono_min_rect_size) { max = 2; } if (max >= 256) { max = 256; } switch (vs->client_pf.bytes_per_pixel) { case 4: return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette); case 2: return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette); default: max = 2; return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette); } return 0; }
165,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DeserializeNotificationDatabaseData(const std::string& input, NotificationDatabaseData* output) { DCHECK(output); NotificationDatabaseDataProto message; if (!message.ParseFromString(input)) return false; output->notification_id = message.notification_id(); output->origin = GURL(message.origin()); output->service_worker_registration_id = message.service_worker_registration_id(); PlatformNotificationData* notification_data = &output->notification_data; const NotificationDatabaseDataProto::NotificationData& payload = message.notification_data(); notification_data->title = base::UTF8ToUTF16(payload.title()); switch (payload.direction()) { case NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT: notification_data->direction = PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; break; case NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT: notification_data->direction = PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; break; case NotificationDatabaseDataProto::NotificationData::AUTO: notification_data->direction = PlatformNotificationData::DIRECTION_AUTO; break; } notification_data->lang = payload.lang(); notification_data->body = base::UTF8ToUTF16(payload.body()); notification_data->tag = payload.tag(); notification_data->icon = GURL(payload.icon()); if (payload.vibration_pattern().size() > 0) { notification_data->vibration_pattern.assign( payload.vibration_pattern().begin(), payload.vibration_pattern().end()); } notification_data->timestamp = base::Time::FromInternalValue(payload.timestamp()); notification_data->silent = payload.silent(); notification_data->require_interaction = payload.require_interaction(); if (payload.data().length()) { notification_data->data.assign(payload.data().begin(), payload.data().end()); } for (const auto& payload_action : payload.actions()) { PlatformNotificationAction action; action.action = payload_action.action(); action.title = base::UTF8ToUTF16(payload_action.title()); notification_data->actions.push_back(action); } return true; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
bool DeserializeNotificationDatabaseData(const std::string& input, NotificationDatabaseData* output) { DCHECK(output); NotificationDatabaseDataProto message; if (!message.ParseFromString(input)) return false; output->notification_id = message.notification_id(); output->origin = GURL(message.origin()); output->service_worker_registration_id = message.service_worker_registration_id(); PlatformNotificationData* notification_data = &output->notification_data; const NotificationDatabaseDataProto::NotificationData& payload = message.notification_data(); notification_data->title = base::UTF8ToUTF16(payload.title()); switch (payload.direction()) { case NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT: notification_data->direction = PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; break; case NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT: notification_data->direction = PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; break; case NotificationDatabaseDataProto::NotificationData::AUTO: notification_data->direction = PlatformNotificationData::DIRECTION_AUTO; break; } notification_data->lang = payload.lang(); notification_data->body = base::UTF8ToUTF16(payload.body()); notification_data->tag = payload.tag(); notification_data->icon = GURL(payload.icon()); if (payload.vibration_pattern().size() > 0) { notification_data->vibration_pattern.assign( payload.vibration_pattern().begin(), payload.vibration_pattern().end()); } notification_data->timestamp = base::Time::FromInternalValue(payload.timestamp()); notification_data->silent = payload.silent(); notification_data->require_interaction = payload.require_interaction(); if (payload.data().length()) { notification_data->data.assign(payload.data().begin(), payload.data().end()); } for (const auto& payload_action : payload.actions()) { PlatformNotificationAction action; action.action = payload_action.action(); action.title = base::UTF8ToUTF16(payload_action.title()); action.icon = GURL(payload_action.icon()); notification_data->actions.push_back(action); } return true; }
171,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::CreateBlock(long long id, long long pos, // absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock if (m_entries_count < 0) { // haven't parsed anything yet assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new BlockEntry* [m_entries_size]; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new BlockEntry* [entries_size]; assert(entries); BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) // BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else // SimpleBlock ID return CreateSimpleBlock(pos, size); } 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::CreateBlock(long long id, long long pos, // absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock if (m_entries_count < 0) { // haven't parsed anything yet assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new (std::nothrow) BlockEntry*[m_entries_size]; if (m_entries == NULL) return -1; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new (std::nothrow) BlockEntry*[entries_size]; if (entries == NULL) return -1; BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) // BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else // SimpleBlock ID return CreateSimpleBlock(pos, size); }
173,805
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::FocusThroughTabTraversal(bool reverse) { if (ShowingInterstitialPage()) { GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse); return; } RenderWidgetHostView* const fullscreen_view = GetFullscreenRenderWidgetHostView(); if (fullscreen_view) { fullscreen_view->Focus(); return; } GetRenderViewHost()->SetInitialFocus(reverse); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void WebContentsImpl::FocusThroughTabTraversal(bool reverse) { if (ShowingInterstitialPage()) { interstitial_page_->FocusThroughTabTraversal(reverse); return; } RenderWidgetHostView* const fullscreen_view = GetFullscreenRenderWidgetHostView(); if (fullscreen_view) { fullscreen_view->Focus(); return; } GetRenderViewHost()->SetInitialFocus(reverse); }
172,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageCapture::ResolveWithMediaTrackConstraints( MediaTrackConstraints constraints, ScriptPromiseResolver* resolver) { DCHECK(resolver); resolver->Resolve(constraints); } Commit Message: Convert MediaTrackConstraints to a ScriptValue IDLDictionaries such as MediaTrackConstraints should not be stored on the heap which would happen when binding one as a parameter to a callback. This change converts the object to a ScriptValue ahead of time. This is fine because the value will be passed to a ScriptPromiseResolver that will converted it to a V8 value if it isn't already. Bug: 759457 Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8 Reviewed-on: https://chromium-review.googlesource.com/701358 Reviewed-by: Kentaro Hara <haraken@chromium.org> Commit-Queue: Reilly Grant <reillyg@chromium.org> Cr-Commit-Position: refs/heads/master@{#507177} CWE ID: CWE-416
void ImageCapture::ResolveWithMediaTrackConstraints( ScriptValue constraints, ScriptPromiseResolver* resolver) { DCHECK(resolver); resolver->Resolve(constraints); }
172,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OMXNodeInstance::handleMessage(omx_message &msg) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (msg.type == omx_message::FILL_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.extended_buffer_data.buffer); { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( FBD, WITH_STATS(FULL_BUFFER( msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd))); unbumpDebugLevel_l(kPortIndexOutput); } BufferMeta *buffer_meta = static_cast<BufferMeta *>(buffer->pAppPrivate); if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset || buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) { CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter, FULL_BUFFER(NULL, buffer, msg.fenceFd)); } buffer_meta->CopyFromOMX(buffer); if (bufferSource != NULL) { bufferSource->codecBufferFilled(buffer); msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp; } } else if (msg.type == omx_message::EMPTY_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.buffer_data.buffer); { Mutex::Autolock _l(mDebugLock); mInputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd))); } if (bufferSource != NULL) { bufferSource->codecBufferEmptied(buffer, msg.fenceFd); return true; } } return false; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
bool OMXNodeInstance::handleMessage(omx_message &msg) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (msg.type == omx_message::FILL_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.extended_buffer_data.buffer, kPortIndexOutput); if (buffer == NULL) { return false; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( FBD, WITH_STATS(FULL_BUFFER( msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd))); unbumpDebugLevel_l(kPortIndexOutput); } BufferMeta *buffer_meta = static_cast<BufferMeta *>(buffer->pAppPrivate); if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset || buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) { CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter, FULL_BUFFER(NULL, buffer, msg.fenceFd)); } buffer_meta->CopyFromOMX(buffer); if (bufferSource != NULL) { bufferSource->codecBufferFilled(buffer); msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp; } } else if (msg.type == omx_message::EMPTY_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.buffer_data.buffer, kPortIndexInput); if (buffer == NULL) { return false; } { Mutex::Autolock _l(mDebugLock); mInputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd))); } if (bufferSource != NULL) { bufferSource->codecBufferEmptied(buffer, msg.fenceFd); return true; } } return false; }
173,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::GetDiscardPadding() const { return m_discard_padding; } 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::GetDiscardPadding() const
174,303