instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoundPool::doLoad(sp<Sample>& sample)
{
ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
sample->startLoad();
mDecodeThread->loadSample(sample->sampleID());
}
Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread
Sample decoding still occurs in SoundPoolThread
without holding the SoundPool lock.
Bug: 25781119
Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
CWE ID: CWE-264 | void SoundPool::doLoad(sp<Sample>& sample)
int sampleID;
{
Mutex::Autolock lock(&mLock);
sampleID = ++mNextSampleID;
sp<Sample> sample = new Sample(sampleID, fd, offset, length);
mSamples.add(sampleID, sample);
sample->startLoad();
}
// mDecodeThread->loadSample() must be called outside of mLock.
// mDecodeThread->loadSample() may block on mDecodeThread message queue space;
// the message queue emptying may block on SoundPool::findSample().
//
// It theoretically possible that sample loads might decode out-of-order.
mDecodeThread->loadSample(sampleID);
return sampleID;
}
| 173,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ParamTraits<FilePath>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
FilePath::StringType value;
if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value))
return false;
*r = FilePath(value);
return true;
}
Commit Message: Validate that paths don't contain embedded NULLs at deserialization.
BUG=166867
Review URL: https://chromiumcodereview.appspot.com/11743009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool ParamTraits<FilePath>::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
FilePath::StringType value;
if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value))
return false;
// Reject embedded NULs as they can cause security checks to go awry.
if (value.find(FILE_PATH_LITERAL('\0')) != FilePath::StringType::npos)
return false;
*r = FilePath(value);
return true;
}
| 171,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg)
{
if (pp != NULL)
png_error(pp, msg);
/* Else we have to do it ourselves. png_error eventually calls store_log,
* above. store_log accepts a NULL png_structp - it just changes what gets
* output by store_message.
*/
store_log(ps, pp, msg, 1 /* error */);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg)
store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
{
if (pp != NULL)
png_error(pp, msg);
/* Else we have to do it ourselves. png_error eventually calls store_log,
* above. store_log accepts a NULL png_structp - it just changes what gets
* output by store_message.
*/
store_log(ps, pp, msg, 1 /* error */);
}
| 173,708 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream)
{
UWORD16 u2_mb_addr_incr = 0;
while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE)
{
impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN);
u2_mb_addr_incr += 33;
}
u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) +
MB_ADDR_INCR_OFFSET;
return(u2_mb_addr_incr);
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream)
{
UWORD16 u2_mb_addr_incr = 0;
while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN);
u2_mb_addr_incr += 33;
}
u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) +
MB_ADDR_INCR_OFFSET;
return(u2_mb_addr_incr);
}
| 173,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ip_printroute(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
if (length < 3) {
ND_PRINT((ndo, " [bad length %u]", length));
return;
}
if ((length + 1) & 3)
ND_PRINT((ndo, " [bad length %u]", length));
ptr = cp[2] - 1;
if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1)
ND_PRINT((ndo, " [bad ptr %u]", cp[2]));
for (len = 3; len < length; len += 4) {
ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len])));
if (ptr > len)
ND_PRINT((ndo, ","));
}
}
Commit Message: CVE-2017-13022/IP: Add bounds checks to ip_printroute().
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ip_printroute(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
if (length < 3) {
ND_PRINT((ndo, " [bad length %u]", length));
return (0);
}
if ((length + 1) & 3)
ND_PRINT((ndo, " [bad length %u]", length));
ND_TCHECK(cp[2]);
ptr = cp[2] - 1;
if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1)
ND_PRINT((ndo, " [bad ptr %u]", cp[2]));
for (len = 3; len < length; len += 4) {
ND_TCHECK2(cp[len], 4);
ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len])));
if (ptr > len)
ND_PRINT((ndo, ","));
}
return (0);
trunc:
return (-1);
}
| 167,870 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper(
ppapi::host::ResourceHost* resource_host,
Delegate* delegate,
PP_DeviceType_Dev device_type,
const GURL& document_url)
: resource_host_(resource_host),
delegate_(delegate),
device_type_(device_type),
document_url_(document_url) {}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399 | PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper(
ppapi::host::ResourceHost* resource_host,
base::WeakPtr<Delegate> delegate,
PP_DeviceType_Dev device_type,
const GURL& document_url)
: resource_host_(resource_host),
delegate_(delegate),
device_type_(device_type),
document_url_(document_url) {}
| 171,604 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
struct epoll_event __user *, event)
{
int error;
int did_lock_epmutex = 0;
struct file *file, *tfile;
struct eventpoll *ep;
struct epitem *epi;
struct epoll_event epds;
error = -EFAULT;
if (ep_op_has_event(op) &&
copy_from_user(&epds, event, sizeof(struct epoll_event)))
goto error_return;
/* Get the "struct file *" for the eventpoll file */
error = -EBADF;
file = fget(epfd);
if (!file)
goto error_return;
/* Get the "struct file *" for the target file */
tfile = fget(fd);
if (!tfile)
goto error_fput;
/* The target file descriptor must support poll */
error = -EPERM;
if (!tfile->f_op || !tfile->f_op->poll)
goto error_tgt_fput;
/*
* We have to check that the file structure underneath the file descriptor
* the user passed to us _is_ an eventpoll file. And also we do not permit
* adding an epoll file descriptor inside itself.
*/
error = -EINVAL;
if (file == tfile || !is_file_epoll(file))
goto error_tgt_fput;
/*
* At this point it is safe to assume that the "private_data" contains
* our own data structure.
*/
ep = file->private_data;
/*
* When we insert an epoll file descriptor, inside another epoll file
* descriptor, there is the change of creating closed loops, which are
* better be handled here, than in more critical paths. While we are
* checking for loops we also determine the list of files reachable
* and hang them on the tfile_check_list, so we can check that we
* haven't created too many possible wakeup paths.
*
* We need to hold the epmutex across both ep_insert and ep_remove
* b/c we want to make sure we are looking at a coherent view of
* epoll network.
*/
if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_DEL) {
mutex_lock(&epmutex);
did_lock_epmutex = 1;
}
if (op == EPOLL_CTL_ADD) {
if (is_file_epoll(tfile)) {
error = -ELOOP;
if (ep_loop_check(ep, tfile) != 0)
goto error_tgt_fput;
} else
list_add(&tfile->f_tfile_llink, &tfile_check_list);
}
mutex_lock_nested(&ep->mtx, 0);
/*
* Try to lookup the file inside our RB tree, Since we grabbed "mtx"
* above, we can be sure to be able to use the item looked up by
* ep_find() till we release the mutex.
*/
epi = ep_find(ep, tfile, fd);
error = -EINVAL;
switch (op) {
case EPOLL_CTL_ADD:
if (!epi) {
epds.events |= POLLERR | POLLHUP;
error = ep_insert(ep, &epds, tfile, fd);
} else
error = -EEXIST;
clear_tfile_check_list();
break;
case EPOLL_CTL_DEL:
if (epi)
error = ep_remove(ep, epi);
else
error = -ENOENT;
break;
case EPOLL_CTL_MOD:
if (epi) {
epds.events |= POLLERR | POLLHUP;
error = ep_modify(ep, epi, &epds);
} else
error = -ENOENT;
break;
}
mutex_unlock(&ep->mtx);
error_tgt_fput:
if (did_lock_epmutex)
mutex_unlock(&epmutex);
fput(tfile);
error_fput:
fput(file);
error_return:
return error;
}
Commit Message: epoll: clear the tfile_check_list on -ELOOP
An epoll_ctl(,EPOLL_CTL_ADD,,) operation can return '-ELOOP' to prevent
circular epoll dependencies from being created. However, in that case we
do not properly clear the 'tfile_check_list'. Thus, add a call to
clear_tfile_check_list() for the -ELOOP case.
Signed-off-by: Jason Baron <[email protected]>
Reported-by: Yurij M. Plotnikov <[email protected]>
Cc: Nelson Elhage <[email protected]>
Cc: Davide Libenzi <[email protected]>
Tested-by: Alexandra N. Kossovsky <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
struct epoll_event __user *, event)
{
int error;
int did_lock_epmutex = 0;
struct file *file, *tfile;
struct eventpoll *ep;
struct epitem *epi;
struct epoll_event epds;
error = -EFAULT;
if (ep_op_has_event(op) &&
copy_from_user(&epds, event, sizeof(struct epoll_event)))
goto error_return;
/* Get the "struct file *" for the eventpoll file */
error = -EBADF;
file = fget(epfd);
if (!file)
goto error_return;
/* Get the "struct file *" for the target file */
tfile = fget(fd);
if (!tfile)
goto error_fput;
/* The target file descriptor must support poll */
error = -EPERM;
if (!tfile->f_op || !tfile->f_op->poll)
goto error_tgt_fput;
/*
* We have to check that the file structure underneath the file descriptor
* the user passed to us _is_ an eventpoll file. And also we do not permit
* adding an epoll file descriptor inside itself.
*/
error = -EINVAL;
if (file == tfile || !is_file_epoll(file))
goto error_tgt_fput;
/*
* At this point it is safe to assume that the "private_data" contains
* our own data structure.
*/
ep = file->private_data;
/*
* When we insert an epoll file descriptor, inside another epoll file
* descriptor, there is the change of creating closed loops, which are
* better be handled here, than in more critical paths. While we are
* checking for loops we also determine the list of files reachable
* and hang them on the tfile_check_list, so we can check that we
* haven't created too many possible wakeup paths.
*
* We need to hold the epmutex across both ep_insert and ep_remove
* b/c we want to make sure we are looking at a coherent view of
* epoll network.
*/
if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_DEL) {
mutex_lock(&epmutex);
did_lock_epmutex = 1;
}
if (op == EPOLL_CTL_ADD) {
if (is_file_epoll(tfile)) {
error = -ELOOP;
if (ep_loop_check(ep, tfile) != 0) {
clear_tfile_check_list();
goto error_tgt_fput;
}
} else
list_add(&tfile->f_tfile_llink, &tfile_check_list);
}
mutex_lock_nested(&ep->mtx, 0);
/*
* Try to lookup the file inside our RB tree, Since we grabbed "mtx"
* above, we can be sure to be able to use the item looked up by
* ep_find() till we release the mutex.
*/
epi = ep_find(ep, tfile, fd);
error = -EINVAL;
switch (op) {
case EPOLL_CTL_ADD:
if (!epi) {
epds.events |= POLLERR | POLLHUP;
error = ep_insert(ep, &epds, tfile, fd);
} else
error = -EEXIST;
clear_tfile_check_list();
break;
case EPOLL_CTL_DEL:
if (epi)
error = ep_remove(ep, epi);
else
error = -ENOENT;
break;
case EPOLL_CTL_MOD:
if (epi) {
epds.events |= POLLERR | POLLHUP;
error = ep_modify(ep, epi, &epds);
} else
error = -ENOENT;
break;
}
mutex_unlock(&ep->mtx);
error_tgt_fput:
if (did_lock_epmutex)
mutex_unlock(&epmutex);
fput(tfile);
error_fput:
fput(file);
error_return:
return error;
}
| 165,588 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + (rlen + 1);
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
list[i] = NULL;
}
} else
list[i] = NULL;
}
}
} else
Commit Message:
CWE ID: CWE-682 | char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + rlen;
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
list[i] = NULL;
}
}
} else
| 164,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void reply_sesssetup_and_X_spnego(struct smb_request *req)
{
const uint8 *p;
DATA_BLOB blob1;
size_t bufrem;
char *tmp;
const char *native_os;
const char *native_lanman;
const char *primary_domain;
const char *p2;
uint16 data_blob_len = SVAL(req->vwv+7, 0);
enum remote_arch_types ra_type = get_remote_arch();
int vuid = req->vuid;
user_struct *vuser = NULL;
NTSTATUS status = NT_STATUS_OK;
uint16 smbpid = req->smbpid;
struct smbd_server_connection *sconn = smbd_server_conn;
DEBUG(3,("Doing spnego session setup\n"));
if (global_client_caps == 0) {
global_client_caps = IVAL(req->vwv+10, 0);
if (!(global_client_caps & CAP_STATUS32)) {
remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES);
}
}
p = req->buf;
if (data_blob_len == 0) {
/* an invalid request */
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
return;
}
bufrem = smbreq_bufrem(req, p);
/* pull the spnego blob */
blob1 = data_blob(p, MIN(bufrem, data_blob_len));
#if 0
file_save("negotiate.dat", blob1.data, blob1.length);
#endif
p2 = (char *)req->buf + data_blob_len;
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_os = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_lanman = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
primary_domain = tmp ? tmp : "";
DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n",
native_os, native_lanman, primary_domain));
if ( ra_type == RA_WIN2K ) {
/* Vista sets neither the OS or lanman strings */
if ( !strlen(native_os) && !strlen(native_lanman) )
set_remote_arch(RA_VISTA);
/* Windows 2003 doesn't set the native lanman string,
but does set primary domain which is a bug I think */
if ( !strlen(native_lanman) ) {
ra_lanman_string( primary_domain );
} else {
ra_lanman_string( native_lanman );
}
}
/* Did we get a valid vuid ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, then try and see if this is an intermediate sessionsetup
* for a large SPNEGO packet. */
struct pending_auth_data *pad;
pad = get_pending_auth_data(sconn, smbpid);
if (pad) {
DEBUG(10,("reply_sesssetup_and_X_spnego: found "
"pending vuid %u\n",
(unsigned int)pad->vuid ));
vuid = pad->vuid;
}
}
/* Do we have a valid vuid now ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, start a new authentication setup. */
vuid = register_initial_vuid(sconn);
if (vuid == UID_FIELD_INVALID) {
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(
NT_STATUS_INVALID_PARAMETER));
return;
}
}
vuser = get_partial_auth_user_struct(sconn, vuid);
/* This MUST be valid. */
if (!vuser) {
smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
}
/* Large (greater than 4k) SPNEGO blobs are split into multiple
* sessionsetup requests as the Windows limit on the security blob
* field is 4k. Bug #4400. JRA.
*/
status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
if (!NT_STATUS_IS_OK(status)) {
if (!NT_STATUS_EQUAL(status,
NT_STATUS_MORE_PROCESSING_REQUIRED)) {
/* Real error - kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
}
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
if (blob1.data[0] == ASN1_APPLICATION(0)) {
/* its a negTokenTarg packet */
reply_spnego_negotiate(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (blob1.data[0] == ASN1_CONTEXT(1)) {
/* its a auth packet */
reply_spnego_auth(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) {
DATA_BLOB chal;
if (!vuser->auth_ntlmssp_state) {
status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
if (!NT_STATUS_IS_OK(status)) {
/* Kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
}
status = auth_ntlmssp_update(vuser->auth_ntlmssp_state,
blob1, &chal);
data_blob_free(&blob1);
reply_spnego_ntlmssp(req, vuid,
&vuser->auth_ntlmssp_state,
&chal, status, OID_NTLMSSP, false);
data_blob_free(&chal);
return;
}
/* what sort of packet is this? */
DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n"));
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
}
Commit Message:
CWE ID: CWE-119 | static void reply_sesssetup_and_X_spnego(struct smb_request *req)
{
const uint8 *p;
DATA_BLOB blob1;
size_t bufrem;
char *tmp;
const char *native_os;
const char *native_lanman;
const char *primary_domain;
const char *p2;
uint16 data_blob_len = SVAL(req->vwv+7, 0);
enum remote_arch_types ra_type = get_remote_arch();
int vuid = req->vuid;
user_struct *vuser = NULL;
NTSTATUS status = NT_STATUS_OK;
uint16 smbpid = req->smbpid;
struct smbd_server_connection *sconn = smbd_server_conn;
DEBUG(3,("Doing spnego session setup\n"));
if (global_client_caps == 0) {
global_client_caps = IVAL(req->vwv+10, 0);
if (!(global_client_caps & CAP_STATUS32)) {
remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES);
}
}
p = req->buf;
if (data_blob_len == 0) {
/* an invalid request */
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
return;
}
bufrem = smbreq_bufrem(req, p);
/* pull the spnego blob */
blob1 = data_blob(p, MIN(bufrem, data_blob_len));
#if 0
file_save("negotiate.dat", blob1.data, blob1.length);
#endif
p2 = (char *)req->buf + blob1.length;
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_os = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_lanman = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
primary_domain = tmp ? tmp : "";
DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n",
native_os, native_lanman, primary_domain));
if ( ra_type == RA_WIN2K ) {
/* Vista sets neither the OS or lanman strings */
if ( !strlen(native_os) && !strlen(native_lanman) )
set_remote_arch(RA_VISTA);
/* Windows 2003 doesn't set the native lanman string,
but does set primary domain which is a bug I think */
if ( !strlen(native_lanman) ) {
ra_lanman_string( primary_domain );
} else {
ra_lanman_string( native_lanman );
}
}
/* Did we get a valid vuid ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, then try and see if this is an intermediate sessionsetup
* for a large SPNEGO packet. */
struct pending_auth_data *pad;
pad = get_pending_auth_data(sconn, smbpid);
if (pad) {
DEBUG(10,("reply_sesssetup_and_X_spnego: found "
"pending vuid %u\n",
(unsigned int)pad->vuid ));
vuid = pad->vuid;
}
}
/* Do we have a valid vuid now ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, start a new authentication setup. */
vuid = register_initial_vuid(sconn);
if (vuid == UID_FIELD_INVALID) {
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(
NT_STATUS_INVALID_PARAMETER));
return;
}
}
vuser = get_partial_auth_user_struct(sconn, vuid);
/* This MUST be valid. */
if (!vuser) {
smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
}
/* Large (greater than 4k) SPNEGO blobs are split into multiple
* sessionsetup requests as the Windows limit on the security blob
* field is 4k. Bug #4400. JRA.
*/
status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
if (!NT_STATUS_IS_OK(status)) {
if (!NT_STATUS_EQUAL(status,
NT_STATUS_MORE_PROCESSING_REQUIRED)) {
/* Real error - kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
}
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
if (blob1.data[0] == ASN1_APPLICATION(0)) {
/* its a negTokenTarg packet */
reply_spnego_negotiate(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (blob1.data[0] == ASN1_CONTEXT(1)) {
/* its a auth packet */
reply_spnego_auth(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) {
DATA_BLOB chal;
if (!vuser->auth_ntlmssp_state) {
status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
if (!NT_STATUS_IS_OK(status)) {
/* Kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
}
status = auth_ntlmssp_update(vuser->auth_ntlmssp_state,
blob1, &chal);
data_blob_free(&blob1);
reply_spnego_ntlmssp(req, vuid,
&vuser->auth_ntlmssp_state,
&chal, status, OID_NTLMSSP, false);
data_blob_free(&chal);
return;
}
/* what sort of packet is this? */
DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n"));
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
}
| 165,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IHEVCD_ERROR_T ihevcd_parse_sps(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i;
WORD32 vps_id;
WORD32 sps_max_sub_layers;
WORD32 sps_id;
WORD32 sps_temporal_id_nesting_flag;
sps_t *ps_sps;
profile_tier_lvl_info_t s_ptl;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 ctb_log2_size_y = 0;
BITS_PARSE("video_parameter_set_id", value, ps_bitstrm, 4);
vps_id = value;
vps_id = CLIP3(vps_id, 0, MAX_VPS_CNT - 1);
BITS_PARSE("sps_max_sub_layers_minus1", value, ps_bitstrm, 3);
sps_max_sub_layers = value + 1;
sps_max_sub_layers = CLIP3(sps_max_sub_layers, 1, 7);
BITS_PARSE("sps_temporal_id_nesting_flag", value, ps_bitstrm, 1);
sps_temporal_id_nesting_flag = value;
ret = ihevcd_profile_tier_level(ps_bitstrm, &(s_ptl), 1,
(sps_max_sub_layers - 1));
UEV_PARSE("seq_parameter_set_id", value, ps_bitstrm);
sps_id = value;
if((sps_id >= MAX_SPS_CNT) || (sps_id < 0))
{
if(ps_codec->i4_sps_done)
return IHEVCD_UNSUPPORTED_SPS_ID;
else
sps_id = 0;
}
ps_sps = (ps_codec->s_parse.ps_sps_base + MAX_SPS_CNT - 1);
ps_sps->i1_sps_id = sps_id;
ps_sps->i1_vps_id = vps_id;
ps_sps->i1_sps_max_sub_layers = sps_max_sub_layers;
ps_sps->i1_sps_temporal_id_nesting_flag = sps_temporal_id_nesting_flag;
/* This is used only during initialization to get reorder count etc */
ps_codec->i4_sps_id = sps_id;
memcpy(&ps_sps->s_ptl, &s_ptl, sizeof(profile_tier_lvl_info_t));
UEV_PARSE("chroma_format_idc", value, ps_bitstrm);
ps_sps->i1_chroma_format_idc = value;
if(ps_sps->i1_chroma_format_idc != CHROMA_FMT_IDC_YUV420)
{
ps_codec->s_parse.i4_error_code = IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC;
return (IHEVCD_ERROR_T)IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC;
}
if(CHROMA_FMT_IDC_YUV444_PLANES == ps_sps->i1_chroma_format_idc)
{
BITS_PARSE("separate_colour_plane_flag", value, ps_bitstrm, 1);
ps_sps->i1_separate_colour_plane_flag = value;
}
else
{
ps_sps->i1_separate_colour_plane_flag = 0;
}
UEV_PARSE("pic_width_in_luma_samples", value, ps_bitstrm);
ps_sps->i2_pic_width_in_luma_samples = value;
UEV_PARSE("pic_height_in_luma_samples", value, ps_bitstrm);
ps_sps->i2_pic_height_in_luma_samples = value;
if((0 >= ps_sps->i2_pic_width_in_luma_samples) || (0 >= ps_sps->i2_pic_height_in_luma_samples))
return IHEVCD_INVALID_PARAMETER;
/* i2_pic_width_in_luma_samples and i2_pic_height_in_luma_samples
should be multiples of min_cb_size. Here these are aligned to 8,
i.e. smallest CB size */
ps_sps->i2_pic_width_in_luma_samples = ALIGN8(ps_sps->i2_pic_width_in_luma_samples);
ps_sps->i2_pic_height_in_luma_samples = ALIGN8(ps_sps->i2_pic_height_in_luma_samples);
BITS_PARSE("pic_cropping_flag", value, ps_bitstrm, 1);
ps_sps->i1_pic_cropping_flag = value;
if(ps_sps->i1_pic_cropping_flag)
{
UEV_PARSE("pic_crop_left_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_left_offset = value;
UEV_PARSE("pic_crop_right_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_right_offset = value;
UEV_PARSE("pic_crop_top_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_top_offset = value;
UEV_PARSE("pic_crop_bottom_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_bottom_offset = value;
}
else
{
ps_sps->i2_pic_crop_left_offset = 0;
ps_sps->i2_pic_crop_right_offset = 0;
ps_sps->i2_pic_crop_top_offset = 0;
ps_sps->i2_pic_crop_bottom_offset = 0;
}
UEV_PARSE("bit_depth_luma_minus8", value, ps_bitstrm);
if(0 != value)
return IHEVCD_UNSUPPORTED_BIT_DEPTH;
UEV_PARSE("bit_depth_chroma_minus8", value, ps_bitstrm);
if(0 != value)
return IHEVCD_UNSUPPORTED_BIT_DEPTH;
UEV_PARSE("log2_max_pic_order_cnt_lsb_minus4", value, ps_bitstrm);
ps_sps->i1_log2_max_pic_order_cnt_lsb = value + 4;
BITS_PARSE("sps_sub_layer_ordering_info_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_sps_sub_layer_ordering_info_present_flag = value;
i = (ps_sps->i1_sps_sub_layer_ordering_info_present_flag ? 0 : (ps_sps->i1_sps_max_sub_layers - 1));
for(; i < ps_sps->i1_sps_max_sub_layers; i++)
{
UEV_PARSE("max_dec_pic_buffering", value, ps_bitstrm);
ps_sps->ai1_sps_max_dec_pic_buffering[i] = value + 1;
if(ps_sps->ai1_sps_max_dec_pic_buffering[i] > MAX_DPB_SIZE)
{
return IHEVCD_INVALID_PARAMETER;
}
UEV_PARSE("num_reorder_pics", value, ps_bitstrm);
ps_sps->ai1_sps_max_num_reorder_pics[i] = value;
if(ps_sps->ai1_sps_max_num_reorder_pics[i] > ps_sps->ai1_sps_max_dec_pic_buffering[i])
{
return IHEVCD_INVALID_PARAMETER;
}
UEV_PARSE("max_latency_increase", value, ps_bitstrm);
ps_sps->ai1_sps_max_latency_increase[i] = value;
}
UEV_PARSE("log2_min_coding_block_size_minus3", value, ps_bitstrm);
ps_sps->i1_log2_min_coding_block_size = value + 3;
UEV_PARSE("log2_diff_max_min_coding_block_size", value, ps_bitstrm);
ps_sps->i1_log2_diff_max_min_coding_block_size = value;
ctb_log2_size_y = ps_sps->i1_log2_min_coding_block_size + ps_sps->i1_log2_diff_max_min_coding_block_size;
UEV_PARSE("log2_min_transform_block_size_minus2", value, ps_bitstrm);
ps_sps->i1_log2_min_transform_block_size = value + 2;
UEV_PARSE("log2_diff_max_min_transform_block_size", value, ps_bitstrm);
ps_sps->i1_log2_diff_max_min_transform_block_size = value;
ps_sps->i1_log2_max_transform_block_size = ps_sps->i1_log2_min_transform_block_size +
ps_sps->i1_log2_diff_max_min_transform_block_size;
if ((ps_sps->i1_log2_max_transform_block_size < 0) ||
(ps_sps->i1_log2_max_transform_block_size > MIN(ctb_log2_size_y, 5)))
{
return IHEVCD_INVALID_PARAMETER;
}
ps_sps->i1_log2_ctb_size = ps_sps->i1_log2_min_coding_block_size +
ps_sps->i1_log2_diff_max_min_coding_block_size;
if((ps_sps->i1_log2_min_coding_block_size < 3) ||
(ps_sps->i1_log2_min_transform_block_size < 2) ||
(ps_sps->i1_log2_diff_max_min_transform_block_size < 0) ||
(ps_sps->i1_log2_max_transform_block_size > ps_sps->i1_log2_ctb_size) ||
(ps_sps->i1_log2_ctb_size < 4) ||
(ps_sps->i1_log2_ctb_size > 6))
{
return IHEVCD_INVALID_PARAMETER;
}
ps_sps->i1_log2_min_pcm_coding_block_size = 0;
ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = 0;
UEV_PARSE("max_transform_hierarchy_depth_inter", value, ps_bitstrm);
ps_sps->i1_max_transform_hierarchy_depth_inter = value;
UEV_PARSE("max_transform_hierarchy_depth_intra", value, ps_bitstrm);
ps_sps->i1_max_transform_hierarchy_depth_intra = value;
/* String has a d (enabled) in order to match with HM */
BITS_PARSE("scaling_list_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_scaling_list_enable_flag = value;
if(ps_sps->i1_scaling_list_enable_flag)
{
COPY_DEFAULT_SCALING_LIST(ps_sps->pi2_scaling_mat);
BITS_PARSE("sps_scaling_list_data_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_sps_scaling_list_data_present_flag = value;
if(ps_sps->i1_sps_scaling_list_data_present_flag)
ihevcd_scaling_list_data(ps_codec, ps_sps->pi2_scaling_mat);
}
else
{
COPY_FLAT_SCALING_LIST(ps_sps->pi2_scaling_mat);
}
/* String is asymmetric_motion_partitions_enabled_flag instead of amp_enabled_flag in order to match with HM */
BITS_PARSE("asymmetric_motion_partitions_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_amp_enabled_flag = value;
BITS_PARSE("sample_adaptive_offset_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_sample_adaptive_offset_enabled_flag = value;
BITS_PARSE("pcm_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_pcm_enabled_flag = value;
if(ps_sps->i1_pcm_enabled_flag)
{
BITS_PARSE("pcm_sample_bit_depth_luma", value, ps_bitstrm, 4);
ps_sps->i1_pcm_sample_bit_depth_luma = value + 1;
BITS_PARSE("pcm_sample_bit_depth_chroma", value, ps_bitstrm, 4);
ps_sps->i1_pcm_sample_bit_depth_chroma = value + 1;
UEV_PARSE("log2_min_pcm_coding_block_size_minus3", value, ps_bitstrm);
ps_sps->i1_log2_min_pcm_coding_block_size = value + 3;
UEV_PARSE("log2_diff_max_min_pcm_coding_block_size", value, ps_bitstrm);
ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = value;
BITS_PARSE("pcm_loop_filter_disable_flag", value, ps_bitstrm, 1);
ps_sps->i1_pcm_loop_filter_disable_flag = value;
}
UEV_PARSE("num_short_term_ref_pic_sets", value, ps_bitstrm);
ps_sps->i1_num_short_term_ref_pic_sets = value;
ps_sps->i1_num_short_term_ref_pic_sets = CLIP3(ps_sps->i1_num_short_term_ref_pic_sets, 0, MAX_STREF_PICS_SPS);
for(i = 0; i < ps_sps->i1_num_short_term_ref_pic_sets; i++)
ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, i, &ps_sps->as_stref_picset[i]);
BITS_PARSE("long_term_ref_pics_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_long_term_ref_pics_present_flag = value;
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
UEV_PARSE("num_long_term_ref_pics_sps", value, ps_bitstrm);
ps_sps->i1_num_long_term_ref_pics_sps = value;
for(i = 0; i < ps_sps->i1_num_long_term_ref_pics_sps; i++)
{
BITS_PARSE("lt_ref_pic_poc_lsb_sps[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_sps->ai1_lt_ref_pic_poc_lsb_sps[i] = value;
BITS_PARSE("used_by_curr_pic_lt_sps_flag[ i ]", value, ps_bitstrm, 1);
ps_sps->ai1_used_by_curr_pic_lt_sps_flag[i] = value;
}
}
BITS_PARSE("sps_temporal_mvp_enable_flag", value, ps_bitstrm, 1);
ps_sps->i1_sps_temporal_mvp_enable_flag = value;
/* Print matches HM 8-2 */
BITS_PARSE("sps_strong_intra_smoothing_enable_flag", value, ps_bitstrm, 1);
ps_sps->i1_strong_intra_smoothing_enable_flag = value;
BITS_PARSE("vui_parameters_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_vui_parameters_present_flag = value;
if(ps_sps->i1_vui_parameters_present_flag)
ihevcd_parse_vui_parameters(ps_bitstrm,
&ps_sps->s_vui_parameters,
ps_sps->i1_sps_max_sub_layers - 1);
BITS_PARSE("sps_extension_flag", value, ps_bitstrm, 1);
{
WORD32 numerator;
WORD32 ceil_offset;
ceil_offset = (1 << ps_sps->i1_log2_ctb_size) - 1;
numerator = ps_sps->i2_pic_width_in_luma_samples;
ps_sps->i2_pic_wd_in_ctb = ((numerator + ceil_offset) /
(1 << ps_sps->i1_log2_ctb_size));
numerator = ps_sps->i2_pic_height_in_luma_samples;
ps_sps->i2_pic_ht_in_ctb = ((numerator + ceil_offset) /
(1 << ps_sps->i1_log2_ctb_size));
ps_sps->i4_pic_size_in_ctb = ps_sps->i2_pic_ht_in_ctb *
ps_sps->i2_pic_wd_in_ctb;
if(0 == ps_codec->i4_sps_done)
ps_codec->s_parse.i4_next_ctb_indx = ps_sps->i4_pic_size_in_ctb;
numerator = ps_sps->i2_pic_width_in_luma_samples;
ps_sps->i2_pic_wd_in_min_cb = numerator /
(1 << ps_sps->i1_log2_min_coding_block_size);
numerator = ps_sps->i2_pic_height_in_luma_samples;
ps_sps->i2_pic_ht_in_min_cb = numerator /
(1 << ps_sps->i1_log2_min_coding_block_size);
}
if((0 != ps_codec->i4_first_pic_done) &&
((ps_codec->i4_wd != ps_sps->i2_pic_width_in_luma_samples) ||
(ps_codec->i4_ht != ps_sps->i2_pic_height_in_luma_samples)))
{
ps_codec->i4_reset_flag = 1;
return (IHEVCD_ERROR_T)IVD_RES_CHANGED;
}
/* Update display width and display height */
{
WORD32 disp_wd, disp_ht;
WORD32 crop_unit_x, crop_unit_y;
crop_unit_x = 1;
crop_unit_y = 1;
if(CHROMA_FMT_IDC_YUV420 == ps_sps->i1_chroma_format_idc)
{
crop_unit_x = 2;
crop_unit_y = 2;
}
disp_wd = ps_sps->i2_pic_width_in_luma_samples;
disp_wd -= ps_sps->i2_pic_crop_left_offset * crop_unit_x;
disp_wd -= ps_sps->i2_pic_crop_right_offset * crop_unit_x;
disp_ht = ps_sps->i2_pic_height_in_luma_samples;
disp_ht -= ps_sps->i2_pic_crop_top_offset * crop_unit_y;
disp_ht -= ps_sps->i2_pic_crop_bottom_offset * crop_unit_y;
if((0 >= disp_wd) || (0 >= disp_ht))
return IHEVCD_INVALID_PARAMETER;
ps_codec->i4_disp_wd = disp_wd;
ps_codec->i4_disp_ht = disp_ht;
ps_codec->i4_wd = ps_sps->i2_pic_width_in_luma_samples;
ps_codec->i4_ht = ps_sps->i2_pic_height_in_luma_samples;
{
WORD32 ref_strd;
ref_strd = ALIGN32(ps_sps->i2_pic_width_in_luma_samples + PAD_WD);
if(ps_codec->i4_strd < ref_strd)
{
ps_codec->i4_strd = ref_strd;
}
}
if(0 == ps_codec->i4_share_disp_buf)
{
if(ps_codec->i4_disp_strd < ps_codec->i4_disp_wd)
{
ps_codec->i4_disp_strd = ps_codec->i4_disp_wd;
}
}
else
{
if(ps_codec->i4_disp_strd < ps_codec->i4_strd)
{
ps_codec->i4_disp_strd = ps_codec->i4_strd;
}
}
}
ps_codec->i4_sps_done = 1;
return ret;
}
Commit Message: Return error if SPS parsing reads more bytes than the nal length
Bug: 35039946
Change-Id: Ia97fa8711f313d0029d2b13e6d150d5e46b2bb99
(cherry picked from commit a6c58e18a49a1ea4929f8345b3c59f900d5813f5)
(cherry picked from commit 232bbe1908d1dd9f10513d7b8065ecaf5c9a11a6)
CWE ID: CWE-119 | IHEVCD_ERROR_T ihevcd_parse_sps(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i;
WORD32 vps_id;
WORD32 sps_max_sub_layers;
WORD32 sps_id;
WORD32 sps_temporal_id_nesting_flag;
sps_t *ps_sps;
profile_tier_lvl_info_t s_ptl;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 ctb_log2_size_y = 0;
BITS_PARSE("video_parameter_set_id", value, ps_bitstrm, 4);
vps_id = value;
vps_id = CLIP3(vps_id, 0, MAX_VPS_CNT - 1);
BITS_PARSE("sps_max_sub_layers_minus1", value, ps_bitstrm, 3);
sps_max_sub_layers = value + 1;
sps_max_sub_layers = CLIP3(sps_max_sub_layers, 1, 7);
BITS_PARSE("sps_temporal_id_nesting_flag", value, ps_bitstrm, 1);
sps_temporal_id_nesting_flag = value;
ret = ihevcd_profile_tier_level(ps_bitstrm, &(s_ptl), 1,
(sps_max_sub_layers - 1));
UEV_PARSE("seq_parameter_set_id", value, ps_bitstrm);
sps_id = value;
if((sps_id >= MAX_SPS_CNT) || (sps_id < 0))
{
if(ps_codec->i4_sps_done)
return IHEVCD_UNSUPPORTED_SPS_ID;
else
sps_id = 0;
}
ps_sps = (ps_codec->s_parse.ps_sps_base + MAX_SPS_CNT - 1);
ps_sps->i1_sps_id = sps_id;
ps_sps->i1_vps_id = vps_id;
ps_sps->i1_sps_max_sub_layers = sps_max_sub_layers;
ps_sps->i1_sps_temporal_id_nesting_flag = sps_temporal_id_nesting_flag;
/* This is used only during initialization to get reorder count etc */
ps_codec->i4_sps_id = sps_id;
memcpy(&ps_sps->s_ptl, &s_ptl, sizeof(profile_tier_lvl_info_t));
UEV_PARSE("chroma_format_idc", value, ps_bitstrm);
ps_sps->i1_chroma_format_idc = value;
if(ps_sps->i1_chroma_format_idc != CHROMA_FMT_IDC_YUV420)
{
ps_codec->s_parse.i4_error_code = IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC;
return (IHEVCD_ERROR_T)IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC;
}
if(CHROMA_FMT_IDC_YUV444_PLANES == ps_sps->i1_chroma_format_idc)
{
BITS_PARSE("separate_colour_plane_flag", value, ps_bitstrm, 1);
ps_sps->i1_separate_colour_plane_flag = value;
}
else
{
ps_sps->i1_separate_colour_plane_flag = 0;
}
UEV_PARSE("pic_width_in_luma_samples", value, ps_bitstrm);
ps_sps->i2_pic_width_in_luma_samples = value;
UEV_PARSE("pic_height_in_luma_samples", value, ps_bitstrm);
ps_sps->i2_pic_height_in_luma_samples = value;
if((0 >= ps_sps->i2_pic_width_in_luma_samples) || (0 >= ps_sps->i2_pic_height_in_luma_samples))
return IHEVCD_INVALID_PARAMETER;
/* i2_pic_width_in_luma_samples and i2_pic_height_in_luma_samples
should be multiples of min_cb_size. Here these are aligned to 8,
i.e. smallest CB size */
ps_sps->i2_pic_width_in_luma_samples = ALIGN8(ps_sps->i2_pic_width_in_luma_samples);
ps_sps->i2_pic_height_in_luma_samples = ALIGN8(ps_sps->i2_pic_height_in_luma_samples);
BITS_PARSE("pic_cropping_flag", value, ps_bitstrm, 1);
ps_sps->i1_pic_cropping_flag = value;
if(ps_sps->i1_pic_cropping_flag)
{
UEV_PARSE("pic_crop_left_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_left_offset = value;
UEV_PARSE("pic_crop_right_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_right_offset = value;
UEV_PARSE("pic_crop_top_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_top_offset = value;
UEV_PARSE("pic_crop_bottom_offset", value, ps_bitstrm);
ps_sps->i2_pic_crop_bottom_offset = value;
}
else
{
ps_sps->i2_pic_crop_left_offset = 0;
ps_sps->i2_pic_crop_right_offset = 0;
ps_sps->i2_pic_crop_top_offset = 0;
ps_sps->i2_pic_crop_bottom_offset = 0;
}
UEV_PARSE("bit_depth_luma_minus8", value, ps_bitstrm);
if(0 != value)
return IHEVCD_UNSUPPORTED_BIT_DEPTH;
UEV_PARSE("bit_depth_chroma_minus8", value, ps_bitstrm);
if(0 != value)
return IHEVCD_UNSUPPORTED_BIT_DEPTH;
UEV_PARSE("log2_max_pic_order_cnt_lsb_minus4", value, ps_bitstrm);
ps_sps->i1_log2_max_pic_order_cnt_lsb = value + 4;
BITS_PARSE("sps_sub_layer_ordering_info_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_sps_sub_layer_ordering_info_present_flag = value;
i = (ps_sps->i1_sps_sub_layer_ordering_info_present_flag ? 0 : (ps_sps->i1_sps_max_sub_layers - 1));
for(; i < ps_sps->i1_sps_max_sub_layers; i++)
{
UEV_PARSE("max_dec_pic_buffering", value, ps_bitstrm);
ps_sps->ai1_sps_max_dec_pic_buffering[i] = value + 1;
if(ps_sps->ai1_sps_max_dec_pic_buffering[i] > MAX_DPB_SIZE)
{
return IHEVCD_INVALID_PARAMETER;
}
UEV_PARSE("num_reorder_pics", value, ps_bitstrm);
ps_sps->ai1_sps_max_num_reorder_pics[i] = value;
if(ps_sps->ai1_sps_max_num_reorder_pics[i] > ps_sps->ai1_sps_max_dec_pic_buffering[i])
{
return IHEVCD_INVALID_PARAMETER;
}
UEV_PARSE("max_latency_increase", value, ps_bitstrm);
ps_sps->ai1_sps_max_latency_increase[i] = value;
}
UEV_PARSE("log2_min_coding_block_size_minus3", value, ps_bitstrm);
ps_sps->i1_log2_min_coding_block_size = value + 3;
UEV_PARSE("log2_diff_max_min_coding_block_size", value, ps_bitstrm);
ps_sps->i1_log2_diff_max_min_coding_block_size = value;
ctb_log2_size_y = ps_sps->i1_log2_min_coding_block_size + ps_sps->i1_log2_diff_max_min_coding_block_size;
UEV_PARSE("log2_min_transform_block_size_minus2", value, ps_bitstrm);
ps_sps->i1_log2_min_transform_block_size = value + 2;
UEV_PARSE("log2_diff_max_min_transform_block_size", value, ps_bitstrm);
ps_sps->i1_log2_diff_max_min_transform_block_size = value;
ps_sps->i1_log2_max_transform_block_size = ps_sps->i1_log2_min_transform_block_size +
ps_sps->i1_log2_diff_max_min_transform_block_size;
if ((ps_sps->i1_log2_max_transform_block_size < 0) ||
(ps_sps->i1_log2_max_transform_block_size > MIN(ctb_log2_size_y, 5)))
{
return IHEVCD_INVALID_PARAMETER;
}
ps_sps->i1_log2_ctb_size = ps_sps->i1_log2_min_coding_block_size +
ps_sps->i1_log2_diff_max_min_coding_block_size;
if((ps_sps->i1_log2_min_coding_block_size < 3) ||
(ps_sps->i1_log2_min_transform_block_size < 2) ||
(ps_sps->i1_log2_diff_max_min_transform_block_size < 0) ||
(ps_sps->i1_log2_max_transform_block_size > ps_sps->i1_log2_ctb_size) ||
(ps_sps->i1_log2_ctb_size < 4) ||
(ps_sps->i1_log2_ctb_size > 6))
{
return IHEVCD_INVALID_PARAMETER;
}
ps_sps->i1_log2_min_pcm_coding_block_size = 0;
ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = 0;
UEV_PARSE("max_transform_hierarchy_depth_inter", value, ps_bitstrm);
ps_sps->i1_max_transform_hierarchy_depth_inter = value;
UEV_PARSE("max_transform_hierarchy_depth_intra", value, ps_bitstrm);
ps_sps->i1_max_transform_hierarchy_depth_intra = value;
/* String has a d (enabled) in order to match with HM */
BITS_PARSE("scaling_list_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_scaling_list_enable_flag = value;
if(ps_sps->i1_scaling_list_enable_flag)
{
COPY_DEFAULT_SCALING_LIST(ps_sps->pi2_scaling_mat);
BITS_PARSE("sps_scaling_list_data_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_sps_scaling_list_data_present_flag = value;
if(ps_sps->i1_sps_scaling_list_data_present_flag)
ihevcd_scaling_list_data(ps_codec, ps_sps->pi2_scaling_mat);
}
else
{
COPY_FLAT_SCALING_LIST(ps_sps->pi2_scaling_mat);
}
/* String is asymmetric_motion_partitions_enabled_flag instead of amp_enabled_flag in order to match with HM */
BITS_PARSE("asymmetric_motion_partitions_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_amp_enabled_flag = value;
BITS_PARSE("sample_adaptive_offset_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_sample_adaptive_offset_enabled_flag = value;
BITS_PARSE("pcm_enabled_flag", value, ps_bitstrm, 1);
ps_sps->i1_pcm_enabled_flag = value;
if(ps_sps->i1_pcm_enabled_flag)
{
BITS_PARSE("pcm_sample_bit_depth_luma", value, ps_bitstrm, 4);
ps_sps->i1_pcm_sample_bit_depth_luma = value + 1;
BITS_PARSE("pcm_sample_bit_depth_chroma", value, ps_bitstrm, 4);
ps_sps->i1_pcm_sample_bit_depth_chroma = value + 1;
UEV_PARSE("log2_min_pcm_coding_block_size_minus3", value, ps_bitstrm);
ps_sps->i1_log2_min_pcm_coding_block_size = value + 3;
UEV_PARSE("log2_diff_max_min_pcm_coding_block_size", value, ps_bitstrm);
ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = value;
BITS_PARSE("pcm_loop_filter_disable_flag", value, ps_bitstrm, 1);
ps_sps->i1_pcm_loop_filter_disable_flag = value;
}
UEV_PARSE("num_short_term_ref_pic_sets", value, ps_bitstrm);
ps_sps->i1_num_short_term_ref_pic_sets = value;
ps_sps->i1_num_short_term_ref_pic_sets = CLIP3(ps_sps->i1_num_short_term_ref_pic_sets, 0, MAX_STREF_PICS_SPS);
for(i = 0; i < ps_sps->i1_num_short_term_ref_pic_sets; i++)
ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, i, &ps_sps->as_stref_picset[i]);
BITS_PARSE("long_term_ref_pics_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_long_term_ref_pics_present_flag = value;
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
UEV_PARSE("num_long_term_ref_pics_sps", value, ps_bitstrm);
ps_sps->i1_num_long_term_ref_pics_sps = value;
for(i = 0; i < ps_sps->i1_num_long_term_ref_pics_sps; i++)
{
BITS_PARSE("lt_ref_pic_poc_lsb_sps[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_sps->ai1_lt_ref_pic_poc_lsb_sps[i] = value;
BITS_PARSE("used_by_curr_pic_lt_sps_flag[ i ]", value, ps_bitstrm, 1);
ps_sps->ai1_used_by_curr_pic_lt_sps_flag[i] = value;
}
}
BITS_PARSE("sps_temporal_mvp_enable_flag", value, ps_bitstrm, 1);
ps_sps->i1_sps_temporal_mvp_enable_flag = value;
/* Print matches HM 8-2 */
BITS_PARSE("sps_strong_intra_smoothing_enable_flag", value, ps_bitstrm, 1);
ps_sps->i1_strong_intra_smoothing_enable_flag = value;
BITS_PARSE("vui_parameters_present_flag", value, ps_bitstrm, 1);
ps_sps->i1_vui_parameters_present_flag = value;
if(ps_sps->i1_vui_parameters_present_flag)
ihevcd_parse_vui_parameters(ps_bitstrm,
&ps_sps->s_vui_parameters,
ps_sps->i1_sps_max_sub_layers - 1);
BITS_PARSE("sps_extension_flag", value, ps_bitstrm, 1);
if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max)
{
return IHEVCD_INVALID_PARAMETER;
}
{
WORD32 numerator;
WORD32 ceil_offset;
ceil_offset = (1 << ps_sps->i1_log2_ctb_size) - 1;
numerator = ps_sps->i2_pic_width_in_luma_samples;
ps_sps->i2_pic_wd_in_ctb = ((numerator + ceil_offset) /
(1 << ps_sps->i1_log2_ctb_size));
numerator = ps_sps->i2_pic_height_in_luma_samples;
ps_sps->i2_pic_ht_in_ctb = ((numerator + ceil_offset) /
(1 << ps_sps->i1_log2_ctb_size));
ps_sps->i4_pic_size_in_ctb = ps_sps->i2_pic_ht_in_ctb *
ps_sps->i2_pic_wd_in_ctb;
if(0 == ps_codec->i4_sps_done)
ps_codec->s_parse.i4_next_ctb_indx = ps_sps->i4_pic_size_in_ctb;
numerator = ps_sps->i2_pic_width_in_luma_samples;
ps_sps->i2_pic_wd_in_min_cb = numerator /
(1 << ps_sps->i1_log2_min_coding_block_size);
numerator = ps_sps->i2_pic_height_in_luma_samples;
ps_sps->i2_pic_ht_in_min_cb = numerator /
(1 << ps_sps->i1_log2_min_coding_block_size);
}
if((0 != ps_codec->i4_first_pic_done) &&
((ps_codec->i4_wd != ps_sps->i2_pic_width_in_luma_samples) ||
(ps_codec->i4_ht != ps_sps->i2_pic_height_in_luma_samples)))
{
ps_codec->i4_reset_flag = 1;
return (IHEVCD_ERROR_T)IVD_RES_CHANGED;
}
/* Update display width and display height */
{
WORD32 disp_wd, disp_ht;
WORD32 crop_unit_x, crop_unit_y;
crop_unit_x = 1;
crop_unit_y = 1;
if(CHROMA_FMT_IDC_YUV420 == ps_sps->i1_chroma_format_idc)
{
crop_unit_x = 2;
crop_unit_y = 2;
}
disp_wd = ps_sps->i2_pic_width_in_luma_samples;
disp_wd -= ps_sps->i2_pic_crop_left_offset * crop_unit_x;
disp_wd -= ps_sps->i2_pic_crop_right_offset * crop_unit_x;
disp_ht = ps_sps->i2_pic_height_in_luma_samples;
disp_ht -= ps_sps->i2_pic_crop_top_offset * crop_unit_y;
disp_ht -= ps_sps->i2_pic_crop_bottom_offset * crop_unit_y;
if((0 >= disp_wd) || (0 >= disp_ht))
return IHEVCD_INVALID_PARAMETER;
ps_codec->i4_disp_wd = disp_wd;
ps_codec->i4_disp_ht = disp_ht;
ps_codec->i4_wd = ps_sps->i2_pic_width_in_luma_samples;
ps_codec->i4_ht = ps_sps->i2_pic_height_in_luma_samples;
{
WORD32 ref_strd;
ref_strd = ALIGN32(ps_sps->i2_pic_width_in_luma_samples + PAD_WD);
if(ps_codec->i4_strd < ref_strd)
{
ps_codec->i4_strd = ref_strd;
}
}
if(0 == ps_codec->i4_share_disp_buf)
{
if(ps_codec->i4_disp_strd < ps_codec->i4_disp_wd)
{
ps_codec->i4_disp_strd = ps_codec->i4_disp_wd;
}
}
else
{
if(ps_codec->i4_disp_strd < ps_codec->i4_strd)
{
ps_codec->i4_disp_strd = ps_codec->i4_strd;
}
}
}
ps_codec->i4_sps_done = 1;
return ret;
}
| 174,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: fr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
int ret;
uint16_t extracted_ethertype;
u_int dlci;
u_int addr_len;
uint16_t nlpid;
u_int hdr_len;
uint8_t flags[4];
ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length);
if (ret == -1)
goto trunc;
if (ret == 0) {
ND_PRINT((ndo, "Q.922, invalid address"));
return 0;
}
ND_TCHECK(p[addr_len]);
if (length < addr_len + 1)
goto trunc;
if (p[addr_len] != LLC_UI && dlci != 0) {
/*
* Let's figure out if we have Cisco-style encapsulation,
* with an Ethernet type (Cisco HDLC type?) following the
* address.
*/
if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) {
/* no Ethertype */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
} else {
extracted_ethertype = EXTRACT_16BITS(p+addr_len);
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci,
flags, extracted_ethertype);
if (ethertype_print(ndo, extracted_ethertype,
p+addr_len+ETHERTYPE_LEN,
length-addr_len-ETHERTYPE_LEN,
ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
else
return addr_len + 2;
}
}
ND_TCHECK(p[addr_len+1]);
if (length < addr_len + 2)
goto trunc;
if (p[addr_len + 1] == 0) {
/*
* Assume a pad byte after the control (UI) byte.
* A pad byte should only be used with 3-byte Q.922.
*/
if (addr_len != 3)
ND_PRINT((ndo, "Pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */;
} else {
/*
* Not a pad byte.
* A pad byte should be used with 3-byte Q.922.
*/
if (addr_len == 3)
ND_PRINT((ndo, "No pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */;
}
ND_TCHECK(p[hdr_len - 1]);
if (length < hdr_len)
goto trunc;
nlpid = p[hdr_len - 1];
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid);
p += hdr_len;
length -= hdr_len;
switch (nlpid) {
case NLPID_IP:
ip_print(ndo, p, length);
break;
case NLPID_IP6:
ip6_print(ndo, p, length);
break;
case NLPID_CLNP:
case NLPID_ESIS:
case NLPID_ISIS:
isoclns_print(ndo, p - 1, length + 1, ndo->ndo_snapend - p + 1); /* OSI printers need the NLPID field */
break;
case NLPID_SNAP:
if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) {
/* ether_type not known, print raw packet */
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, hdr_len,
dlci, flags, nlpid);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p - hdr_len, length + hdr_len);
}
break;
case NLPID_Q933:
q933_print(ndo, p, length);
break;
case NLPID_MFR:
frf15_print(ndo, p, length);
break;
case NLPID_PPP:
ppp_print(ndo, p, length);
break;
default:
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, addr_len,
dlci, flags, nlpid);
if (!ndo->ndo_xflag)
ND_DEFAULTPRINT(p, length);
}
return hdr_len;
trunc:
ND_PRINT((ndo, "[|fr]"));
return 0;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | fr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
int ret;
uint16_t extracted_ethertype;
u_int dlci;
u_int addr_len;
uint16_t nlpid;
u_int hdr_len;
uint8_t flags[4];
ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length);
if (ret == -1)
goto trunc;
if (ret == 0) {
ND_PRINT((ndo, "Q.922, invalid address"));
return 0;
}
ND_TCHECK(p[addr_len]);
if (length < addr_len + 1)
goto trunc;
if (p[addr_len] != LLC_UI && dlci != 0) {
/*
* Let's figure out if we have Cisco-style encapsulation,
* with an Ethernet type (Cisco HDLC type?) following the
* address.
*/
if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) {
/* no Ethertype */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
} else {
extracted_ethertype = EXTRACT_16BITS(p+addr_len);
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci,
flags, extracted_ethertype);
if (ethertype_print(ndo, extracted_ethertype,
p+addr_len+ETHERTYPE_LEN,
length-addr_len-ETHERTYPE_LEN,
ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
else
return addr_len + 2;
}
}
ND_TCHECK(p[addr_len+1]);
if (length < addr_len + 2)
goto trunc;
if (p[addr_len + 1] == 0) {
/*
* Assume a pad byte after the control (UI) byte.
* A pad byte should only be used with 3-byte Q.922.
*/
if (addr_len != 3)
ND_PRINT((ndo, "Pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */;
} else {
/*
* Not a pad byte.
* A pad byte should be used with 3-byte Q.922.
*/
if (addr_len == 3)
ND_PRINT((ndo, "No pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */;
}
ND_TCHECK(p[hdr_len - 1]);
if (length < hdr_len)
goto trunc;
nlpid = p[hdr_len - 1];
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid);
p += hdr_len;
length -= hdr_len;
switch (nlpid) {
case NLPID_IP:
ip_print(ndo, p, length);
break;
case NLPID_IP6:
ip6_print(ndo, p, length);
break;
case NLPID_CLNP:
case NLPID_ESIS:
case NLPID_ISIS:
isoclns_print(ndo, p - 1, length + 1); /* OSI printers need the NLPID field */
break;
case NLPID_SNAP:
if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) {
/* ether_type not known, print raw packet */
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, hdr_len,
dlci, flags, nlpid);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p - hdr_len, length + hdr_len);
}
break;
case NLPID_Q933:
q933_print(ndo, p, length);
break;
case NLPID_MFR:
frf15_print(ndo, p, length);
break;
case NLPID_PPP:
ppp_print(ndo, p, length);
break;
default:
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, addr_len,
dlci, flags, nlpid);
if (!ndo->ndo_xflag)
ND_DEFAULTPRINT(p, length);
}
return hdr_len;
trunc:
ND_PRINT((ndo, "[|fr]"));
return 0;
}
| 167,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long writeaccess,
unsigned long textaccess, unsigned long address)
{
struct task_struct *tsk;
struct mm_struct *mm;
struct vm_area_struct * vma;
const struct exception_table_entry *fixup;
pte_t *pte;
int fault;
/* SIM
* Note this is now called with interrupts still disabled
* This is to cope with being called for a missing IO port
* address with interrupts disabled. This should be fixed as
* soon as we have a better 'fast path' miss handler.
*
* Plus take care how you try and debug this stuff.
* For example, writing debug data to a port which you
* have just faulted on is not going to work.
*/
tsk = current;
mm = tsk->mm;
/* Not an IO address, so reenable interrupts */
local_irq_enable();
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto no_context;
/* TLB misses upon some cache flushes get done under cli() */
down_read(&mm->mmap_sem);
vma = find_vma(mm, address);
if (!vma) {
#ifdef DEBUG_FAULT
print_task(tsk);
printk("%s:%d fault, address is 0x%08x PC %016Lx textaccess %d writeaccess %d\n",
__func__, __LINE__,
address,regs->pc,textaccess,writeaccess);
show_regs(regs);
#endif
goto bad_area;
}
if (vma->vm_start <= address) {
goto good_area;
}
if (!(vma->vm_flags & VM_GROWSDOWN)) {
#ifdef DEBUG_FAULT
print_task(tsk);
printk("%s:%d fault, address is 0x%08x PC %016Lx textaccess %d writeaccess %d\n",
__func__, __LINE__,
address,regs->pc,textaccess,writeaccess);
show_regs(regs);
print_vma(vma);
#endif
goto bad_area;
}
if (expand_stack(vma, address)) {
#ifdef DEBUG_FAULT
print_task(tsk);
printk("%s:%d fault, address is 0x%08x PC %016Lx textaccess %d writeaccess %d\n",
__func__, __LINE__,
address,regs->pc,textaccess,writeaccess);
show_regs(regs);
#endif
goto bad_area;
}
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
if (textaccess) {
if (!(vma->vm_flags & VM_EXEC))
goto bad_area;
} else {
if (writeaccess) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
if (!(vma->vm_flags & VM_READ))
goto bad_area;
}
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, writeaccess ? FAULT_FLAG_WRITE : 0);
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,
regs, address);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,
regs, address);
}
/* If we get here, the page fault has been handled. Do the TLB refill
now from the newly-setup PTE, to avoid having to fault again right
away on the same instruction. */
pte = lookup_pte (mm, address);
if (!pte) {
/* From empirical evidence, we can get here, due to
!pte_present(pte). (e.g. if a swap-in occurs, and the page
is swapped back out again before the process that wanted it
gets rescheduled?) */
goto no_pte;
}
__do_tlb_refill(address, textaccess, pte);
no_pte:
up_read(&mm->mmap_sem);
return;
/*
* Something tried to access memory that isn't in our memory map..
* Fix it, but check if it's kernel or user first..
*/
bad_area:
#ifdef DEBUG_FAULT
printk("fault:bad area\n");
#endif
up_read(&mm->mmap_sem);
if (user_mode(regs)) {
static int count=0;
siginfo_t info;
if (count < 4) {
/* This is really to help debug faults when starting
* usermode, so only need a few */
count++;
printk("user mode bad_area address=%08lx pid=%d (%s) pc=%08lx\n",
address, task_pid_nr(current), current->comm,
(unsigned long) regs->pc);
#if 0
show_regs(regs);
#endif
}
if (is_global_init(tsk)) {
panic("INIT had user mode bad_area\n");
}
tsk->thread.address = address;
tsk->thread.error_code = writeaccess;
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_addr = (void *) address;
force_sig_info(SIGSEGV, &info, tsk);
return;
}
no_context:
#ifdef DEBUG_FAULT
printk("fault:No context\n");
#endif
/* Are we prepared to handle this kernel fault? */
fixup = search_exception_tables(regs->pc);
if (fixup) {
regs->pc = fixup->fixup;
return;
}
/*
* Oops. The kernel tried to access some bad page. We'll have to
* terminate things with extreme prejudice.
*
*/
if (address < PAGE_SIZE)
printk(KERN_ALERT "Unable to handle kernel NULL pointer dereference");
else
printk(KERN_ALERT "Unable to handle kernel paging request");
printk(" at virtual address %08lx\n", address);
printk(KERN_ALERT "pc = %08Lx%08Lx\n", regs->pc >> 32, regs->pc & 0xffffffff);
die("Oops", regs, writeaccess);
do_exit(SIGKILL);
/*
* We ran out of memory, or some other thing happened to us that made
* us unable to handle the page fault gracefully.
*/
out_of_memory:
up_read(&mm->mmap_sem);
if (!user_mode(regs))
goto no_context;
pagefault_out_of_memory();
return;
do_sigbus:
printk("fault:Do sigbus\n");
up_read(&mm->mmap_sem);
/*
* Send a sigbus, regardless of whether we were in kernel
* or user mode.
*/
tsk->thread.address = address;
tsk->thread.error_code = writeaccess;
tsk->thread.trap_no = 14;
force_sig(SIGBUS, tsk);
/* Kernel mode? Handle exceptions or die */
if (!user_mode(regs))
goto no_context;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long writeaccess,
unsigned long textaccess, unsigned long address)
{
struct task_struct *tsk;
struct mm_struct *mm;
struct vm_area_struct * vma;
const struct exception_table_entry *fixup;
pte_t *pte;
int fault;
/* SIM
* Note this is now called with interrupts still disabled
* This is to cope with being called for a missing IO port
* address with interrupts disabled. This should be fixed as
* soon as we have a better 'fast path' miss handler.
*
* Plus take care how you try and debug this stuff.
* For example, writing debug data to a port which you
* have just faulted on is not going to work.
*/
tsk = current;
mm = tsk->mm;
/* Not an IO address, so reenable interrupts */
local_irq_enable();
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto no_context;
/* TLB misses upon some cache flushes get done under cli() */
down_read(&mm->mmap_sem);
vma = find_vma(mm, address);
if (!vma) {
#ifdef DEBUG_FAULT
print_task(tsk);
printk("%s:%d fault, address is 0x%08x PC %016Lx textaccess %d writeaccess %d\n",
__func__, __LINE__,
address,regs->pc,textaccess,writeaccess);
show_regs(regs);
#endif
goto bad_area;
}
if (vma->vm_start <= address) {
goto good_area;
}
if (!(vma->vm_flags & VM_GROWSDOWN)) {
#ifdef DEBUG_FAULT
print_task(tsk);
printk("%s:%d fault, address is 0x%08x PC %016Lx textaccess %d writeaccess %d\n",
__func__, __LINE__,
address,regs->pc,textaccess,writeaccess);
show_regs(regs);
print_vma(vma);
#endif
goto bad_area;
}
if (expand_stack(vma, address)) {
#ifdef DEBUG_FAULT
print_task(tsk);
printk("%s:%d fault, address is 0x%08x PC %016Lx textaccess %d writeaccess %d\n",
__func__, __LINE__,
address,regs->pc,textaccess,writeaccess);
show_regs(regs);
#endif
goto bad_area;
}
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
if (textaccess) {
if (!(vma->vm_flags & VM_EXEC))
goto bad_area;
} else {
if (writeaccess) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
if (!(vma->vm_flags & VM_READ))
goto bad_area;
}
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, writeaccess ? FAULT_FLAG_WRITE : 0);
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1,
regs, address);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1,
regs, address);
}
/* If we get here, the page fault has been handled. Do the TLB refill
now from the newly-setup PTE, to avoid having to fault again right
away on the same instruction. */
pte = lookup_pte (mm, address);
if (!pte) {
/* From empirical evidence, we can get here, due to
!pte_present(pte). (e.g. if a swap-in occurs, and the page
is swapped back out again before the process that wanted it
gets rescheduled?) */
goto no_pte;
}
__do_tlb_refill(address, textaccess, pte);
no_pte:
up_read(&mm->mmap_sem);
return;
/*
* Something tried to access memory that isn't in our memory map..
* Fix it, but check if it's kernel or user first..
*/
bad_area:
#ifdef DEBUG_FAULT
printk("fault:bad area\n");
#endif
up_read(&mm->mmap_sem);
if (user_mode(regs)) {
static int count=0;
siginfo_t info;
if (count < 4) {
/* This is really to help debug faults when starting
* usermode, so only need a few */
count++;
printk("user mode bad_area address=%08lx pid=%d (%s) pc=%08lx\n",
address, task_pid_nr(current), current->comm,
(unsigned long) regs->pc);
#if 0
show_regs(regs);
#endif
}
if (is_global_init(tsk)) {
panic("INIT had user mode bad_area\n");
}
tsk->thread.address = address;
tsk->thread.error_code = writeaccess;
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_addr = (void *) address;
force_sig_info(SIGSEGV, &info, tsk);
return;
}
no_context:
#ifdef DEBUG_FAULT
printk("fault:No context\n");
#endif
/* Are we prepared to handle this kernel fault? */
fixup = search_exception_tables(regs->pc);
if (fixup) {
regs->pc = fixup->fixup;
return;
}
/*
* Oops. The kernel tried to access some bad page. We'll have to
* terminate things with extreme prejudice.
*
*/
if (address < PAGE_SIZE)
printk(KERN_ALERT "Unable to handle kernel NULL pointer dereference");
else
printk(KERN_ALERT "Unable to handle kernel paging request");
printk(" at virtual address %08lx\n", address);
printk(KERN_ALERT "pc = %08Lx%08Lx\n", regs->pc >> 32, regs->pc & 0xffffffff);
die("Oops", regs, writeaccess);
do_exit(SIGKILL);
/*
* We ran out of memory, or some other thing happened to us that made
* us unable to handle the page fault gracefully.
*/
out_of_memory:
up_read(&mm->mmap_sem);
if (!user_mode(regs))
goto no_context;
pagefault_out_of_memory();
return;
do_sigbus:
printk("fault:Do sigbus\n");
up_read(&mm->mmap_sem);
/*
* Send a sigbus, regardless of whether we were in kernel
* or user mode.
*/
tsk->thread.address = address;
tsk->thread.error_code = writeaccess;
tsk->thread.trap_no = 14;
force_sig(SIGBUS, tsk);
/* Kernel mode? Handle exceptions or die */
if (!user_mode(regs))
goto no_context;
}
| 165,803 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btif_config_flush(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
alarm_cancel(alarm_timer);
pthread_mutex_lock(&lock);
config_save(config, CONFIG_FILE_PATH);
pthread_mutex_unlock(&lock);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119 | void btif_config_flush(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
alarm_cancel(alarm_timer);
btif_config_write();
}
| 173,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool BlockEntry::EOS() const
{
return (GetKind() == kBlockEOS);
}
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 BlockEntry::EOS() const
| 174,271 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetSpeechSynthesisLibrary(
SpeechSynthesisLibrary* library, bool own) {
library_->speech_synthesis_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::SetSpeechSynthesisLibrary(
| 170,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: process_demand_active(STREAM s)
{
uint8 type;
uint16 len_src_descriptor, len_combined_caps;
/* at this point we need to ensure that we have ui created */
rd_create_ui();
in_uint32_le(s, g_rdp_shareid);
in_uint16_le(s, len_src_descriptor);
in_uint16_le(s, len_combined_caps);
in_uint8s(s, len_src_descriptor);
logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid);
rdp_process_server_caps(s, len_combined_caps);
rdp_send_confirm_active();
rdp_send_synchronise();
rdp_send_control(RDP_CTL_COOPERATE);
rdp_send_control(RDP_CTL_REQUEST_CONTROL);
rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */
rdp_recv(&type); /* RDP_CTL_COOPERATE */
rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */
rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,
g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);
if (g_rdp_version >= RDP_V5)
{
rdp_enum_bmpcache2();
rdp_send_fonts(3);
}
else
{
rdp_send_fonts(1);
rdp_send_fonts(2);
}
rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */
reset_order_state();
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | process_demand_active(STREAM s)
{
uint8 type;
uint16 len_src_descriptor, len_combined_caps;
struct stream packet = *s;
/* at this point we need to ensure that we have ui created */
rd_create_ui();
in_uint32_le(s, g_rdp_shareid);
in_uint16_le(s, len_src_descriptor);
in_uint16_le(s, len_combined_caps);
if (!s_check_rem(s, len_src_descriptor))
{
rdp_protocol_error("rdp_demand_active(), consume of source descriptor from stream would overrun", &packet);
}
in_uint8s(s, len_src_descriptor);
logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid);
rdp_process_server_caps(s, len_combined_caps);
rdp_send_confirm_active();
rdp_send_synchronise();
rdp_send_control(RDP_CTL_COOPERATE);
rdp_send_control(RDP_CTL_REQUEST_CONTROL);
rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */
rdp_recv(&type); /* RDP_CTL_COOPERATE */
rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */
rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,
g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);
if (g_rdp_version >= RDP_V5)
{
rdp_enum_bmpcache2();
rdp_send_fonts(3);
}
else
{
rdp_send_fonts(1);
rdp_send_fonts(2);
}
rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */
reset_order_state();
}
| 169,803 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
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 <[email protected]>
CWE ID: CWE-119 | int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
if(dtls1_process_buffered_records(s)<0)
return -1;
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
if(dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num)<0)
return -1;
dtls1_record_bitmap_update(s, bitmap);/* Mark receipt of record. */
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
dtls1_record_bitmap_update(s, bitmap);/* Mark receipt of record. */
return(1);
}
| 166,746 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AllocateDataSet(cmsIT8* it8)
{
TABLE* t = GetTable(it8);
if (t -> Data) return; // Already allocated
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
}
}
Commit Message: Upgrade Visual studio 2017 15.8
- Upgrade to 15.8
- Add check on CGATS memory allocation (thanks to Quang Nguyen for
pointing out this)
CWE ID: CWE-190 | void AllocateDataSet(cmsIT8* it8)
{
TABLE* t = GetTable(it8);
if (t -> Data) return; // Already allocated
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)
{
SynError(it8, "AllocateDataSet: too much data");
}
else {
t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
}
}
}
| 169,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
char *ksep, *vsep, *val;
size_t klen, vlen;
/* FIXME: string-size_t */
unsigned int new_vlen;
if (var->ptr >= var->end) {
return 0;
}
vsep = memchr(var->ptr, '&', var->end - var->ptr);
if (!vsep) {
if (!eof) {
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
return 1;
}
Commit Message: Fix bug #73807
CWE ID: CWE-400 | static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
char *start, *ksep, *vsep, *val;
size_t klen, vlen;
/* FIXME: string-size_t */
unsigned int new_vlen;
if (var->ptr >= var->end) {
return 0;
}
start = var->ptr + var->already_scanned;
vsep = memchr(start, '&', var->end - start);
if (!vsep) {
if (!eof) {
var->already_scanned = var->end - var->ptr;
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
var->already_scanned = 0;
return 1;
}
| 168,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags, uint16_t *notecount)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (*notecount == 0)
return 0;
--*notecount;
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & FLAGS_DID_OS_NOTE) == 0) {
if (do_os_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
if (do_bid_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
if (do_pax_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_CORE) == 0) {
if (do_core_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz))
return size;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
return size;
case NT_NETBSD_MARCH:
if (*flags & FLAGS_DID_NETBSD_MARCH)
return size;
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (*flags & FLAGS_DID_NETBSD_CMODEL)
return size;
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
return size;
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
return offset;
}
Commit Message: Limit string printing to 100 chars, and add flags I forgot in the previous
commit.
CWE ID: CWE-399 | donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags, uint16_t *notecount)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (*notecount == 0)
return 0;
--*notecount;
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & FLAGS_DID_OS_NOTE) == 0) {
if (do_os_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
if (do_bid_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
if (do_pax_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_CORE) == 0) {
if (do_core_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz))
return size;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
if (descsz > 100)
descsz = 100;
switch (xnh_type) {
case NT_NETBSD_VERSION:
return size;
case NT_NETBSD_MARCH:
if (*flags & FLAGS_DID_NETBSD_MARCH)
return size;
*flags |= FLAGS_DID_NETBSD_MARCH;
if (file_printf(ms, ", compiled for: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (*flags & FLAGS_DID_NETBSD_CMODEL)
return size;
*flags |= FLAGS_DID_NETBSD_CMODEL;
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
return size;
*flags |= FLAGS_DID_NETBSD_UNKNOWN;
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
return offset;
}
| 166,772 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyMono8(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyMono8(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
}
}
| 174,017 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) {
int i;
memset(cfg, 0, sizeof(cfg_t));
cfg->debug_file = stderr;
for (i = 0; i < argc; i++) {
if (strncmp(argv[i], "max_devices=", 12) == 0)
sscanf(argv[i], "max_devices=%u", &cfg->max_devs);
if (strcmp(argv[i], "manual") == 0)
cfg->manual = 1;
if (strcmp(argv[i], "debug") == 0)
cfg->debug = 1;
if (strcmp(argv[i], "nouserok") == 0)
cfg->nouserok = 1;
if (strcmp(argv[i], "openasuser") == 0)
cfg->openasuser = 1;
if (strcmp(argv[i], "alwaysok") == 0)
cfg->alwaysok = 1;
if (strcmp(argv[i], "interactive") == 0)
cfg->interactive = 1;
if (strcmp(argv[i], "cue") == 0)
cfg->cue = 1;
if (strcmp(argv[i], "nodetect") == 0)
cfg->nodetect = 1;
if (strncmp(argv[i], "authfile=", 9) == 0)
cfg->auth_file = argv[i] + 9;
if (strncmp(argv[i], "authpending_file=", 17) == 0)
cfg->authpending_file = argv[i] + 17;
if (strncmp(argv[i], "origin=", 7) == 0)
cfg->origin = argv[i] + 7;
if (strncmp(argv[i], "appid=", 6) == 0)
cfg->appid = argv[i] + 6;
if (strncmp(argv[i], "prompt=", 7) == 0)
cfg->prompt = argv[i] + 7;
if (strncmp (argv[i], "debug_file=", 11) == 0) {
const char *filename = argv[i] + 11;
if(strncmp (filename, "stdout", 6) == 0) {
cfg->debug_file = stdout;
}
else if(strncmp (filename, "stderr", 6) == 0) {
cfg->debug_file = stderr;
}
else if( strncmp (filename, "syslog", 6) == 0) {
cfg->debug_file = (FILE *)-1;
}
else {
struct stat st;
FILE *file;
if(lstat(filename, &st) == 0) {
if(S_ISREG(st.st_mode)) {
file = fopen(filename, "a");
if(file != NULL) {
cfg->debug_file = file;
}
}
}
}
}
}
if (cfg->debug) {
D(cfg->debug_file, "called.");
D(cfg->debug_file, "flags %d argc %d", flags, argc);
for (i = 0; i < argc; i++) {
D(cfg->debug_file, "argv[%d]=%s", i, argv[i]);
}
D(cfg->debug_file, "max_devices=%d", cfg->max_devs);
D(cfg->debug_file, "debug=%d", cfg->debug);
D(cfg->debug_file, "interactive=%d", cfg->interactive);
D(cfg->debug_file, "cue=%d", cfg->cue);
D(cfg->debug_file, "nodetect=%d", cfg->nodetect);
D(cfg->debug_file, "manual=%d", cfg->manual);
D(cfg->debug_file, "nouserok=%d", cfg->nouserok);
D(cfg->debug_file, "openasuser=%d", cfg->openasuser);
D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok);
D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)");
D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)");
D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)");
D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)");
D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)");
}
}
Commit Message: Do not leak file descriptor when doing exec
When opening a custom debug file, the descriptor would stay
open when calling exec and leak to the child process.
Make sure all files are opened with close-on-exec.
This fixes CVE-2019-12210.
Thanks to Matthias Gerstner of the SUSE Security Team for reporting
the issue.
CWE ID: CWE-200 | static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) {
struct stat st;
FILE *file = NULL;
int fd = -1;
int i;
memset(cfg, 0, sizeof(cfg_t));
cfg->debug_file = stderr;
for (i = 0; i < argc; i++) {
if (strncmp(argv[i], "max_devices=", 12) == 0)
sscanf(argv[i], "max_devices=%u", &cfg->max_devs);
if (strcmp(argv[i], "manual") == 0)
cfg->manual = 1;
if (strcmp(argv[i], "debug") == 0)
cfg->debug = 1;
if (strcmp(argv[i], "nouserok") == 0)
cfg->nouserok = 1;
if (strcmp(argv[i], "openasuser") == 0)
cfg->openasuser = 1;
if (strcmp(argv[i], "alwaysok") == 0)
cfg->alwaysok = 1;
if (strcmp(argv[i], "interactive") == 0)
cfg->interactive = 1;
if (strcmp(argv[i], "cue") == 0)
cfg->cue = 1;
if (strcmp(argv[i], "nodetect") == 0)
cfg->nodetect = 1;
if (strncmp(argv[i], "authfile=", 9) == 0)
cfg->auth_file = argv[i] + 9;
if (strncmp(argv[i], "authpending_file=", 17) == 0)
cfg->authpending_file = argv[i] + 17;
if (strncmp(argv[i], "origin=", 7) == 0)
cfg->origin = argv[i] + 7;
if (strncmp(argv[i], "appid=", 6) == 0)
cfg->appid = argv[i] + 6;
if (strncmp(argv[i], "prompt=", 7) == 0)
cfg->prompt = argv[i] + 7;
if (strncmp (argv[i], "debug_file=", 11) == 0) {
const char *filename = argv[i] + 11;
if(strncmp (filename, "stdout", 6) == 0) {
cfg->debug_file = stdout;
}
else if(strncmp (filename, "stderr", 6) == 0) {
cfg->debug_file = stderr;
}
else if( strncmp (filename, "syslog", 6) == 0) {
cfg->debug_file = (FILE *)-1;
}
else {
fd = open(filename, O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW | O_NOCTTY);
if (fd >= 0 && (fstat(fd, &st) == 0) && S_ISREG(st.st_mode)) {
file = fdopen(fd, "a");
if(file != NULL) {
cfg->debug_file = file;
cfg->is_custom_debug_file = 1;
file = NULL;
fd = -1;
}
}
}
}
}
if (cfg->debug) {
D(cfg->debug_file, "called.");
D(cfg->debug_file, "flags %d argc %d", flags, argc);
for (i = 0; i < argc; i++) {
D(cfg->debug_file, "argv[%d]=%s", i, argv[i]);
}
D(cfg->debug_file, "max_devices=%d", cfg->max_devs);
D(cfg->debug_file, "debug=%d", cfg->debug);
D(cfg->debug_file, "interactive=%d", cfg->interactive);
D(cfg->debug_file, "cue=%d", cfg->cue);
D(cfg->debug_file, "nodetect=%d", cfg->nodetect);
D(cfg->debug_file, "manual=%d", cfg->manual);
D(cfg->debug_file, "nouserok=%d", cfg->nouserok);
D(cfg->debug_file, "openasuser=%d", cfg->openasuser);
D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok);
D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)");
D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)");
D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)");
D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)");
D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)");
}
if (fd != -1)
close(fd);
if (file != NULL)
fclose(file);
}
| 169,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[])
{
FILE *fp_rd = stdin;
FILE *fp_wr = stdout;
FILE *fp_al = NULL;
BOOL raw = TRUE;
BOOL alpha = FALSE;
int argi;
for (argi = 1; argi < argc; argi++)
{
if (argv[argi][0] == '-')
{
switch (argv[argi][1])
{
case 'n':
raw = FALSE;
break;
case 'r':
raw = TRUE;
break;
case 'a':
alpha = TRUE;
argi++;
if ((fp_al = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]);
exit (1);
}
break;
case 'h':
case '?':
usage();
exit(0);
break;
default:
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unknown option %s\n", argv[argi]);
usage();
exit(1);
break;
} /* end switch */
}
else if (fp_rd == stdin)
{
if ((fp_rd = fopen (argv[argi], "rb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: file %s does not exist\n", argv[argi]);
exit (1);
}
}
else if (fp_wr == stdout)
{
if ((fp_wr = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: can not create file %s\n", argv[argi]);
exit (1);
}
}
else
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: too many parameters\n");
usage();
exit(1);
}
} /* end for */
#ifdef __TURBOC__
/* set stdin/stdout if required to binary */
if (fp_rd == stdin)
{
setmode (STDIN, O_BINARY);
}
if ((raw) && (fp_wr == stdout))
{
setmode (STDOUT, O_BINARY);
}
#endif
/* call the conversion program itself */
if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n");
exit(1);
}
/* close input file */
fclose (fp_rd);
/* close output file */
fclose (fp_wr);
/* close alpha file */
if (alpha)
fclose (fp_al);
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int main(int argc, char *argv[])
{
FILE *fp_rd = stdin;
FILE *fp_wr = stdout;
FILE *fp_al = NULL;
BOOL raw = TRUE;
BOOL alpha = FALSE;
int argi;
for (argi = 1; argi < argc; argi++)
{
if (argv[argi][0] == '-')
{
switch (argv[argi][1])
{
case 'n':
raw = FALSE;
break;
case 'r':
raw = TRUE;
break;
case 'a':
alpha = TRUE;
argi++;
if ((fp_al = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, "Error: can not create alpha-channel file %s\n",
argv[argi]);
exit (1);
}
break;
case 'h':
case '?':
usage();
exit(0);
break;
default:
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unknown option %s\n", argv[argi]);
usage();
exit(1);
break;
} /* end switch */
}
else if (fp_rd == stdin)
{
if ((fp_rd = fopen (argv[argi], "rb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: file %s does not exist\n", argv[argi]);
exit (1);
}
}
else if (fp_wr == stdout)
{
if ((fp_wr = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: can not create file %s\n", argv[argi]);
exit (1);
}
}
else
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: too many parameters\n");
usage();
exit(1);
}
} /* end for */
#ifdef __TURBOC__
/* set stdin/stdout if required to binary */
if (fp_rd == stdin)
{
setmode (STDIN, O_BINARY);
}
if ((raw) && (fp_wr == stdout))
{
setmode (STDOUT, O_BINARY);
}
#endif
/* call the conversion program itself */
if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n");
exit(1);
}
/* close input file */
fclose (fp_rd);
/* close output file */
fclose (fp_wr);
/* close alpha file */
if (alpha)
fclose (fp_al);
return 0;
}
| 173,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EBMLHeader::Init()
{
m_version = 1;
m_readVersion = 1;
m_maxIdLength = 4;
m_maxSizeLength = 8;
if (m_docType)
{
delete[] m_docType;
m_docType = NULL;
}
m_docTypeVersion = 1;
m_docTypeReadVersion = 1;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void EBMLHeader::Init()
long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) {
assert(pReader);
long long total, available;
| 174,389 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);
object->u.dir.index++;
do {
spl_filesystem_dir_read(object TSRMLS_CC);
} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));
if (object->file_name) {
efree(object->file_name);
object->file_name = NULL;
}
if (iterator->current) {
zval_ptr_dtor(&iterator->current);
iterator->current = NULL;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);
object->u.dir.index++;
do {
spl_filesystem_dir_read(object TSRMLS_CC);
} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));
if (object->file_name) {
efree(object->file_name);
object->file_name = NULL;
}
if (iterator->current) {
zval_ptr_dtor(&iterator->current);
iterator->current = NULL;
}
}
| 167,087 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NaClProcessHost::ReplyToRenderer(
const IPC::ChannelHandle& channel_handle) {
std::vector<nacl::FileDescriptor> handles_for_renderer;
for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
#if defined(OS_WIN)
HANDLE handle_in_renderer;
if (!DuplicateHandle(base::GetCurrentProcessHandle(),
reinterpret_cast<HANDLE>(
internal_->sockets_for_renderer[i]),
chrome_render_message_filter_->peer_handle(),
&handle_in_renderer,
0, // Unused given DUPLICATE_SAME_ACCESS.
FALSE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
DLOG(ERROR) << "DuplicateHandle() failed";
return false;
}
handles_for_renderer.push_back(
reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
#else
nacl::FileDescriptor imc_handle;
imc_handle.fd = internal_->sockets_for_renderer[i];
imc_handle.auto_close = true;
handles_for_renderer.push_back(imc_handle);
#endif
}
#if defined(OS_WIN)
if (RunningOnWOW64()) {
if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
DLOG(ERROR) << "Failed to add NaCl process PID";
return false;
}
}
#endif
ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
reply_msg_, handles_for_renderer, channel_handle);
chrome_render_message_filter_->Send(reply_msg_);
chrome_render_message_filter_ = NULL;
reply_msg_ = NULL;
internal_->sockets_for_renderer.clear();
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool NaClProcessHost::ReplyToRenderer(
bool NaClProcessHost::ReplyToRenderer() {
std::vector<nacl::FileDescriptor> handles_for_renderer;
for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
#if defined(OS_WIN)
HANDLE handle_in_renderer;
if (!DuplicateHandle(base::GetCurrentProcessHandle(),
reinterpret_cast<HANDLE>(
internal_->sockets_for_renderer[i]),
chrome_render_message_filter_->peer_handle(),
&handle_in_renderer,
0, // Unused given DUPLICATE_SAME_ACCESS.
FALSE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
DLOG(ERROR) << "DuplicateHandle() failed";
return false;
}
handles_for_renderer.push_back(
reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
#else
nacl::FileDescriptor imc_handle;
imc_handle.fd = internal_->sockets_for_renderer[i];
imc_handle.auto_close = true;
handles_for_renderer.push_back(imc_handle);
#endif
}
#if defined(OS_WIN)
if (RunningOnWOW64()) {
if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
DLOG(ERROR) << "Failed to add NaCl process PID";
return false;
}
}
#endif
ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
reply_msg_, handles_for_renderer);
chrome_render_message_filter_->Send(reply_msg_);
chrome_render_message_filter_ = NULL;
reply_msg_ = NULL;
internal_->sockets_for_renderer.clear();
return true;
}
| 170,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */
{
zval tmp;
intern->type = SPL_FS_FILE;
php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC);
if (Z_LVAL(tmp)) {
intern->u.file.open_mode = NULL;
intern->file_name = NULL;
zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories");
return FAILURE;
}
intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0);
intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context);
if (!intern->file_name_len || !intern->u.file.stream) {
if (!EG(exception)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : "");
}
intern->file_name = NULL; /* until here it is not a copy */
intern->u.file.open_mode = NULL;
return FAILURE;
}
if (intern->u.file.zcontext) {
zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext));
}
if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) {
intern->file_name_len--;
}
intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path));
intern->file_name = estrndup(intern->file_name, intern->file_name_len);
intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len);
/* avoid reference counting in debug mode, thus do it manually */
ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream));
Z_SET_REFCOUNT(intern->u.file.zresource, 1);
intern->u.file.delimiter = ',';
intern->u.file.enclosure = '"';
intern->u.file.escape = '\\';
zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr);
return SUCCESS;
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */
{
zval tmp;
intern->type = SPL_FS_FILE;
php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC);
if (Z_LVAL(tmp)) {
intern->u.file.open_mode = NULL;
intern->file_name = NULL;
zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories");
return FAILURE;
}
intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0);
intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context);
if (!intern->file_name_len || !intern->u.file.stream) {
if (!EG(exception)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : "");
}
intern->file_name = NULL; /* until here it is not a copy */
intern->u.file.open_mode = NULL;
return FAILURE;
}
if (intern->u.file.zcontext) {
zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext));
}
if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) {
intern->file_name_len--;
}
intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path));
intern->file_name = estrndup(intern->file_name, intern->file_name_len);
intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len);
/* avoid reference counting in debug mode, thus do it manually */
ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream));
Z_SET_REFCOUNT(intern->u.file.zresource, 1);
intern->u.file.delimiter = ',';
intern->u.file.enclosure = '"';
intern->u.file.escape = '\\';
zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr);
return SUCCESS;
} /* }}} */
| 167,075 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ParamTraits<AudioParameters>::Read(const Message* m,
PickleIterator* iter,
AudioParameters* r) {
int format, channel_layout, sample_rate, bits_per_sample,
frames_per_buffer, channels;
if (!m->ReadInt(iter, &format) ||
!m->ReadInt(iter, &channel_layout) ||
!m->ReadInt(iter, &sample_rate) ||
!m->ReadInt(iter, &bits_per_sample) ||
!m->ReadInt(iter, &frames_per_buffer) ||
!m->ReadInt(iter, &channels))
return false;
r->Reset(static_cast<AudioParameters::Format>(format),
static_cast<ChannelLayout>(channel_layout),
sample_rate, bits_per_sample, frames_per_buffer);
return true;
}
Commit Message: Improve validation when creating audio streams.
BUG=166795
Review URL: https://codereview.chromium.org/11647012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | bool ParamTraits<AudioParameters>::Read(const Message* m,
PickleIterator* iter,
AudioParameters* r) {
int format, channel_layout, sample_rate, bits_per_sample,
frames_per_buffer, channels;
if (!m->ReadInt(iter, &format) ||
!m->ReadInt(iter, &channel_layout) ||
!m->ReadInt(iter, &sample_rate) ||
!m->ReadInt(iter, &bits_per_sample) ||
!m->ReadInt(iter, &frames_per_buffer) ||
!m->ReadInt(iter, &channels))
return false;
r->Reset(static_cast<AudioParameters::Format>(format),
static_cast<ChannelLayout>(channel_layout),
sample_rate, bits_per_sample, frames_per_buffer);
if (!r->IsValid())
return false;
return true;
}
| 171,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: intuit_diff_type (bool need_header, mode_t *p_file_type)
{
file_offset this_line = 0;
file_offset first_command_line = -1;
char first_ed_command_letter = 0;
lin fcl_line = 0; /* Pacify 'gcc -W'. */
bool this_is_a_command = false;
bool stars_this_line = false;
bool extended_headers = false;
enum nametype i;
struct stat st[3];
int stat_errno[3];
int version_controlled[3];
enum diff retval;
mode_t file_type;
size_t indent = 0;
for (i = OLD; i <= INDEX; i++)
if (p_name[i]) {
free (p_name[i]);
p_name[i] = 0;
}
for (i = 0; i < ARRAY_SIZE (invalid_names); i++)
invalid_names[i] = NULL;
for (i = OLD; i <= NEW; i++)
if (p_timestr[i])
{
free(p_timestr[i]);
p_timestr[i] = 0;
}
for (i = OLD; i <= NEW; i++)
if (p_sha1[i])
{
free (p_sha1[i]);
p_sha1[i] = 0;
}
p_git_diff = false;
for (i = OLD; i <= NEW; i++)
{
p_mode[i] = 0;
p_copy[i] = false;
p_rename[i] = false;
}
/* Ed and normal format patches don't have filename headers. */
if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF)
need_header = false;
version_controlled[OLD] = -1;
version_controlled[NEW] = -1;
version_controlled[INDEX] = -1;
p_rfc934_nesting = 0;
p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1;
p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
Fseek (pfp, p_base, SEEK_SET);
p_input_line = p_bline - 1;
for (;;) {
char *s;
char *t;
file_offset previous_line = this_line;
bool last_line_was_command = this_is_a_command;
bool stars_last_line = stars_this_line;
size_t indent_last_line = indent;
char ed_command_letter;
bool strip_trailing_cr;
size_t chars_read;
indent = 0;
this_line = file_tell (pfp);
chars_read = pget_line (0, 0, false, false);
if (chars_read == (size_t) -1)
xalloc_die ();
if (! chars_read) {
if (first_ed_command_letter) {
/* nothing but deletes!? */
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
else {
p_start = this_line;
p_sline = p_input_line;
if (extended_headers)
{
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
return NO_DIFF;
}
}
strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r';
for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
if (*s == '\t')
indent = (indent + 8) & ~7;
else
indent++;
}
if (ISDIGIT (*s))
{
for (t = s + 1; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
if (*t == 'd' || *t == 'c' || *t == 'a')
{
for (t++; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
for (; *t == ' ' || *t == '\t'; t++)
/* do nothing */ ;
if (*t == '\r')
t++;
this_is_a_command = (*t == '\n');
}
}
if (! need_header
&& first_command_line < 0
&& ((ed_command_letter = get_ed_command_letter (s))
|| this_is_a_command)) {
first_command_line = this_line;
first_ed_command_letter = ed_command_letter;
fcl_line = p_input_line;
p_indent = indent; /* assume this for now */
p_strip_trailing_cr = strip_trailing_cr;
}
if (!stars_last_line && strnEQ(s, "*** ", 4))
{
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
}
else if (strnEQ(s, "+++ ", 4))
{
/* Swap with NEW below. */
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Index:", 6))
{
fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Prereq:", 7))
{
for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
/* do nothing */ ;
revision = t;
for (t = revision; *t; t++)
if (ISSPACE ((unsigned char) *t))
{
char const *u;
for (u = t + 1; ISSPACE ((unsigned char) *u); u++)
/* do nothing */ ;
if (*u)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("Prereq: with multiple words at line %s of patch\n",
format_linenum (numbuf, this_line));
}
break;
}
if (t == revision)
revision = 0;
else {
char oldc = *t;
*t = '\0';
revision = xstrdup (revision);
*t = oldc;
}
}
else if (strnEQ (s, "diff --git ", 11))
{
char const *u;
if (extended_headers)
{
p_start = this_line;
p_sline = p_input_line;
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u))
&& ISSPACE ((unsigned char) *u)
&& (p_name[NEW] = parse_name (u, strippath, &u))
&& (u = skip_spaces (u), ! *u)))
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
p_git_diff = true;
need_header = false;
}
else if (p_git_diff && strnEQ (s, "index ", 6))
{
char const *u, *v;
if ((u = skip_hex_digits (s + 6))
&& u[0] == '.' && u[1] == '.'
&& (v = skip_hex_digits (u + 2))
&& (! *v || ISSPACE ((unsigned char) *v)))
{
get_sha1(&p_sha1[OLD], s + 6, u);
get_sha1(&p_sha1[NEW], u + 2, v);
p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]);
p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]);
if (*(v = skip_spaces (v)))
p_mode[OLD] = p_mode[NEW] = fetchmode (v);
extended_headers = true;
}
}
else if (p_git_diff && strnEQ (s, "old mode ", 9))
{
p_mode[OLD] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new mode ", 9))
{
p_mode[NEW] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "deleted file mode ", 18))
{
p_mode[OLD] = fetchmode (s + 18);
p_says_nonexistent[NEW] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new file mode ", 14))
{
p_mode[NEW] = fetchmode (s + 14);
p_says_nonexistent[OLD] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename from ", 12))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename to ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy from ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy to ", 8))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "GIT binary patch", 16))
{
p_start = this_line;
p_sline = p_input_line;
retval = GIT_BINARY_DIFF;
goto scan_exit;
}
else
{
for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
/* do nothing */ ;
if (strnEQ(t, "--- ", 4))
{
struct timespec timestamp;
timestamp.tv_sec = -1;
fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW],
×tamp);
need_header = false;
if (timestamp.tv_sec != -1)
{
p_timestamp[NEW] = timestamp;
p_rfc934_nesting = (t - s) >> 1;
}
p_strip_trailing_cr = strip_trailing_cr;
}
}
if (need_header)
continue;
if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
first_command_line >= 0 &&
strEQ(s, ".\n") ) {
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
&& strnEQ(s, "@@ -", 4)) {
/* 'p_name', 'p_timestr', and 'p_timestamp' are backwards;
swap them. */
struct timespec ti = p_timestamp[OLD];
p_timestamp[OLD] = p_timestamp[NEW];
p_timestamp[NEW] = ti;
t = p_name[OLD];
p_name[OLD] = p_name[NEW];
p_name[NEW] = t;
t = p_timestr[OLD];
p_timestr[OLD] = p_timestr[NEW];
p_timestr[NEW] = t;
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
while (*s != ' ' && *s != '\n')
s++;
while (*s == ' ')
s++;
if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
p_indent = indent;
p_start = this_line;
p_sline = p_input_line;
retval = UNI_DIFF;
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for unified diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
stars_this_line = strnEQ(s, "********", 8);
if ((diff_type == NO_DIFF
|| diff_type == CONTEXT_DIFF
|| diff_type == NEW_CONTEXT_DIFF)
&& stars_last_line && indent_last_line == indent
&& strnEQ (s, "*** ", 4)) {
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
/* if this is a new context diff the character just before */
/* the newline is a '*'. */
while (*s != '\n')
s++;
p_indent = indent;
p_strip_trailing_cr = strip_trailing_cr;
p_start = previous_line;
p_sline = p_input_line - 1;
retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
{
/* Scan the first hunk to see whether the file contents
appear to have been deleted. */
file_offset saved_p_base = p_base;
lin saved_p_bline = p_bline;
Fseek (pfp, previous_line, SEEK_SET);
p_input_line -= 2;
if (another_hunk (retval, false)
&& ! p_repl_lines && p_newfirst == 1)
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
next_intuit_at (saved_p_base, saved_p_bline);
}
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for context diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
last_line_was_command &&
(strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
p_start = previous_line;
p_sline = p_input_line - 1;
p_indent = indent;
retval = NORMAL_DIFF;
goto scan_exit;
}
}
scan_exit:
/* The old, new, or old and new file types may be defined. When both
file types are defined, make sure they are the same, or else assume
we do not know the file type. */
file_type = p_mode[OLD] & S_IFMT;
if (file_type)
{
mode_t new_file_type = p_mode[NEW] & S_IFMT;
if (new_file_type && file_type != new_file_type)
file_type = 0;
}
else
{
file_type = p_mode[NEW] & S_IFMT;
if (! file_type)
file_type = S_IFREG;
}
*p_file_type = file_type;
/* To intuit 'inname', the name of the file to patch,
use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599
(with some modifications if posixly_correct is zero):
- Take the old and new names from the context header if present,
and take the index name from the 'Index:' line if present and
if either the old and new names are both absent
or posixly_correct is nonzero.
Consider the file names to be in the order (old, new, index).
- If some named files exist, use the first one if posixly_correct
is nonzero, the best one otherwise.
- If patch_get is nonzero, and no named files exist,
but an RCS or SCCS master file exists,
use the first named file with an RCS or SCCS master.
- If no named files exist, no RCS or SCCS master was found,
some names are given, posixly_correct is zero,
and the patch appears to create a file, then use the best name
requiring the creation of the fewest directories.
- Otherwise, report failure by setting 'inname' to 0;
this causes our invoker to ask the user for a file name. */
i = NONE;
if (!inname)
{
enum nametype i0 = NONE;
if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX])
{
free (p_name[INDEX]);
p_name[INDEX] = 0;
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0)
{
/* It's the same name as before; reuse stat results. */
stat_errno[i] = stat_errno[i0];
if (! stat_errno[i])
st[i] = st[i0];
}
else
{
stat_errno[i] = stat_file (p_name[i], &st[i]);
if (! stat_errno[i])
{
if (lookup_file_id (&st[i]) == DELETE_LATER)
stat_errno[i] = ENOENT;
else if (posixly_correct && name_is_valid (p_name[i]))
break;
}
}
i0 = i;
}
if (! posixly_correct)
{
/* The best of all existing files. */
i = best_name (p_name, stat_errno);
if (i == NONE && patch_get)
{
enum nametype nope = NONE;
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
char const *cs;
char *getbuf;
char *diffbuf;
bool readonly = (outfile
&& strcmp (outfile, p_name[i]) != 0);
if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0)
{
cs = (version_controller
(p_name[i], readonly, (struct stat *) 0,
&getbuf, &diffbuf));
version_controlled[i] = !! cs;
if (cs)
{
if (version_get (p_name[i], cs, false, readonly,
getbuf, &st[i]))
stat_errno[i] = 0;
else
version_controlled[i] = 0;
free (getbuf);
free (diffbuf);
if (! stat_errno[i])
break;
}
}
nope = i;
}
}
if (i0 != NONE
&& (i == NONE || (st[i].st_mode & S_IFMT) == file_type)
&& maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE,
i == NONE || st[i].st_size == 0)
&& i == NONE)
i = i0;
if (i == NONE && p_says_nonexistent[reverse])
{
int newdirs[3];
int newdirs_min = INT_MAX;
int distance_from_minimum[3];
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
newdirs[i] = (prefix_components (p_name[i], false)
- prefix_components (p_name[i], true));
if (newdirs[i] < newdirs_min)
newdirs_min = newdirs[i];
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
distance_from_minimum[i] = newdirs[i] - newdirs_min;
/* The best of the filenames which create the fewest directories. */
i = best_name (p_name, distance_from_minimum);
}
}
}
if ((pch_rename () || pch_copy ())
&& ! inname
&& ! ((i == OLD || i == NEW) &&
p_name[! reverse] &&
name_is_valid (p_name[! reverse])))
{
say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy");
}
if (i == NONE)
{
if (inname)
{
inerrno = stat_file (inname, &instat);
if (inerrno || (instat.st_mode & S_IFMT) == file_type)
maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0);
}
else
inerrno = -1;
}
else
{
inname = xstrdup (p_name[i]);
inerrno = stat_errno[i];
invc = version_controlled[i];
instat = st[i];
}
return retval;
}
Commit Message:
CWE ID: CWE-476 | intuit_diff_type (bool need_header, mode_t *p_file_type)
{
file_offset this_line = 0;
file_offset first_command_line = -1;
char first_ed_command_letter = 0;
lin fcl_line = 0; /* Pacify 'gcc -W'. */
bool this_is_a_command = false;
bool stars_this_line = false;
bool extended_headers = false;
enum nametype i;
struct stat st[3];
int stat_errno[3];
int version_controlled[3];
enum diff retval;
mode_t file_type;
size_t indent = 0;
for (i = OLD; i <= INDEX; i++)
if (p_name[i]) {
free (p_name[i]);
p_name[i] = 0;
}
for (i = 0; i < ARRAY_SIZE (invalid_names); i++)
invalid_names[i] = NULL;
for (i = OLD; i <= NEW; i++)
if (p_timestr[i])
{
free(p_timestr[i]);
p_timestr[i] = 0;
}
for (i = OLD; i <= NEW; i++)
if (p_sha1[i])
{
free (p_sha1[i]);
p_sha1[i] = 0;
}
p_git_diff = false;
for (i = OLD; i <= NEW; i++)
{
p_mode[i] = 0;
p_copy[i] = false;
p_rename[i] = false;
}
/* Ed and normal format patches don't have filename headers. */
if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF)
need_header = false;
version_controlled[OLD] = -1;
version_controlled[NEW] = -1;
version_controlled[INDEX] = -1;
p_rfc934_nesting = 0;
p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1;
p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
Fseek (pfp, p_base, SEEK_SET);
p_input_line = p_bline - 1;
for (;;) {
char *s;
char *t;
file_offset previous_line = this_line;
bool last_line_was_command = this_is_a_command;
bool stars_last_line = stars_this_line;
size_t indent_last_line = indent;
char ed_command_letter;
bool strip_trailing_cr;
size_t chars_read;
indent = 0;
this_line = file_tell (pfp);
chars_read = pget_line (0, 0, false, false);
if (chars_read == (size_t) -1)
xalloc_die ();
if (! chars_read) {
if (first_ed_command_letter) {
/* nothing but deletes!? */
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
else {
p_start = this_line;
p_sline = p_input_line;
if (extended_headers)
{
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
return NO_DIFF;
}
}
strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r';
for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
if (*s == '\t')
indent = (indent + 8) & ~7;
else
indent++;
}
if (ISDIGIT (*s))
{
for (t = s + 1; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
if (*t == 'd' || *t == 'c' || *t == 'a')
{
for (t++; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
for (; *t == ' ' || *t == '\t'; t++)
/* do nothing */ ;
if (*t == '\r')
t++;
this_is_a_command = (*t == '\n');
}
}
if (! need_header
&& first_command_line < 0
&& ((ed_command_letter = get_ed_command_letter (s))
|| this_is_a_command)) {
first_command_line = this_line;
first_ed_command_letter = ed_command_letter;
fcl_line = p_input_line;
p_indent = indent; /* assume this for now */
p_strip_trailing_cr = strip_trailing_cr;
}
if (!stars_last_line && strnEQ(s, "*** ", 4))
{
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
}
else if (strnEQ(s, "+++ ", 4))
{
/* Swap with NEW below. */
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Index:", 6))
{
fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Prereq:", 7))
{
for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
/* do nothing */ ;
revision = t;
for (t = revision; *t; t++)
if (ISSPACE ((unsigned char) *t))
{
char const *u;
for (u = t + 1; ISSPACE ((unsigned char) *u); u++)
/* do nothing */ ;
if (*u)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("Prereq: with multiple words at line %s of patch\n",
format_linenum (numbuf, this_line));
}
break;
}
if (t == revision)
revision = 0;
else {
char oldc = *t;
*t = '\0';
revision = xstrdup (revision);
*t = oldc;
}
}
else if (strnEQ (s, "diff --git ", 11))
{
char const *u;
if (extended_headers)
{
p_start = this_line;
p_sline = p_input_line;
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u))
&& ISSPACE ((unsigned char) *u)
&& (p_name[NEW] = parse_name (u, strippath, &u))
&& (u = skip_spaces (u), ! *u)))
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
p_git_diff = true;
need_header = false;
}
else if (p_git_diff && strnEQ (s, "index ", 6))
{
char const *u, *v;
if ((u = skip_hex_digits (s + 6))
&& u[0] == '.' && u[1] == '.'
&& (v = skip_hex_digits (u + 2))
&& (! *v || ISSPACE ((unsigned char) *v)))
{
get_sha1(&p_sha1[OLD], s + 6, u);
get_sha1(&p_sha1[NEW], u + 2, v);
p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]);
p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]);
if (*(v = skip_spaces (v)))
p_mode[OLD] = p_mode[NEW] = fetchmode (v);
extended_headers = true;
}
}
else if (p_git_diff && strnEQ (s, "old mode ", 9))
{
p_mode[OLD] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new mode ", 9))
{
p_mode[NEW] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "deleted file mode ", 18))
{
p_mode[OLD] = fetchmode (s + 18);
p_says_nonexistent[NEW] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new file mode ", 14))
{
p_mode[NEW] = fetchmode (s + 14);
p_says_nonexistent[OLD] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename from ", 12))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename to ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy from ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy to ", 8))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "GIT binary patch", 16))
{
p_start = this_line;
p_sline = p_input_line;
retval = GIT_BINARY_DIFF;
goto scan_exit;
}
else
{
for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
/* do nothing */ ;
if (strnEQ(t, "--- ", 4))
{
struct timespec timestamp;
timestamp.tv_sec = -1;
fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW],
×tamp);
need_header = false;
if (timestamp.tv_sec != -1)
{
p_timestamp[NEW] = timestamp;
p_rfc934_nesting = (t - s) >> 1;
}
p_strip_trailing_cr = strip_trailing_cr;
}
}
if (need_header)
continue;
if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
first_command_line >= 0 &&
strEQ(s, ".\n") ) {
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
&& strnEQ(s, "@@ -", 4)) {
/* 'p_name', 'p_timestr', and 'p_timestamp' are backwards;
swap them. */
struct timespec ti = p_timestamp[OLD];
p_timestamp[OLD] = p_timestamp[NEW];
p_timestamp[NEW] = ti;
t = p_name[OLD];
p_name[OLD] = p_name[NEW];
p_name[NEW] = t;
t = p_timestr[OLD];
p_timestr[OLD] = p_timestr[NEW];
p_timestr[NEW] = t;
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
while (*s != ' ' && *s != '\n')
s++;
while (*s == ' ')
s++;
if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
p_indent = indent;
p_start = this_line;
p_sline = p_input_line;
retval = UNI_DIFF;
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for unified diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
stars_this_line = strnEQ(s, "********", 8);
if ((diff_type == NO_DIFF
|| diff_type == CONTEXT_DIFF
|| diff_type == NEW_CONTEXT_DIFF)
&& stars_last_line && indent_last_line == indent
&& strnEQ (s, "*** ", 4)) {
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
/* if this is a new context diff the character just before */
/* the newline is a '*'. */
while (*s != '\n')
s++;
p_indent = indent;
p_strip_trailing_cr = strip_trailing_cr;
p_start = previous_line;
p_sline = p_input_line - 1;
retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
{
/* Scan the first hunk to see whether the file contents
appear to have been deleted. */
file_offset saved_p_base = p_base;
lin saved_p_bline = p_bline;
Fseek (pfp, previous_line, SEEK_SET);
p_input_line -= 2;
if (another_hunk (retval, false)
&& ! p_repl_lines && p_newfirst == 1)
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
next_intuit_at (saved_p_base, saved_p_bline);
}
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for context diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
last_line_was_command &&
(strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
p_start = previous_line;
p_sline = p_input_line - 1;
p_indent = indent;
retval = NORMAL_DIFF;
goto scan_exit;
}
}
scan_exit:
/* The old, new, or old and new file types may be defined. When both
file types are defined, make sure they are the same, or else assume
we do not know the file type. */
file_type = p_mode[OLD] & S_IFMT;
if (file_type)
{
mode_t new_file_type = p_mode[NEW] & S_IFMT;
if (new_file_type && file_type != new_file_type)
file_type = 0;
}
else
{
file_type = p_mode[NEW] & S_IFMT;
if (! file_type)
file_type = S_IFREG;
}
*p_file_type = file_type;
/* To intuit 'inname', the name of the file to patch,
use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599
(with some modifications if posixly_correct is zero):
- Take the old and new names from the context header if present,
and take the index name from the 'Index:' line if present and
if either the old and new names are both absent
or posixly_correct is nonzero.
Consider the file names to be in the order (old, new, index).
- If some named files exist, use the first one if posixly_correct
is nonzero, the best one otherwise.
- If patch_get is nonzero, and no named files exist,
but an RCS or SCCS master file exists,
use the first named file with an RCS or SCCS master.
- If no named files exist, no RCS or SCCS master was found,
some names are given, posixly_correct is zero,
and the patch appears to create a file, then use the best name
requiring the creation of the fewest directories.
- Otherwise, report failure by setting 'inname' to 0;
this causes our invoker to ask the user for a file name. */
i = NONE;
if (!inname)
{
enum nametype i0 = NONE;
if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX])
{
free (p_name[INDEX]);
p_name[INDEX] = 0;
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0)
{
/* It's the same name as before; reuse stat results. */
stat_errno[i] = stat_errno[i0];
if (! stat_errno[i])
st[i] = st[i0];
}
else
{
stat_errno[i] = stat_file (p_name[i], &st[i]);
if (! stat_errno[i])
{
if (lookup_file_id (&st[i]) == DELETE_LATER)
stat_errno[i] = ENOENT;
else if (posixly_correct && name_is_valid (p_name[i]))
break;
}
}
i0 = i;
}
if (! posixly_correct)
{
/* The best of all existing files. */
i = best_name (p_name, stat_errno);
if (i == NONE && patch_get)
{
enum nametype nope = NONE;
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
char const *cs;
char *getbuf;
char *diffbuf;
bool readonly = (outfile
&& strcmp (outfile, p_name[i]) != 0);
if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0)
{
cs = (version_controller
(p_name[i], readonly, (struct stat *) 0,
&getbuf, &diffbuf));
version_controlled[i] = !! cs;
if (cs)
{
if (version_get (p_name[i], cs, false, readonly,
getbuf, &st[i]))
stat_errno[i] = 0;
else
version_controlled[i] = 0;
free (getbuf);
free (diffbuf);
if (! stat_errno[i])
break;
}
}
nope = i;
}
}
if (i0 != NONE
&& (i == NONE || (st[i].st_mode & S_IFMT) == file_type)
&& maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE,
i == NONE || st[i].st_size == 0)
&& i == NONE)
i = i0;
if (i == NONE && p_says_nonexistent[reverse])
{
int newdirs[3];
int newdirs_min = INT_MAX;
int distance_from_minimum[3];
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
newdirs[i] = (prefix_components (p_name[i], false)
- prefix_components (p_name[i], true));
if (newdirs[i] < newdirs_min)
newdirs_min = newdirs[i];
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
distance_from_minimum[i] = newdirs[i] - newdirs_min;
/* The best of the filenames which create the fewest directories. */
i = best_name (p_name, distance_from_minimum);
}
}
}
if ((pch_rename () || pch_copy ())
&& ! inname
&& ! ((i == OLD || i == NEW) &&
p_name[reverse] && p_name[! reverse] &&
name_is_valid (p_name[reverse]) &&
name_is_valid (p_name[! reverse])))
{
say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy");
}
if (i == NONE)
{
if (inname)
{
inerrno = stat_file (inname, &instat);
if (inerrno || (instat.st_mode & S_IFMT) == file_type)
maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0);
}
else
inerrno = -1;
}
else
{
inname = xstrdup (p_name[i]);
inerrno = stat_errno[i];
invc = version_controlled[i];
instat = st[i];
}
return retval;
}
| 165,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromeContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type()))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
OnRobustJPEGDecodeImage)
#endif // defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff,
OnPatchFileBsdiff)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette,
OnPatchFileCourgette)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
#if defined(FULL_SAFE_BROWSING)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
OnAnalyzeZipFileForDownloadProtection)
#endif
#if defined(ENABLE_EXTENSIONS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata,
OnParseMediaMetadata)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
for (Handlers::iterator it = handlers_.begin();
!handled && it != handlers_.end(); ++it) {
handled = (*it)->OnMessageReceived(message);
}
return handled;
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID: | bool ChromeContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type()))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
OnRobustJPEGDecodeImage)
#endif // defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff,
OnPatchFileBsdiff)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette,
OnPatchFileCourgette)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
#if defined(FULL_SAFE_BROWSING)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
OnAnalyzeZipFileForDownloadProtection)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeDmgFileForDownloadProtection,
OnAnalyzeDmgFileForDownloadProtection)
#endif
#endif
#if defined(ENABLE_EXTENSIONS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata,
OnParseMediaMetadata)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
for (Handlers::iterator it = handlers_.begin();
!handled && it != handlers_.end(); ++it) {
handled = (*it)->OnMessageReceived(message);
}
return handled;
}
| 171,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileInfo, getPathInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
int path_len;
char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);
if (path) {
char *dpath = estrndup(path, path_len);
path_len = php_dirname(dpath, path_len);
spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC);
efree(dpath);
}
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileInfo, getPathInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
int path_len;
char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);
if (path) {
char *dpath = estrndup(path, path_len);
path_len = php_dirname(dpath, path_len);
spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC);
efree(dpath);
}
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jas_matrix_asl(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = jas_seqent_asl(*data, n);
}
}
}
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | void jas_matrix_asl(jas_matrix_t *matrix, int n)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = jas_seqent_asl(*data, n);
}
}
}
}
| 168,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_expand_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_expand(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_expand_set(PNG_CONST image_transform *this,
image_transform_png_set_expand_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_expand(pp);
if (that->this.has_tRNS)
that->this.is_transparent = 1;
this->next->set(this->next, that, pp, pi);
}
| 173,634 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
get_block_t *get_block;
/*
* Fallback to buffered I/O if we see an inode without
* extents.
*/
if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
return 0;
/* Fallback to buffered I/O if we do not support append dio. */
if (iocb->ki_pos + iter->count > i_size_read(inode) &&
!ocfs2_supports_append_dio(osb))
return 0;
if (iov_iter_rw(iter) == READ)
get_block = ocfs2_get_block;
else
get_block = ocfs2_dio_get_block;
return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
iter, get_block,
ocfs2_dio_end_io, NULL, 0);
}
Commit Message: ocfs2: ip_alloc_sem should be taken in ocfs2_get_block()
ip_alloc_sem should be taken in ocfs2_get_block() when reading file in
DIRECT mode to prevent concurrent access to extent tree with
ocfs2_dio_end_io_write(), which may cause BUGON in the following
situation:
read file 'A' end_io of writing file 'A'
vfs_read
__vfs_read
ocfs2_file_read_iter
generic_file_read_iter
ocfs2_direct_IO
__blockdev_direct_IO
do_blockdev_direct_IO
do_direct_IO
get_more_blocks
ocfs2_get_block
ocfs2_extent_map_get_blocks
ocfs2_get_clusters
ocfs2_get_clusters_nocache()
ocfs2_search_extent_list
return the index of record which
contains the v_cluster, that is
v_cluster > rec[i]->e_cpos.
ocfs2_dio_end_io
ocfs2_dio_end_io_write
down_write(&oi->ip_alloc_sem);
ocfs2_mark_extent_written
ocfs2_change_extent_flag
ocfs2_split_extent
...
--> modify the rec[i]->e_cpos, resulting
in v_cluster < rec[i]->e_cpos.
BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos))
[[email protected]: v3]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io")
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Reviewed-by: Gang He <[email protected]>
Acked-by: Changwei Ge <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
get_block_t *get_block;
/*
* Fallback to buffered I/O if we see an inode without
* extents.
*/
if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
return 0;
/* Fallback to buffered I/O if we do not support append dio. */
if (iocb->ki_pos + iter->count > i_size_read(inode) &&
!ocfs2_supports_append_dio(osb))
return 0;
if (iov_iter_rw(iter) == READ)
get_block = ocfs2_lock_get_block;
else
get_block = ocfs2_dio_wr_get_block;
return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
iter, get_block,
ocfs2_dio_end_io, NULL, 0);
}
| 169,397 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Init(const IPC::ChannelHandle& channel_handle,
PP_Module pp_module,
PP_GetInterface_Func local_get_interface,
const ppapi::Preferences& preferences,
SyncMessageStatusReceiver* status_receiver) {
dispatcher_delegate_.reset(new ProxyChannelDelegate);
dispatcher_.reset(new ppapi::proxy::HostDispatcher(
pp_module, local_get_interface, status_receiver));
if (!dispatcher_->InitHostWithChannel(dispatcher_delegate_.get(),
channel_handle,
true, // Client.
preferences)) {
dispatcher_.reset();
dispatcher_delegate_.reset();
return false;
}
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool Init(const IPC::ChannelHandle& channel_handle,
| 170,735 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
}
Commit Message: xkbcomp: Don't explode on invalid virtual modifiers
testcase: 'virtualModifiers=LevelThreC'
Signed-off-by: Daniel Stone <[email protected]>
CWE ID: CWE-476 | LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (!str)
return false;
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
}
| 169,089 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to)
{
struct pathComponent *pc;
int elen = 0;
unsigned char *p = to;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0)
break;
/* Fall through */
case 2:
p = to;
*p++ = '/';
break;
case 3:
memcpy(p, "../", 3);
p += 3;
break;
case 4:
memcpy(p, "./", 2);
p += 2;
/* that would be . - just ignore */
break;
case 5:
p += udf_get_filename(sb, pc->componentIdent, p,
pc->lengthComponentIdent);
*p++ = '/';
break;
}
elen += sizeof(struct pathComponent) + pc->lengthComponentIdent;
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
}
Commit Message: udf: Check path length when reading symlink
Symlink reading code does not check whether the resulting path fits into
the page provided by the generic code. This isn't as easy as just
checking the symlink size because of various encoding conversions we
perform on path. So we have to check whether there is still enough space
in the buffer on the fly.
CC: [email protected]
Reported-by: Carl Henrik Lunde <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-17 | static void udf_pc_to_char(struct super_block *sb, unsigned char *from,
static int udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to, int tolen)
{
struct pathComponent *pc;
int elen = 0;
int comp_len;
unsigned char *p = to;
/* Reserve one byte for terminating \0 */
tolen--;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0)
break;
/* Fall through */
case 2:
if (tolen == 0)
return -ENAMETOOLONG;
p = to;
*p++ = '/';
tolen--;
break;
case 3:
if (tolen < 3)
return -ENAMETOOLONG;
memcpy(p, "../", 3);
p += 3;
tolen -= 3;
break;
case 4:
if (tolen < 2)
return -ENAMETOOLONG;
memcpy(p, "./", 2);
p += 2;
tolen -= 2;
/* that would be . - just ignore */
break;
case 5:
comp_len = udf_get_filename(sb, pc->componentIdent,
pc->lengthComponentIdent,
p, tolen);
p += comp_len;
tolen -= comp_len;
if (tolen == 0)
return -ENAMETOOLONG;
*p++ = '/';
tolen--;
break;
}
elen += sizeof(struct pathComponent) + pc->lengthComponentIdent;
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
return 0;
}
| 166,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
return true;
}
Commit Message: Disable setxattr calls from quarantine subsystem on Chrome OS.
BUG=733943
Change-Id: I6e743469a8dc91536e180ecf4ff0df0cf427037c
Reviewed-on: https://chromium-review.googlesource.com/c/1380571
Commit-Queue: Will Harris <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Reviewed-by: David Trainor <[email protected]>
Reviewed-by: Thiemo Nagel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#617961}
CWE ID: CWE-200 | bool SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
#if !defined(OS_CHROMEOS)
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
#endif // !defined(OS_CHROMEOS)
return true;
}
| 173,117 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_unwrap(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer,
gss_buffer_t output_message_buffer,
int *conf_state,
gss_qop_t *qop_state)
{
OM_uint32 ret;
ret = gss_unwrap(minor_status,
context_handle,
input_message_buffer,
output_message_buffer,
conf_state,
qop_state);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_unwrap(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer,
gss_buffer_t output_message_buffer,
int *conf_state,
gss_qop_t *qop_state)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_unwrap(minor_status,
sc->ctx_handle,
input_message_buffer,
output_message_buffer,
conf_state,
qop_state);
return (ret);
}
| 166,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
Commit Message:
CWE ID: CWE-772 | vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
| 164,941 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *newext, int flag)
{
struct ext4_extent_header *eh;
struct ext4_extent *ex, *fex;
struct ext4_extent *nearex; /* nearest extent */
struct ext4_ext_path *npath = NULL;
int depth, len, err;
ext4_lblk_t next;
unsigned uninitialized = 0;
BUG_ON(ext4_ext_get_actual_len(newext) == 0);
depth = ext_depth(inode);
ex = path[depth].p_ext;
BUG_ON(path[depth].p_hdr == NULL);
/* try to insert block into found extent and return */
if (ex && (flag != EXT4_GET_BLOCKS_PRE_IO)
&& ext4_can_extents_be_merged(inode, ex, newext)) {
ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_uninitialized(ex),
ext4_ext_get_actual_len(ex), ext_pblock(ex));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
return err;
/*
* ext4_can_extents_be_merged should have checked that either
* both extents are uninitialized, or both aren't. Thus we
* need to check only one of them here.
*/
if (ext4_ext_is_uninitialized(ex))
uninitialized = 1;
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (uninitialized)
ext4_ext_mark_uninitialized(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
repeat:
depth = ext_depth(inode);
eh = path[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
goto has_space;
/* probably next leaf has space for us? */
fex = EXT_LAST_EXTENT(eh);
next = ext4_ext_next_leaf_block(inode, path);
if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
&& next != EXT_MAX_BLOCK) {
ext_debug("next leaf block - %d\n", next);
BUG_ON(npath != NULL);
npath = ext4_ext_find_extent(inode, next, NULL);
if (IS_ERR(npath))
return PTR_ERR(npath);
BUG_ON(npath->p_depth != path->p_depth);
eh = npath[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
ext_debug("next leaf isnt full(%d)\n",
le16_to_cpu(eh->eh_entries));
path = npath;
goto repeat;
}
ext_debug("next leaf has no free space(%d,%d)\n",
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
}
/*
* There is no free space in the found leaf.
* We're gonna add a new leaf in the tree.
*/
err = ext4_ext_create_new_leaf(handle, inode, path, newext);
if (err)
goto cleanup;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
has_space:
nearex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
if (!nearex) {
/* there is no extent in this leaf, create first one */
ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext));
path[depth].p_ext = EXT_FIRST_EXTENT(eh);
} else if (le32_to_cpu(newext->ee_block)
> le32_to_cpu(nearex->ee_block)) {
/* BUG_ON(newext->ee_block == nearex->ee_block); */
if (nearex != EXT_LAST_EXTENT(eh)) {
len = EXT_MAX_EXTENT(eh) - nearex;
len = (len - 1) * sizeof(struct ext4_extent);
len = len < 0 ? 0 : len;
ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
"move %d from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
nearex, len, nearex + 1, nearex + 2);
memmove(nearex + 2, nearex + 1, len);
}
path[depth].p_ext = nearex + 1;
} else {
BUG_ON(newext->ee_block == nearex->ee_block);
len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
len = len < 0 ? 0 : len;
ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
"move %d from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
nearex, len, nearex + 1, nearex + 2);
memmove(nearex + 1, nearex, len);
path[depth].p_ext = nearex;
}
le16_add_cpu(&eh->eh_entries, 1);
nearex = path[depth].p_ext;
nearex->ee_block = newext->ee_block;
ext4_ext_store_pblock(nearex, ext_pblock(newext));
nearex->ee_len = newext->ee_len;
merge:
/* try to merge extents to the right */
if (flag != EXT4_GET_BLOCKS_PRE_IO)
ext4_ext_try_to_merge(inode, path, nearex);
/* try to merge extents to the left */
/* time to correct all indexes above */
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto cleanup;
err = ext4_ext_dirty(handle, inode, path + depth);
cleanup:
if (npath) {
ext4_ext_drop_refs(npath);
kfree(npath);
}
ext4_ext_invalidate_cache(inode);
return err;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *newext, int flag)
{
struct ext4_extent_header *eh;
struct ext4_extent *ex, *fex;
struct ext4_extent *nearex; /* nearest extent */
struct ext4_ext_path *npath = NULL;
int depth, len, err;
ext4_lblk_t next;
unsigned uninitialized = 0;
BUG_ON(ext4_ext_get_actual_len(newext) == 0);
depth = ext_depth(inode);
ex = path[depth].p_ext;
BUG_ON(path[depth].p_hdr == NULL);
/* try to insert block into found extent and return */
if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
&& ext4_can_extents_be_merged(inode, ex, newext)) {
ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_uninitialized(ex),
ext4_ext_get_actual_len(ex), ext_pblock(ex));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
return err;
/*
* ext4_can_extents_be_merged should have checked that either
* both extents are uninitialized, or both aren't. Thus we
* need to check only one of them here.
*/
if (ext4_ext_is_uninitialized(ex))
uninitialized = 1;
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (uninitialized)
ext4_ext_mark_uninitialized(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
repeat:
depth = ext_depth(inode);
eh = path[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
goto has_space;
/* probably next leaf has space for us? */
fex = EXT_LAST_EXTENT(eh);
next = ext4_ext_next_leaf_block(inode, path);
if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
&& next != EXT_MAX_BLOCK) {
ext_debug("next leaf block - %d\n", next);
BUG_ON(npath != NULL);
npath = ext4_ext_find_extent(inode, next, NULL);
if (IS_ERR(npath))
return PTR_ERR(npath);
BUG_ON(npath->p_depth != path->p_depth);
eh = npath[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
ext_debug("next leaf isnt full(%d)\n",
le16_to_cpu(eh->eh_entries));
path = npath;
goto repeat;
}
ext_debug("next leaf has no free space(%d,%d)\n",
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
}
/*
* There is no free space in the found leaf.
* We're gonna add a new leaf in the tree.
*/
err = ext4_ext_create_new_leaf(handle, inode, path, newext);
if (err)
goto cleanup;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
has_space:
nearex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
if (!nearex) {
/* there is no extent in this leaf, create first one */
ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext));
path[depth].p_ext = EXT_FIRST_EXTENT(eh);
} else if (le32_to_cpu(newext->ee_block)
> le32_to_cpu(nearex->ee_block)) {
/* BUG_ON(newext->ee_block == nearex->ee_block); */
if (nearex != EXT_LAST_EXTENT(eh)) {
len = EXT_MAX_EXTENT(eh) - nearex;
len = (len - 1) * sizeof(struct ext4_extent);
len = len < 0 ? 0 : len;
ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
"move %d from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
nearex, len, nearex + 1, nearex + 2);
memmove(nearex + 2, nearex + 1, len);
}
path[depth].p_ext = nearex + 1;
} else {
BUG_ON(newext->ee_block == nearex->ee_block);
len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
len = len < 0 ? 0 : len;
ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
"move %d from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
nearex, len, nearex + 1, nearex + 2);
memmove(nearex + 1, nearex, len);
path[depth].p_ext = nearex;
}
le16_add_cpu(&eh->eh_entries, 1);
nearex = path[depth].p_ext;
nearex->ee_block = newext->ee_block;
ext4_ext_store_pblock(nearex, ext_pblock(newext));
nearex->ee_len = newext->ee_len;
merge:
/* try to merge extents to the right */
if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(inode, path, nearex);
/* try to merge extents to the left */
/* time to correct all indexes above */
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto cleanup;
err = ext4_ext_dirty(handle, inode, path + depth);
cleanup:
if (npath) {
ext4_ext_drop_refs(npath);
kfree(npath);
}
ext4_ext_invalidate_cache(inode);
return err;
}
| 167,538 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static __init int seqgen_init(void)
{
rekey_seq_generator(NULL);
return 0;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static __init int seqgen_init(void)
get_random_bytes(random_int_secret, sizeof(random_int_secret));
return 0;
}
| 165,770 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
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_bearer_type_print(netdissect_options *ndo, const u_char *dat)
l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
| 167,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ipc_rcu_putref(void *ptr)
{
if (--container_of(ptr, struct ipc_rcu_hdr, data)->refcount > 0)
return;
if (container_of(ptr, struct ipc_rcu_hdr, data)->is_vmalloc) {
call_rcu(&container_of(ptr, struct ipc_rcu_grace, data)->rcu,
ipc_schedule_free);
} else {
kfree_rcu(container_of(ptr, struct ipc_rcu_grace, data), rcu);
}
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | void ipc_rcu_putref(void *ptr)
{
if (!atomic_dec_and_test(&container_of(ptr, struct ipc_rcu_hdr, data)->refcount))
return;
if (container_of(ptr, struct ipc_rcu_hdr, data)->is_vmalloc) {
call_rcu(&container_of(ptr, struct ipc_rcu_grace, data)->rcu,
ipc_schedule_free);
} else {
kfree_rcu(container_of(ptr, struct ipc_rcu_grace, data), rcu);
}
}
| 165,985 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void runTest()
{
webkit_support::PostDelayedTask(CCLayerTreeHostTest::onBeginTest, static_cast<void*>(this), 0);
webkit_support::PostDelayedTask(CCLayerTreeHostTest::testTimeout, static_cast<void*>(this), 5000);
webkit_support::RunMessageLoop();
m_running = false;
bool timedOut = m_timedOut; // Save whether we're timed out in case RunAllPendingMessages has the timeout.
webkit_support::RunAllPendingMessages();
ASSERT(!m_layerTreeHost.get());
m_client.clear();
if (timedOut) {
FAIL() << "Test timed out";
return;
}
afterTest();
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | virtual void runTest()
class TimeoutTask : public webkit_support::TaskAdaptor {
public:
explicit TimeoutTask(CCLayerTreeHostTest* test)
: m_test(test)
{
}
void clearTest()
{
m_test = 0;
}
virtual ~TimeoutTask()
{
if (m_test)
m_test->clearTimeout();
}
virtual void Run()
{
if (m_test)
m_test->timeout();
}
private:
CCLayerTreeHostTest* m_test;
};
virtual void runTest(bool threaded)
{
m_settings.enableCompositorThread = threaded;
webkit_support::PostDelayedTask(CCLayerTreeHostTest::onBeginTest, static_cast<void*>(this), 0);
m_timeoutTask = new TimeoutTask(this);
webkit_support::PostDelayedTask(m_timeoutTask, 5000); // webkit_support takes ownership of the task
webkit_support::RunMessageLoop();
webkit_support::RunAllPendingMessages();
if (m_timeoutTask)
m_timeoutTask->clearTest();
ASSERT(!m_layerTreeHost.get());
m_client.clear();
if (m_timedOut) {
FAIL() << "Test timed out";
return;
}
afterTest();
}
| 170,295 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: magiccheck(struct magic_set *ms, struct magic *m)
{
uint64_t l = m->value.q;
uint64_t v;
float fl, fv;
double dl, dv;
int matched;
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = p->b;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = p->h;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
v = p->l;
break;
case FILE_QUAD:
case FILE_LEQUAD:
case FILE_BEQUAD:
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
v = p->q;
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
fl = m->value.f;
fv = p->f;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = fv != fl;
break;
case '=':
matched = fv == fl;
break;
case '>':
matched = fv > fl;
break;
case '<':
matched = fv < fl;
break;
default:
file_magerror(ms, "cannot happen with float: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
dl = m->value.d;
dv = p->d;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = dv != dl;
break;
case '=':
matched = dv == dl;
break;
case '>':
matched = dv > dl;
break;
case '<':
matched = dv < dl;
break;
default:
file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln);
return -1;
}
return matched;
case FILE_DEFAULT:
case FILE_CLEAR:
l = 0;
v = 0;
break;
case FILE_STRING:
case FILE_PSTRING:
l = 0;
v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
l = 0;
v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */
size_t slen;
size_t idx;
if (ms->search.s == NULL)
return 0;
slen = MIN(m->vallen, sizeof(m->value.s));
l = 0;
v = 0;
for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {
if (slen + idx > ms->search.s_len)
break;
v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags);
if (v == 0) { /* found match */
ms->search.offset += idx;
break;
}
}
break;
}
case FILE_REGEX: {
int rc;
file_regex_t rx;
if (ms->search.s == NULL)
return 0;
l = 0;
rc = file_regcomp(&rx, m->value.s,
REG_EXTENDED|REG_NEWLINE|
((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));
if (rc) {
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
} else {
regmatch_t pmatch[1];
#ifndef REG_STARTEND
#define REG_STARTEND 0
size_t l = ms->search.s_len - 1;
char c = ms->search.s[l];
((char *)(intptr_t)ms->search.s)[l] = '\0';
#else
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = ms->search.s_len;
#endif
rc = file_regexec(&rx, (const char *)ms->search.s,
1, pmatch, REG_STARTEND);
#if REG_STARTEND == 0
((char *)(intptr_t)ms->search.s)[l] = c;
#endif
switch (rc) {
case 0:
ms->search.s += (int)pmatch[0].rm_so;
ms->search.offset += (size_t)pmatch[0].rm_so;
ms->search.rm_len =
(size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);
v = 0;
break;
case REG_NOMATCH:
v = 1;
break;
default:
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
break;
}
}
file_regfree(&rx);
if (v == (uint64_t)-1)
return -1;
break;
}
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
return 1;
default:
file_magerror(ms, "invalid type %d in magiccheck()", m->type);
return -1;
}
v = file_signextend(ms, m, v);
switch (m->reln) {
case 'x':
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u == *any* = 1\n", (unsigned long long)v);
matched = 1;
break;
case '!':
matched = v != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u != %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '=':
matched = v == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u == %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '>':
if (m->flag & UNSIGNED) {
matched = v > l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u > %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v > (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d > %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '<':
if (m->flag & UNSIGNED) {
matched = v < l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u < %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v < (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d < %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '&':
matched = (v & l) == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) == %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
case '^':
matched = (v & l) != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) != %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
default:
file_magerror(ms, "cannot happen: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
}
Commit Message: If requested, limit search length.
CWE ID: CWE-399 | magiccheck(struct magic_set *ms, struct magic *m)
{
uint64_t l = m->value.q;
uint64_t v;
float fl, fv;
double dl, dv;
int matched;
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = p->b;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = p->h;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
v = p->l;
break;
case FILE_QUAD:
case FILE_LEQUAD:
case FILE_BEQUAD:
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
v = p->q;
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
fl = m->value.f;
fv = p->f;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = fv != fl;
break;
case '=':
matched = fv == fl;
break;
case '>':
matched = fv > fl;
break;
case '<':
matched = fv < fl;
break;
default:
file_magerror(ms, "cannot happen with float: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
dl = m->value.d;
dv = p->d;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = dv != dl;
break;
case '=':
matched = dv == dl;
break;
case '>':
matched = dv > dl;
break;
case '<':
matched = dv < dl;
break;
default:
file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln);
return -1;
}
return matched;
case FILE_DEFAULT:
case FILE_CLEAR:
l = 0;
v = 0;
break;
case FILE_STRING:
case FILE_PSTRING:
l = 0;
v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
l = 0;
v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */
size_t slen;
size_t idx;
if (ms->search.s == NULL)
return 0;
slen = MIN(m->vallen, sizeof(m->value.s));
l = 0;
v = 0;
for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {
if (slen + idx > ms->search.s_len)
break;
v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags);
if (v == 0) { /* found match */
ms->search.offset += idx;
break;
}
}
break;
}
case FILE_REGEX: {
int rc;
file_regex_t rx;
if (ms->search.s == NULL)
return 0;
l = 0;
rc = file_regcomp(&rx, m->value.s,
REG_EXTENDED|REG_NEWLINE|
((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));
if (rc) {
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
} else {
#ifndef REG_STARTEND
char c;
#endif
regmatch_t pmatch[1];
size_t slen = ms->search.s_len;
/* Limit by offset if requested */
if (m->str_range > 0)
slen = MIN(slen, m->str_range);
#ifndef REG_STARTEND
#define REG_STARTEND 0
if (slen != 0)
slen--;
c = ms->search.s[slen];
((char *)(intptr_t)ms->search.s)[slen] = '\0';
#else
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = slen;
#endif
rc = file_regexec(&rx, (const char *)ms->search.s,
1, pmatch, REG_STARTEND);
#if REG_STARTEND == 0
((char *)(intptr_t)ms->search.s)[l] = c;
#endif
switch (rc) {
case 0:
ms->search.s += (int)pmatch[0].rm_so;
ms->search.offset += (size_t)pmatch[0].rm_so;
ms->search.rm_len =
(size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);
v = 0;
break;
case REG_NOMATCH:
v = 1;
break;
default:
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
break;
}
}
file_regfree(&rx);
if (v == (uint64_t)-1)
return -1;
break;
}
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
return 1;
default:
file_magerror(ms, "invalid type %d in magiccheck()", m->type);
return -1;
}
v = file_signextend(ms, m, v);
switch (m->reln) {
case 'x':
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u == *any* = 1\n", (unsigned long long)v);
matched = 1;
break;
case '!':
matched = v != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u != %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '=':
matched = v == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u == %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '>':
if (m->flag & UNSIGNED) {
matched = v > l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u > %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v > (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d > %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '<':
if (m->flag & UNSIGNED) {
matched = v < l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u < %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v < (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d < %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '&':
matched = (v & l) == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) == %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
case '^':
matched = (v & l) != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) != %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
default:
file_magerror(ms, "cannot happen: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
}
| 169,919 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InitializePrinting(content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
printing::PrintViewManager::CreateForWebContents(web_contents);
printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
#else
printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | void InitializePrinting(content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
printing::PrintViewManager::CreateForWebContents(web_contents);
printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
#else
printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
CreateCompositeClientIfNeeded(web_contents, false /* for_preview */);
}
| 171,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry *pce;
zval obj;
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||
!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||
!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||
!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||
!strcmp((char *)name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (Z_TYPE(ent1->data) == IS_UNDEF) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp((char *)name, EL_BINARY)) {
zend_string *new_str = NULL;
if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) {
new_str = php_base64_decode(
(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
}
zval_ptr_dtor(&ent1->data);
if (new_str) {
ZVAL_STR(&ent1->data, new_str);
} else {
ZVAL_EMPTY_STRING(&ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE(ent1->data) == IS_OBJECT) {
zval fname, retval;
ZVAL_STRING(&fname, "__wakeup");
call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);
zval_ptr_dtor(&fname);
zval_ptr_dtor(&retval);
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (Z_ISUNDEF(ent2->data)) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(&ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
zend_string_forget_hash_val(Z_STR(ent1->data));
if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {
incomplete_class = 1;
pce = PHP_IC_ENTRY;
}
if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) {
zval_ptr_dtor(&ent2->data);
ZVAL_UNDEF(&ent2->data);
php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data));
} else {
/* Initialize target object */
object_init_ex(&obj, pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP(obj),
Z_ARRVAL(ent2->data),
zval_add_ref, 0);
if (incomplete_class) {
php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ZVAL_COPY_VALUE(&ent2->data, &obj);
}
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE(ent2->data);
add_property_zval(&ent2->data, ent1->varname, &ent1->data);
if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp((char *)name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
Commit Message: Fix bug #73831 - NULL Pointer Dereference while unserialize php object
CWE ID: CWE-476 | static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry *pce;
zval obj;
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||
!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||
!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||
!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||
!strcmp((char *)name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (Z_TYPE(ent1->data) == IS_UNDEF) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp((char *)name, EL_BINARY)) {
zend_string *new_str = NULL;
if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) {
new_str = php_base64_decode(
(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
}
zval_ptr_dtor(&ent1->data);
if (new_str) {
ZVAL_STR(&ent1->data, new_str);
} else {
ZVAL_EMPTY_STRING(&ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE(ent1->data) == IS_OBJECT) {
zval fname, retval;
ZVAL_STRING(&fname, "__wakeup");
call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);
zval_ptr_dtor(&fname);
zval_ptr_dtor(&retval);
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (Z_ISUNDEF(ent2->data)) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(&ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
zend_string_forget_hash_val(Z_STR(ent1->data));
if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {
incomplete_class = 1;
pce = PHP_IC_ENTRY;
}
if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) {
zval_ptr_dtor(&ent2->data);
ZVAL_UNDEF(&ent2->data);
php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data));
} else {
/* Initialize target object */
if (object_init_ex(&obj, pce) != SUCCESS || EG(exception)) {
zval_ptr_dtor(&ent2->data);
ZVAL_UNDEF(&ent2->data);
php_error_docref(NULL, E_WARNING, "Class %s can not be instantiated", Z_STRVAL(ent1->data));
} else {
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP(obj),
Z_ARRVAL(ent2->data),
zval_add_ref, 0);
if (incomplete_class) {
php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ZVAL_COPY_VALUE(&ent2->data, &obj);
}
}
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE(ent2->data);
add_property_zval(&ent2->data, ent1->varname, &ent1->data);
if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp((char *)name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
| 168,513 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: iakerb_alloc_context(iakerb_ctx_id_t *pctx)
{
iakerb_ctx_id_t ctx;
krb5_error_code code;
*pctx = NULL;
ctx = k5alloc(sizeof(*ctx), &code);
if (ctx == NULL)
goto cleanup;
ctx->defcred = GSS_C_NO_CREDENTIAL;
ctx->magic = KG_IAKERB_CONTEXT;
ctx->state = IAKERB_AS_REQ;
ctx->count = 0;
code = krb5_gss_init_context(&ctx->k5c);
if (code != 0)
goto cleanup;
*pctx = ctx;
cleanup:
if (code != 0)
iakerb_release_context(ctx);
return code;
}
Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696]
The IAKERB mechanism currently replaces its context handle with the
krb5 mechanism handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the IAKERB context structure after context
establishment and add new IAKERB entry points to refer to it with that
type. Add initiate and established flags to the IAKERB context
structure for use in gss_inquire_context() prior to context
establishment.
CVE-2015-2696:
In MIT krb5 1.9 and later, applications which call
gss_inquire_context() on a partially-established IAKERB context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. Java server applications using the
native JGSS provider are vulnerable to this bug. A carefully crafted
IAKERB packet might allow the gss_inquire_context() call to succeed
with attacker-determined results, but applications should not make
access control decisions based on gss_inquire_context() results prior
to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | iakerb_alloc_context(iakerb_ctx_id_t *pctx)
iakerb_alloc_context(iakerb_ctx_id_t *pctx, int initiate)
{
iakerb_ctx_id_t ctx;
krb5_error_code code;
*pctx = NULL;
ctx = k5alloc(sizeof(*ctx), &code);
if (ctx == NULL)
goto cleanup;
ctx->defcred = GSS_C_NO_CREDENTIAL;
ctx->magic = KG_IAKERB_CONTEXT;
ctx->state = IAKERB_AS_REQ;
ctx->count = 0;
ctx->initiate = initiate;
ctx->established = 0;
code = krb5_gss_init_context(&ctx->k5c);
if (code != 0)
goto cleanup;
*pctx = ctx;
cleanup:
if (code != 0)
iakerb_release_context(ctx);
return code;
}
| 166,643 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
(void)png_ptr; /* Unused */
}
| 173,571 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsAgentHostImpl::ForceDetachAllClients() {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
while (!session_by_client_.empty()) {
DevToolsAgentHostClient* client = session_by_client_.begin()->first;
InnerDetachClient(client);
client->AgentHostClosed(this);
}
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | void DevToolsAgentHostImpl::ForceDetachAllClients() {
void DevToolsAgentHostImpl::ForceDetachAllSessions() {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
while (!sessions_.empty()) {
DevToolsAgentHostClient* client = (*sessions_.begin())->client();
DetachClient(client);
client->AgentHostClosed(this);
}
}
| 173,245 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
if (dump_one_state(x, 0, &info)) {
kfree_skb(skb);
return NULL;
}
return skb;
}
Commit Message: xfrm_user: return error pointer instead of NULL
When dump_one_state() returns an error, e.g. because of a too small
buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL
instead of an error pointer. But its callers expect an error pointer
and therefore continue to operate on a NULL skbuff.
This could lead to a privilege escalation (execution of user code in
kernel context) if the attacker has CAP_NET_ADMIN and is able to map
address 0.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
err = dump_one_state(x, 0, &info);
if (err) {
kfree_skb(skb);
return ERR_PTR(err);
}
return skb;
}
| 166,112 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() {
if (!media_service_factory_) {
mojo::InterfacePtr<mojo::Shell> shell_ptr;
GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr));
mojo::ServiceProviderPtr service_provider;
mojo::URLRequestPtr request(mojo::URLRequest::New());
request->url = mojo::String::From("mojo:media");
shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider),
nullptr, nullptr);
mojo::ConnectToService(service_provider.get(), &media_service_factory_);
media_service_factory_.set_connection_error_handler(
base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError,
base::Unretained(this)));
}
return media_service_factory_.get();
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399 | media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() {
if (!media_service_factory_) {
mojo::ServiceProviderPtr service_provider =
ConnectToApplication(GURL("mojo:media"));
mojo::ConnectToService(service_provider.get(), &media_service_factory_);
media_service_factory_.set_connection_error_handler(
base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError,
base::Unretained(this)));
}
return media_service_factory_.get();
}
| 171,696 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PPVarToNPVariant(PP_Var var, NPVariant* result) {
switch (var.type) {
case PP_VARTYPE_UNDEFINED:
VOID_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_NULL:
NULL_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_BOOL:
BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result);
break;
case PP_VARTYPE_INT32:
INT32_TO_NPVARIANT(var.value.as_int, *result);
break;
case PP_VARTYPE_DOUBLE:
DOUBLE_TO_NPVARIANT(var.value.as_double, *result);
break;
case PP_VARTYPE_STRING: {
scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
if (!string) {
VOID_TO_NPVARIANT(*result);
return false;
}
const std::string& value = string->value();
STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result);
break;
}
case PP_VARTYPE_OBJECT: {
scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var));
if (!object) {
VOID_TO_NPVARIANT(*result);
return false;
}
OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()),
*result);
break;
}
case PP_VARTYPE_ARRAY:
case PP_VARTYPE_DICTIONARY:
VOID_TO_NPVARIANT(*result);
break;
}
return true;
}
Commit Message: Fix invalid read in ppapi code
BUG=77493
TEST=attached test
Review URL: http://codereview.chromium.org/6883059
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@82172 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool PPVarToNPVariant(PP_Var var, NPVariant* result) {
switch (var.type) {
case PP_VARTYPE_UNDEFINED:
VOID_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_NULL:
NULL_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_BOOL:
BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result);
break;
case PP_VARTYPE_INT32:
INT32_TO_NPVARIANT(var.value.as_int, *result);
break;
case PP_VARTYPE_DOUBLE:
DOUBLE_TO_NPVARIANT(var.value.as_double, *result);
break;
case PP_VARTYPE_STRING: {
scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
if (!string) {
VOID_TO_NPVARIANT(*result);
return false;
}
const std::string& value = string->value();
char* c_string = static_cast<char*>(malloc(value.size()));
memcpy(c_string, value.data(), value.size());
STRINGN_TO_NPVARIANT(c_string, value.size(), *result);
break;
}
case PP_VARTYPE_OBJECT: {
scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var));
if (!object) {
VOID_TO_NPVARIANT(*result);
return false;
}
OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()),
*result);
break;
}
case PP_VARTYPE_ARRAY:
case PP_VARTYPE_DICTIONARY:
VOID_TO_NPVARIANT(*result);
break;
}
return true;
}
| 170,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b)
{
return (b[0]<<8) | b[1];
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682 | IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b)
{
return ((unsigned int)b[0]<<8) | (unsigned int)b[1];
}
| 168,197 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int hashtable_do_del(hashtable_t *hashtable,
const char *key, size_t hash)
{
pair_t *pair;
bucket_t *bucket;
size_t index;
index = hash % num_buckets(hashtable);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return -1;
if(&pair->list == bucket->first && &pair->list == bucket->last)
bucket->first = bucket->last = &hashtable->list;
else if(&pair->list == bucket->first)
bucket->first = pair->list.next;
else if(&pair->list == bucket->last)
bucket->last = pair->list.prev;
list_remove(&pair->list);
json_decref(pair->value);
jsonp_free(pair);
hashtable->size--;
return 0;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | static int hashtable_do_del(hashtable_t *hashtable,
const char *key, size_t hash)
{
pair_t *pair;
bucket_t *bucket;
size_t index;
index = hash & hashmask(hashtable->order);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return -1;
if(&pair->list == bucket->first && &pair->list == bucket->last)
bucket->first = bucket->last = &hashtable->list;
else if(&pair->list == bucket->first)
bucket->first = pair->list.next;
else if(&pair->list == bucket->last)
bucket->last = pair->list.prev;
list_remove(&pair->list);
json_decref(pair->value);
jsonp_free(pair);
hashtable->size--;
return 0;
}
| 166,528 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static pfunc check_literal(struct jv_parser* p) {
if (p->tokenpos == 0) return 0;
const char* pattern = 0;
int plen;
jv v;
switch (p->tokenbuf[0]) {
case 't': pattern = "true"; plen = 4; v = jv_true(); break;
case 'f': pattern = "false"; plen = 5; v = jv_false(); break;
case 'n': pattern = "null"; plen = 4; v = jv_null(); break;
}
if (pattern) {
if (p->tokenpos != plen) return "Invalid literal";
for (int i=0; i<plen; i++)
if (p->tokenbuf[i] != pattern[i])
return "Invalid literal";
TRY(value(p, v));
} else {
p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid
char* end = 0;
double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end);
if (end == 0 || *end != 0)
return "Invalid numeric literal";
TRY(value(p, jv_number(d)));
}
p->tokenpos = 0;
return 0;
}
Commit Message: Heap buffer overflow in tokenadd() (fix #105)
This was an off-by one: the NUL terminator byte was not allocated on
resize. This was triggered by JSON-encoded numbers longer than 256
bytes.
CWE ID: CWE-119 | static pfunc check_literal(struct jv_parser* p) {
if (p->tokenpos == 0) return 0;
const char* pattern = 0;
int plen;
jv v;
switch (p->tokenbuf[0]) {
case 't': pattern = "true"; plen = 4; v = jv_true(); break;
case 'f': pattern = "false"; plen = 5; v = jv_false(); break;
case 'n': pattern = "null"; plen = 4; v = jv_null(); break;
}
if (pattern) {
if (p->tokenpos != plen) return "Invalid literal";
for (int i=0; i<plen; i++)
if (p->tokenbuf[i] != pattern[i])
return "Invalid literal";
TRY(value(p, v));
} else {
p->tokenbuf[p->tokenpos] = 0;
char* end = 0;
double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end);
if (end == 0 || *end != 0)
return "Invalid numeric literal";
TRY(value(p, jv_number(d)));
}
p->tokenpos = 0;
return 0;
}
| 167,476 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ldb_dn_escape_internal(char *dst, const char *src, int len)
{
const char *p, *s;
char *d;
size_t l;
p = s = src;
d = dst;
while (p - src < len) {
p += strcspn(p, ",=\n\r+<>#;\\\" ");
if (p - src == len) /* found no escapable chars */
break;
/* copy the part of the string before the stop */
memcpy(d, s, p - s);
d += (p - s); /* move to current position */
switch (*p) {
case ' ':
if (p == src || (p-src)==(len-1)) {
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = *p++;
} else {
/* otherwise don't escape */
*d++ = *p++;
}
break;
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = *p++;
} else {
/* otherwise don't escape */
*d++ = *p++;
}
break;
case '?':
/* these must be escaped using \c form */
*d++ = '\\';
*d++ = *p++;
break;
default: {
/* any others get \XX form */
unsigned char v;
const char *hexbytes = "0123456789ABCDEF";
v = *(const unsigned char *)p;
*d++ = '\\';
*d++ = hexbytes[v>>4];
*d++ = hexbytes[v&0xF];
p++;
break;
}
}
s = p; /* move forward */
}
Commit Message:
CWE ID: CWE-200 | static int ldb_dn_escape_internal(char *dst, const char *src, int len)
{
char c;
char *d;
int i;
d = dst;
for (i = 0; i < len; i++){
c = src[i];
switch (c) {
case ' ':
if (i == 0 || i == len - 1) {
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = c;
} else {
/* otherwise don't escape */
*d++ = c;
}
break;
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = *p++;
} else {
/* otherwise don't escape */
*d++ = *p++;
}
break;
case '?':
/* these must be escaped using \c form */
*d++ = '\\';
*d++ = c;
break;
case ';':
case '\r':
case '\n':
case '=':
case '\0': {
/* any others get \XX form */
unsigned char v;
const char *hexbytes = "0123456789ABCDEF";
v = (const unsigned char)c;
*d++ = '\\';
*d++ = hexbytes[v>>4];
*d++ = hexbytes[v&0xF];
break;
}
default:
*d++ = c;
}
}
| 164,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
int sx, sy;
int i;
int ncx, ncy, nc, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int vers, fmt;
t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */
int chunkNum = 0;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax = 0;
int bytesPerPixel;
char *compBuf = NULL; /* So we can gdFree it with impunity. */
gdImagePtr im;
/* Get the header */
im =
_gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
&chunkIdx);
if (im == NULL) {
/* No need to free chunkIdx as _gd2CreateFromFile does it for us. */
return 0;
}
bytesPerPixel = im->trueColor ? 4 : 1;
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
/* Allocate buffers */
chunkMax = cs * bytesPerPixel * cs;
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail;
}
GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
};
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Read the data... */
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk %d (%d, %d), y from %d to %d\n",
chunkNum, cx, cy, ylo, yhi));
if (gd2_compressed (fmt)) {
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
GD2_DBG (printf ("Error reading comproessed chunk\n"));
goto fail;
};
chunkPos = 0;
};
for (y = ylo; (y < yhi); y++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
/*GD2_DBG(printf("y=%d: ",y)); */
if (!gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
if (!gdGetInt (&im->tpixels[y][x], in)) {
/*printf("EOF while reading\n"); */
/*gdImageDestroy(im); */
/*return 0; */
im->tpixels[y][x] = 0;
}
} else {
int ch;
if (!gdGetByte (&ch, in)) {
/*printf("EOF while reading\n"); */
/*gdImageDestroy(im); */
/*return 0; */
ch = 0;
}
im->pixels[y][x] = ch;
}
}
} else {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
/* 2.0.1: work around a gcc bug by being verbose.
TBB */
int a = chunkBuf[chunkPos++] << 24;
int r = chunkBuf[chunkPos++] << 16;
int g = chunkBuf[chunkPos++] << 8;
int b = chunkBuf[chunkPos++];
/* 2.0.11: tpixels */
im->tpixels[y][x] = a + r + g + b;
} else {
im->pixels[y][x] = chunkBuf[chunkPos++];
}
};
};
/*GD2_DBG(printf("\n")); */
};
chunkNum++;
};
};
GD2_DBG (printf ("Freeing memory\n"));
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
GD2_DBG (printf ("Done\n"));
return im;
fail:
gdImageDestroy (im);
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
Commit Message: Fix DOS vulnerability in gdImageCreateFromGd2Ctx()
We must not pretend that there are image data if there are none. Instead
we fail reading the image file gracefully.
CWE ID: CWE-20 | BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
int sx, sy;
int i;
int ncx, ncy, nc, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int vers, fmt;
t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */
int chunkNum = 0;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax = 0;
int bytesPerPixel;
char *compBuf = NULL; /* So we can gdFree it with impunity. */
gdImagePtr im;
/* Get the header */
im =
_gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
&chunkIdx);
if (im == NULL) {
/* No need to free chunkIdx as _gd2CreateFromFile does it for us. */
return 0;
}
bytesPerPixel = im->trueColor ? 4 : 1;
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
/* Allocate buffers */
chunkMax = cs * bytesPerPixel * cs;
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail;
}
GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
};
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Read the data... */
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk %d (%d, %d), y from %d to %d\n",
chunkNum, cx, cy, ylo, yhi));
if (gd2_compressed (fmt)) {
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
GD2_DBG (printf ("Error reading comproessed chunk\n"));
goto fail;
};
chunkPos = 0;
};
for (y = ylo; (y < yhi); y++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
/*GD2_DBG(printf("y=%d: ",y)); */
if (!gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
if (!gdGetInt (&im->tpixels[y][x], in)) {
gd_error("gd2: EOF while reading\n");
gdImageDestroy(im);
return NULL;
}
} else {
int ch;
if (!gdGetByte (&ch, in)) {
gd_error("gd2: EOF while reading\n");
gdImageDestroy(im);
return NULL;
}
im->pixels[y][x] = ch;
}
}
} else {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
/* 2.0.1: work around a gcc bug by being verbose.
TBB */
int a = chunkBuf[chunkPos++] << 24;
int r = chunkBuf[chunkPos++] << 16;
int g = chunkBuf[chunkPos++] << 8;
int b = chunkBuf[chunkPos++];
/* 2.0.11: tpixels */
im->tpixels[y][x] = a + r + g + b;
} else {
im->pixels[y][x] = chunkBuf[chunkPos++];
}
};
};
/*GD2_DBG(printf("\n")); */
};
chunkNum++;
};
};
GD2_DBG (printf ("Freeing memory\n"));
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
GD2_DBG (printf ("Done\n"));
return im;
fail:
gdImageDestroy (im);
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
| 168,510 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CronTab::initRegexObject() {
if ( ! CronTab::regex.isInitialized() ) {
const char *errptr;
int erroffset;
MyString pattern( CRONTAB_PARAMETER_PATTERN ) ;
if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) {
MyString error = "CronTab: Failed to compile Regex - ";
error += pattern;
EXCEPT( const_cast<char*>(error.Value()));
}
}
}
Commit Message:
CWE ID: CWE-134 | CronTab::initRegexObject() {
if ( ! CronTab::regex.isInitialized() ) {
const char *errptr;
int erroffset;
MyString pattern( CRONTAB_PARAMETER_PATTERN ) ;
if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) {
MyString error = "CronTab: Failed to compile Regex - ";
error += pattern;
EXCEPT( "%s", const_cast<char*>(error.Value()) );
}
}
}
| 165,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: LogLuvClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/*
* For consistency, we always want to write out the same
* bitspersample and sampleformat for our TIFF file,
* regardless of the data format being used by the application.
* Since this routine is called after tags have been set but
* before they have been recorded in the file, we reset them here.
*/
td->td_samplesperpixel =
(td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
td->td_bitspersample = 16;
td->td_sampleformat = SAMPLEFORMAT_INT;
}
Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
CWE ID: CWE-125 | LogLuvClose(TIFF* tif)
{
LogLuvState* sp = (LogLuvState*) tif->tif_data;
TIFFDirectory *td = &tif->tif_dir;
assert(sp != 0);
/*
* For consistency, we always want to write out the same
* bitspersample and sampleformat for our TIFF file,
* regardless of the data format being used by the application.
* Since this routine is called after tags have been set but
* before they have been recorded in the file, we reset them here.
* Note: this is really a nasty approach. See PixarLogClose
*/
if( sp->encoder_state )
{
/* See PixarLogClose. Might avoid issues with tags whose size depends
* on those below, but not completely sure this is enough. */
td->td_samplesperpixel =
(td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
td->td_bitspersample = 16;
td->td_sampleformat = SAMPLEFORMAT_INT;
}
}
| 168,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_dict_of_dicts (MyObject *obj, GHashTable *in,
GHashTable **out, GError **error)
{
*out = g_hash_table_new_full (g_str_hash, g_str_equal,
(GDestroyNotify) g_free,
(GDestroyNotify) g_hash_table_destroy);
g_hash_table_foreach (in, hash_foreach_mangle_dict_of_strings, *out);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_dict_of_dicts (MyObject *obj, GHashTable *in,
| 165,091 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: aspath_put (struct stream *s, struct aspath *as, int use32bit )
{
struct assegment *seg = as->segments;
size_t bytes = 0;
if (!seg || seg->length == 0)
return 0;
if (seg)
{
/*
* Hey, what do we do when we have > STREAM_WRITABLE(s) here?
* At the moment, we would write out a partial aspath, and our peer
* will complain and drop the session :-/
*
* The general assumption here is that many things tested will
* never happen. And, in real live, up to now, they have not.
*/
while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s)))
{
struct assegment *next = seg->next;
int written = 0;
int asns_packed = 0;
size_t lenp;
/* Overlength segments have to be split up */
while ( (seg->length - written) > AS_SEGMENT_MAX)
{
assegment_header_put (s, seg->type, AS_SEGMENT_MAX);
assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit);
written += AS_SEGMENT_MAX;
bytes += ASSEGMENT_SIZE (written, use32bit);
}
/* write the final segment, probably is also the first */
lenp = assegment_header_put (s, seg->type, seg->length - written);
assegment_data_put (s, (seg->as + written), seg->length - written,
use32bit);
/* Sequence-type segments can be 'packed' together
* Case of a segment which was overlength and split up
* will be missed here, but that doesn't matter.
*/
while (next && ASSEGMENTS_PACKABLE (seg, next))
{
/* NB: We should never normally get here given we
* normalise aspath data when parse them. However, better
* safe than sorry. We potentially could call
* assegment_normalise here instead, but it's cheaper and
* easier to do it on the fly here rather than go through
* the segment list twice every time we write out
* aspath's.
*/
/* Next segment's data can fit in this one */
assegment_data_put (s, next->as, next->length, use32bit);
/* update the length of the segment header */
stream_putc_at (s, lenp, seg->length - written + next->length);
asns_packed += next->length;
next = next->next;
}
bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed,
use32bit);
seg = next;
}
}
return bytes;
}
Commit Message:
CWE ID: CWE-20 | aspath_put (struct stream *s, struct aspath *as, int use32bit )
{
struct assegment *seg = as->segments;
size_t bytes = 0;
if (!seg || seg->length == 0)
return 0;
if (seg)
{
/*
* Hey, what do we do when we have > STREAM_WRITABLE(s) here?
* At the moment, we would write out a partial aspath, and our peer
* will complain and drop the session :-/
*
* The general assumption here is that many things tested will
* never happen. And, in real live, up to now, they have not.
*/
while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s)))
{
struct assegment *next = seg->next;
int written = 0;
int asns_packed = 0;
size_t lenp;
/* Overlength segments have to be split up */
while ( (seg->length - written) > AS_SEGMENT_MAX)
{
assegment_header_put (s, seg->type, AS_SEGMENT_MAX);
assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit);
written += AS_SEGMENT_MAX;
bytes += ASSEGMENT_SIZE (AS_SEGMENT_MAX, use32bit);
}
/* write the final segment, probably is also the first */
lenp = assegment_header_put (s, seg->type, seg->length - written);
assegment_data_put (s, (seg->as + written), seg->length - written,
use32bit);
/* Sequence-type segments can be 'packed' together
* Case of a segment which was overlength and split up
* will be missed here, but that doesn't matter.
*/
while (next && ASSEGMENTS_PACKABLE (seg, next))
{
/* NB: We should never normally get here given we
* normalise aspath data when parse them. However, better
* safe than sorry. We potentially could call
* assegment_normalise here instead, but it's cheaper and
* easier to do it on the fly here rather than go through
* the segment list twice every time we write out
* aspath's.
*/
/* Next segment's data can fit in this one */
assegment_data_put (s, next->as, next->length, use32bit);
/* update the length of the segment header */
stream_putc_at (s, lenp, seg->length - written + next->length);
asns_packed += next->length;
next = next->next;
}
bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed,
use32bit);
seg = next;
}
}
return bytes;
}
| 164,639 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintWebViewHelper::OnPrintForSystemDialog() {
blink::WebLocalFrame* frame = print_preview_context_.source_frame();
if (!frame) {
NOTREACHED();
return;
}
Print(frame, print_preview_context_.source_node(), false);
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID: | void PrintWebViewHelper::OnPrintForSystemDialog() {
CHECK_LE(ipc_nesting_level_, 1);
blink::WebLocalFrame* frame = print_preview_context_.source_frame();
if (!frame) {
NOTREACHED();
return;
}
Print(frame, print_preview_context_.source_node(), false);
}
| 171,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL || sec_attr_len) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
| 169,079 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "TIME"))
return;
reply(nickFromMask(prefix), "TIME", QDateTime::currentDateTime().toString());
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix));
}
else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2")
.arg(nickFromMask(prefix)).arg(param));
}
}
Commit Message:
CWE ID: CWE-399 | void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
reply = QDateTime::currentDateTime().toString();
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix));
} else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2")
.arg(nickFromMask(prefix)).arg(param));
}
}
| 164,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PPB_URLLoader_Impl::RunCallback(int32_t result) {
if (!pending_callback_.get()) {
CHECK(main_document_loader_);
return;
}
TrackedCallback::ClearAndRun(&pending_callback_, result);
}
Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called.
BUG=137778
Review URL: https://chromiumcodereview.appspot.com/10797037
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void PPB_URLLoader_Impl::RunCallback(int32_t result) {
if (!pending_callback_.get()) {
CHECK(main_document_loader_);
return;
}
// If |user_buffer_| was set as part of registering the callback, ensure
// it got cleared since the callback is now free to delete it.
DCHECK(!user_buffer_);
TrackedCallback::ClearAndRun(&pending_callback_, result);
}
| 170,901 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog(
WebContents* initiator) {
base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true);
ConstrainedWebDialogDelegate* web_dialog_delegate =
ShowConstrainedWebDialog(initiator->GetBrowserContext(),
new PrintPreviewDialogDelegate(initiator),
initiator);
WebContents* preview_dialog = web_dialog_delegate->GetWebContents();
GURL print_url(chrome::kChromeUIPrintURL);
content::HostZoomMap::Get(preview_dialog->GetSiteInstance())
->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0);
PrintViewManager::CreateForWebContents(preview_dialog);
extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
preview_dialog);
preview_dialog_map_[preview_dialog] = initiator;
waiting_for_new_preview_page_ = true;
task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog);
AddObservers(initiator);
AddObservers(preview_dialog);
return preview_dialog;
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog(
WebContents* initiator) {
base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true);
ConstrainedWebDialogDelegate* web_dialog_delegate =
ShowConstrainedWebDialog(initiator->GetBrowserContext(),
new PrintPreviewDialogDelegate(initiator),
initiator);
WebContents* preview_dialog = web_dialog_delegate->GetWebContents();
GURL print_url(chrome::kChromeUIPrintURL);
content::HostZoomMap::Get(preview_dialog->GetSiteInstance())
->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0);
PrintViewManager::CreateForWebContents(preview_dialog);
CreateCompositeClientIfNeeded(preview_dialog, true /* for_preview */);
extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
preview_dialog);
preview_dialog_map_[preview_dialog] = initiator;
waiting_for_new_preview_page_ = true;
task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog);
AddObservers(initiator);
AddObservers(preview_dialog);
return preview_dialog;
}
| 171,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
| 169,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static vpx_image_t *img_alloc_helper(vpx_image_t *img, vpx_img_fmt_t fmt,
unsigned int d_w, unsigned int d_h,
unsigned int buf_align,
unsigned int stride_align,
unsigned char *img_data) {
unsigned int h, w, s, xcs, ycs, bps;
unsigned int stride_in_bytes;
int align;
/* Treat align==0 like align==1 */
if (!buf_align) buf_align = 1;
/* Validate alignment (must be power of 2) */
if (buf_align & (buf_align - 1)) goto fail;
/* Treat align==0 like align==1 */
if (!stride_align) stride_align = 1;
/* Validate alignment (must be power of 2) */
if (stride_align & (stride_align - 1)) goto fail;
/* Get sample size for this format */
switch (fmt) {
case VPX_IMG_FMT_RGB32:
case VPX_IMG_FMT_RGB32_LE:
case VPX_IMG_FMT_ARGB:
case VPX_IMG_FMT_ARGB_LE: bps = 32; break;
case VPX_IMG_FMT_RGB24:
case VPX_IMG_FMT_BGR24: bps = 24; break;
case VPX_IMG_FMT_RGB565:
case VPX_IMG_FMT_RGB565_LE:
case VPX_IMG_FMT_RGB555:
case VPX_IMG_FMT_RGB555_LE:
case VPX_IMG_FMT_UYVY:
case VPX_IMG_FMT_YUY2:
case VPX_IMG_FMT_YVYU: bps = 16; break;
case VPX_IMG_FMT_I420:
case VPX_IMG_FMT_YV12:
case VPX_IMG_FMT_VPXI420:
case VPX_IMG_FMT_VPXYV12: bps = 12; break;
case VPX_IMG_FMT_I422:
case VPX_IMG_FMT_I440: bps = 16; break;
case VPX_IMG_FMT_I444: bps = 24; break;
case VPX_IMG_FMT_I42016: bps = 24; break;
case VPX_IMG_FMT_I42216:
case VPX_IMG_FMT_I44016: bps = 32; break;
case VPX_IMG_FMT_I44416: bps = 48; break;
default: bps = 16; break;
}
/* Get chroma shift values for this format */
switch (fmt) {
case VPX_IMG_FMT_I420:
case VPX_IMG_FMT_YV12:
case VPX_IMG_FMT_VPXI420:
case VPX_IMG_FMT_VPXYV12:
case VPX_IMG_FMT_I422:
case VPX_IMG_FMT_I42016:
case VPX_IMG_FMT_I42216: xcs = 1; break;
default: xcs = 0; break;
}
switch (fmt) {
case VPX_IMG_FMT_I420:
case VPX_IMG_FMT_I440:
case VPX_IMG_FMT_YV12:
case VPX_IMG_FMT_VPXI420:
case VPX_IMG_FMT_VPXYV12:
case VPX_IMG_FMT_I42016:
case VPX_IMG_FMT_I44016: ycs = 1; break;
default: ycs = 0; break;
}
/* Calculate storage sizes given the chroma subsampling */
align = (1 << xcs) - 1;
w = (d_w + align) & ~align;
align = (1 << ycs) - 1;
h = (d_h + align) & ~align;
s = (fmt & VPX_IMG_FMT_PLANAR) ? w : bps * w / 8;
s = (s + stride_align - 1) & ~(stride_align - 1);
stride_in_bytes = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? s * 2 : s;
/* Allocate the new image */
if (!img) {
img = (vpx_image_t *)calloc(1, sizeof(vpx_image_t));
if (!img) goto fail;
img->self_allocd = 1;
} else {
memset(img, 0, sizeof(vpx_image_t));
}
img->img_data = img_data;
if (!img_data) {
const uint64_t alloc_size = (fmt & VPX_IMG_FMT_PLANAR)
? (uint64_t)h * s * bps / 8
: (uint64_t)h * s;
if (alloc_size != (size_t)alloc_size) goto fail;
img->img_data = (uint8_t *)vpx_memalign(buf_align, (size_t)alloc_size);
img->img_data_owner = 1;
}
if (!img->img_data) goto fail;
img->fmt = fmt;
img->bit_depth = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? 16 : 8;
img->w = w;
img->h = h;
img->x_chroma_shift = xcs;
img->y_chroma_shift = ycs;
img->bps = bps;
/* Calculate strides */
img->stride[VPX_PLANE_Y] = img->stride[VPX_PLANE_ALPHA] = stride_in_bytes;
img->stride[VPX_PLANE_U] = img->stride[VPX_PLANE_V] = stride_in_bytes >> xcs;
/* Default viewport to entire image */
if (!vpx_img_set_rect(img, 0, 0, d_w, d_h)) return img;
fail:
vpx_img_free(img);
return NULL;
}
Commit Message: DO NOT MERGE | libvpx: Fix OOB caused by odd frame width.
Keep behaviors unchanged without external allocation.
Bug: b/64710201
Test: poc provided in the bug.
Change-Id: I319a47b64c7cfa7bb47ad01c702be6f2acffe3a4
(cherry picked from commit 51721c34847e6b4f935d5ecb1b44931c7716fd59)
(cherry picked from commit 28a641201287106fbb73dfbad35dae2756cde265)
CWE ID: CWE-20 | static vpx_image_t *img_alloc_helper(vpx_image_t *img, vpx_img_fmt_t fmt,
unsigned int d_w, unsigned int d_h,
unsigned int buf_align,
unsigned int stride_align,
unsigned char *img_data) {
unsigned int h, w, s, xcs, ycs, bps;
unsigned int stride_in_bytes;
int align;
/* Treat align==0 like align==1 */
if (!buf_align) buf_align = 1;
/* Validate alignment (must be power of 2) */
if (buf_align & (buf_align - 1)) goto fail;
/* Treat align==0 like align==1 */
if (!stride_align) stride_align = 1;
/* Validate alignment (must be power of 2) */
if (stride_align & (stride_align - 1)) goto fail;
/* Get sample size for this format */
switch (fmt) {
case VPX_IMG_FMT_RGB32:
case VPX_IMG_FMT_RGB32_LE:
case VPX_IMG_FMT_ARGB:
case VPX_IMG_FMT_ARGB_LE: bps = 32; break;
case VPX_IMG_FMT_RGB24:
case VPX_IMG_FMT_BGR24: bps = 24; break;
case VPX_IMG_FMT_RGB565:
case VPX_IMG_FMT_RGB565_LE:
case VPX_IMG_FMT_RGB555:
case VPX_IMG_FMT_RGB555_LE:
case VPX_IMG_FMT_UYVY:
case VPX_IMG_FMT_YUY2:
case VPX_IMG_FMT_YVYU: bps = 16; break;
case VPX_IMG_FMT_I420:
case VPX_IMG_FMT_YV12:
case VPX_IMG_FMT_VPXI420:
case VPX_IMG_FMT_VPXYV12: bps = 12; break;
case VPX_IMG_FMT_I422:
case VPX_IMG_FMT_I440: bps = 16; break;
case VPX_IMG_FMT_I444: bps = 24; break;
case VPX_IMG_FMT_I42016: bps = 24; break;
case VPX_IMG_FMT_I42216:
case VPX_IMG_FMT_I44016: bps = 32; break;
case VPX_IMG_FMT_I44416: bps = 48; break;
default: bps = 16; break;
}
/* Get chroma shift values for this format */
switch (fmt) {
case VPX_IMG_FMT_I420:
case VPX_IMG_FMT_YV12:
case VPX_IMG_FMT_VPXI420:
case VPX_IMG_FMT_VPXYV12:
case VPX_IMG_FMT_I422:
case VPX_IMG_FMT_I42016:
case VPX_IMG_FMT_I42216: xcs = 1; break;
default: xcs = 0; break;
}
switch (fmt) {
case VPX_IMG_FMT_I420:
case VPX_IMG_FMT_I440:
case VPX_IMG_FMT_YV12:
case VPX_IMG_FMT_VPXI420:
case VPX_IMG_FMT_VPXYV12:
case VPX_IMG_FMT_I42016:
case VPX_IMG_FMT_I44016: ycs = 1; break;
default: ycs = 0; break;
}
/* Calculate storage sizes. If the buffer was allocated externally, the width
* and height shouldn't be adjusted. */
w = d_w;
h = d_h;
s = (fmt & VPX_IMG_FMT_PLANAR) ? w : bps * w / 8;
s = (s + stride_align - 1) & ~(stride_align - 1);
stride_in_bytes = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? s * 2 : s;
/* Allocate the new image */
if (!img) {
img = (vpx_image_t *)calloc(1, sizeof(vpx_image_t));
if (!img) goto fail;
img->self_allocd = 1;
} else {
memset(img, 0, sizeof(vpx_image_t));
}
img->img_data = img_data;
if (!img_data) {
uint64_t alloc_size;
/* Calculate storage sizes given the chroma subsampling */
align = (1 << xcs) - 1;
w = (d_w + align) & ~align;
align = (1 << ycs) - 1;
h = (d_h + align) & ~align;
s = (fmt & VPX_IMG_FMT_PLANAR) ? w : bps * w / 8;
s = (s + stride_align - 1) & ~(stride_align - 1);
stride_in_bytes = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? s * 2 : s;
alloc_size = (fmt & VPX_IMG_FMT_PLANAR) ? (uint64_t)h * s * bps / 8
: (uint64_t)h * s;
if (alloc_size != (size_t)alloc_size) goto fail;
img->img_data = (uint8_t *)vpx_memalign(buf_align, (size_t)alloc_size);
img->img_data_owner = 1;
}
if (!img->img_data) goto fail;
img->fmt = fmt;
img->bit_depth = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? 16 : 8;
img->w = w;
img->h = h;
img->x_chroma_shift = xcs;
img->y_chroma_shift = ycs;
img->bps = bps;
/* Calculate strides */
img->stride[VPX_PLANE_Y] = img->stride[VPX_PLANE_ALPHA] = stride_in_bytes;
img->stride[VPX_PLANE_U] = img->stride[VPX_PLANE_V] = stride_in_bytes >> xcs;
/* Default viewport to entire image */
if (!vpx_img_set_rect(img, 0, 0, d_w, d_h)) return img;
fail:
vpx_img_free(img);
return NULL;
}
| 174,110 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) {
ASSERT(header->checkHeader());
if (header->payloadSize() >= newSize)
return true;
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(allocationSize > header->size());
size_t expandSize = allocationSize - header->size();
if (isObjectAllocatedAtAllocationPoint(header) &&
expandSize <= m_remainingAllocationSize) {
m_currentAllocationPoint += expandSize;
ASSERT(m_remainingAllocationSize >= expandSize);
setRemainingAllocationSize(m_remainingAllocationSize - expandSize);
SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize);
header->setSize(allocationSize);
ASSERT(findPageFromAddress(header->payloadEnd() - 1));
return true;
}
return false;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | bool NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) {
header->checkHeader();
if (header->payloadSize() >= newSize)
return true;
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(allocationSize > header->size());
size_t expandSize = allocationSize - header->size();
if (isObjectAllocatedAtAllocationPoint(header) &&
expandSize <= m_remainingAllocationSize) {
m_currentAllocationPoint += expandSize;
ASSERT(m_remainingAllocationSize >= expandSize);
setRemainingAllocationSize(m_remainingAllocationSize - expandSize);
SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize);
header->setSize(allocationSize);
ASSERT(findPageFromAddress(header->payloadEnd() - 1));
return true;
}
return false;
}
| 172,710 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XRRGetProviderResources(Display *dpy, Window window)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetProvidersReply rep;
xRRGetProvidersReq *req;
XRRProviderResources *xrpr;
long nbytes, nbytesRead;
int rbytes;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq(RRGetProviders, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetProviders;
req->window = window;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
nbytes = (long) rep.length << 2;
nbytesRead = (long) (rep.nProviders * 4);
rbytes = (sizeof(XRRProviderResources) + rep.nProviders * sizeof(RRProvider));
xrpr = (XRRProviderResources *) Xmalloc(rbytes);
if (xrpr == NULL) {
_XEatDataWords (dpy, rep.length);
_XRead32(dpy, (long *) xrpr->providers, rep.nProviders << 2);
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle();
return (XRRProviderResources *) xrpr;
}
void
XRRFreeProviderResources(XRRProviderResources *provider_resources)
{
free(provider_resources);
}
#define ProviderInfoExtra (SIZEOF(xRRGetProviderInfoReply) - 32)
XRRProviderInfo *
XRRGetProviderInfo(Display *dpy, XRRScreenResources *resources, RRProvider provider)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetProviderInfoReply rep;
xRRGetProviderInfoReq *req;
int nbytes, nbytesRead, rbytes;
XRRProviderInfo *xpi;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (RRGetProviderInfo, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetProviderInfo;
req->provider = provider;
req->configTimestamp = resources->configTimestamp;
if (!_XReply (dpy, (xReply *) &rep, ProviderInfoExtra >> 2, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
nbytes = ((long) rep.length << 2) - ProviderInfoExtra;
nbytesRead = (long)(rep.nCrtcs * 4 +
rep.nOutputs * 4 +
rep.nAssociatedProviders * 8 +
((rep.nameLength + 3) & ~3));
return NULL;
}
nbytes = ((long) rep.length << 2) - ProviderInfoExtra;
nbytesRead = (long)(rep.nCrtcs * 4 +
xpi->noutputs = rep.nOutputs;
xpi->nassociatedproviders = rep.nAssociatedProviders;
xpi->crtcs = (RRCrtc *)(xpi + 1);
xpi->outputs = (RROutput *)(xpi->crtcs + rep.nCrtcs);
xpi->associated_providers = (RRProvider *)(xpi->outputs + rep.nOutputs);
xpi->associated_capability = (unsigned int *)(xpi->associated_providers + rep.nAssociatedProviders);
xpi->name = (char *)(xpi->associated_capability + rep.nAssociatedProviders);
_XRead32(dpy, (long *) xpi->crtcs, rep.nCrtcs << 2);
_XRead32(dpy, (long *) xpi->outputs, rep.nOutputs << 2);
_XRead32(dpy, (long *) xpi->associated_providers, rep.nAssociatedProviders << 2);
/*
* _XRead32 reads a series of 32-bit values from the protocol and writes
* them out as a series of "long int" values, but associated_capability
* is defined as unsigned int *, so that won't work for this array.
* Instead we assume for now that "unsigned int" is also 32-bits, so
* the values can be read without any conversion.
*/
_XRead(dpy, (char *) xpi->associated_capability,
rep.nAssociatedProviders << 2);
_XReadPad(dpy, xpi->name, rep.nameLength);
xpi->name[rep.nameLength] = '\0';
/*
* Skip any extra data
*/
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle ();
return (XRRProviderInfo *) xpi;
}
Commit Message:
CWE ID: CWE-787 | XRRGetProviderResources(Display *dpy, Window window)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetProvidersReply rep;
xRRGetProvidersReq *req;
XRRProviderResources *xrpr;
long nbytes, nbytesRead;
int rbytes;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq(RRGetProviders, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetProviders;
req->window = window;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
if (rep.length < INT_MAX >> 2) {
nbytes = (long) rep.length << 2;
nbytesRead = (long) (rep.nProviders * 4);
rbytes = (sizeof(XRRProviderResources) + rep.nProviders *
sizeof(RRProvider));
xrpr = (XRRProviderResources *) Xmalloc(rbytes);
} else {
nbytes = 0;
nbytesRead = 0;
rbytes = 0;
xrpr = NULL;
}
if (xrpr == NULL) {
_XEatDataWords (dpy, rep.length);
_XRead32(dpy, (long *) xrpr->providers, rep.nProviders << 2);
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle();
return (XRRProviderResources *) xrpr;
}
void
XRRFreeProviderResources(XRRProviderResources *provider_resources)
{
free(provider_resources);
}
#define ProviderInfoExtra (SIZEOF(xRRGetProviderInfoReply) - 32)
XRRProviderInfo *
XRRGetProviderInfo(Display *dpy, XRRScreenResources *resources, RRProvider provider)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetProviderInfoReply rep;
xRRGetProviderInfoReq *req;
int nbytes, nbytesRead, rbytes;
XRRProviderInfo *xpi;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (RRGetProviderInfo, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetProviderInfo;
req->provider = provider;
req->configTimestamp = resources->configTimestamp;
if (!_XReply (dpy, (xReply *) &rep, ProviderInfoExtra >> 2, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
nbytes = ((long) rep.length << 2) - ProviderInfoExtra;
nbytesRead = (long)(rep.nCrtcs * 4 +
rep.nOutputs * 4 +
rep.nAssociatedProviders * 8 +
((rep.nameLength + 3) & ~3));
return NULL;
}
if (rep.length > INT_MAX >> 2 || rep.length < ProviderInfoExtra >> 2)
{
if (rep.length < ProviderInfoExtra >> 2)
_XEatDataWords (dpy, rep.length);
else
_XEatDataWords (dpy, rep.length - (ProviderInfoExtra >> 2));
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
nbytes = ((long) rep.length << 2) - ProviderInfoExtra;
nbytesRead = (long)(rep.nCrtcs * 4 +
xpi->noutputs = rep.nOutputs;
xpi->nassociatedproviders = rep.nAssociatedProviders;
xpi->crtcs = (RRCrtc *)(xpi + 1);
xpi->outputs = (RROutput *)(xpi->crtcs + rep.nCrtcs);
xpi->associated_providers = (RRProvider *)(xpi->outputs + rep.nOutputs);
xpi->associated_capability = (unsigned int *)(xpi->associated_providers + rep.nAssociatedProviders);
xpi->name = (char *)(xpi->associated_capability + rep.nAssociatedProviders);
_XRead32(dpy, (long *) xpi->crtcs, rep.nCrtcs << 2);
_XRead32(dpy, (long *) xpi->outputs, rep.nOutputs << 2);
_XRead32(dpy, (long *) xpi->associated_providers, rep.nAssociatedProviders << 2);
/*
* _XRead32 reads a series of 32-bit values from the protocol and writes
* them out as a series of "long int" values, but associated_capability
* is defined as unsigned int *, so that won't work for this array.
* Instead we assume for now that "unsigned int" is also 32-bits, so
* the values can be read without any conversion.
*/
_XRead(dpy, (char *) xpi->associated_capability,
rep.nAssociatedProviders << 2);
_XReadPad(dpy, xpi->name, rep.nameLength);
xpi->name[rep.nameLength] = '\0';
/*
* Skip any extra data
*/
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle ();
return (XRRProviderInfo *) xpi;
}
| 164,916 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
}
Commit Message: Fixed CVE-2018-8784
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119 | static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
return TRUE;
}
| 169,296 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FindBarController::Show() {
FindManager* find_manager = tab_contents_->GetFindManager();
if (!find_manager->find_ui_active()) {
MaybeSetPrepopulateText();
find_manager->set_find_ui_active(true);
find_bar_->Show(true);
}
find_bar_->SetFocusAndSelection();
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void FindBarController::Show() {
FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper();
if (!find_tab_helper->find_ui_active()) {
MaybeSetPrepopulateText();
find_tab_helper->set_find_ui_active(true);
find_bar_->Show(true);
}
find_bar_->SetFocusAndSelection();
}
| 170,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Handle<v8::Value> V8WebGLRenderingContext::getParameterCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.getParameter()");
if (args.Length() != 1)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
unsigned pname = toInt32(args[0]);
WebGLGetInfo info = context->getParameter(pname, ec);
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | v8::Handle<v8::Value> V8WebGLRenderingContext::getParameterCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.getParameter()");
if (args.Length() != 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
unsigned pname = toInt32(args[0]);
WebGLGetInfo info = context->getParameter(pname, ec);
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
| 171,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionSerializedValue(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
RefPtr<SerializedScriptValue> serializedArg(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->serializedValue(serializedArg);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionSerializedValue(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
RefPtr<SerializedScriptValue> serializedArg(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->serializedValue(serializedArg);
return JSValue::encode(jsUndefined());
}
| 170,608 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gs_nulldevice(gs_gstate * pgs)
{
int code = 0;
if (pgs->device == 0 || !gx_device_is_null(pgs->device)) {
gx_device *ndev;
code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device,
pgs->memory);
if (code < 0)
return code;
/*
* Internal devices have a reference count of 0, not 1,
* aside from references from graphics states.
to sort out how the icc profile is best handled with this device.
It seems to inherit properties from the current device if there
is one */
rc_init(ndev, pgs->memory, 0);
if (pgs->device != NULL) {
if ((code = dev_proc(pgs->device, get_profile)(pgs->device,
&(ndev->icc_struct))) < 0)
return code;
rc_increment(ndev->icc_struct);
set_dev_proc(ndev, get_profile, gx_default_get_profile);
}
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
gs_free_object(pgs->memory, ndev, "gs_copydevice(device)");
}
return code;
}
Commit Message:
CWE ID: CWE-78 | gs_nulldevice(gs_gstate * pgs)
{
int code = 0;
bool saveLockSafety = false;
if (pgs->device == 0 || !gx_device_is_null(pgs->device)) {
gx_device *ndev;
code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device,
pgs->memory);
if (code < 0)
return code;
if (gs_currentdevice_inline(pgs) != NULL)
saveLockSafety = gs_currentdevice_inline(pgs)->LockSafetyParams;
/*
* Internal devices have a reference count of 0, not 1,
* aside from references from graphics states.
to sort out how the icc profile is best handled with this device.
It seems to inherit properties from the current device if there
is one */
rc_init(ndev, pgs->memory, 0);
if (pgs->device != NULL) {
if ((code = dev_proc(pgs->device, get_profile)(pgs->device,
&(ndev->icc_struct))) < 0)
return code;
rc_increment(ndev->icc_struct);
set_dev_proc(ndev, get_profile, gx_default_get_profile);
}
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
gs_free_object(pgs->memory, ndev, "gs_copydevice(device)");
gs_currentdevice_inline(pgs)->LockSafetyParams = saveLockSafety;
}
return code;
}
| 164,687 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rds_ib_laddr_check(__be32 addr)
{
int ret;
struct rdma_cm_id *cm_id;
struct sockaddr_in sin;
/* Create a CMA ID and try to bind it. This catches both
* IB and iWARP capable NICs.
*/
cm_id = rdma_create_id(NULL, NULL, RDMA_PS_TCP, IB_QPT_RC);
if (IS_ERR(cm_id))
return PTR_ERR(cm_id);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = addr;
/* rdma_bind_addr will only succeed for IB & iWARP devices */
ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);
/* due to this, we will claim to support iWARP devices unless we
check node_type. */
if (ret || cm_id->device->node_type != RDMA_NODE_IB_CA)
ret = -EADDRNOTAVAIL;
rdsdebug("addr %pI4 ret %d node type %d\n",
&addr, ret,
cm_id->device ? cm_id->device->node_type : -1);
rdma_destroy_id(cm_id);
return ret;
}
Commit Message: rds: prevent dereference of a NULL device
Binding might result in a NULL device, which is dereferenced
causing this BUG:
[ 1317.260548] BUG: unable to handle kernel NULL pointer dereference at 000000000000097
4
[ 1317.261847] IP: [<ffffffff84225f52>] rds_ib_laddr_check+0x82/0x110
[ 1317.263315] PGD 418bcb067 PUD 3ceb21067 PMD 0
[ 1317.263502] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC
[ 1317.264179] Dumping ftrace buffer:
[ 1317.264774] (ftrace buffer empty)
[ 1317.265220] Modules linked in:
[ 1317.265824] CPU: 4 PID: 836 Comm: trinity-child46 Tainted: G W 3.13.0-rc4-
next-20131218-sasha-00013-g2cebb9b-dirty #4159
[ 1317.267415] task: ffff8803ddf33000 ti: ffff8803cd31a000 task.ti: ffff8803cd31a000
[ 1317.268399] RIP: 0010:[<ffffffff84225f52>] [<ffffffff84225f52>] rds_ib_laddr_check+
0x82/0x110
[ 1317.269670] RSP: 0000:ffff8803cd31bdf8 EFLAGS: 00010246
[ 1317.270230] RAX: 0000000000000000 RBX: ffff88020b0dd388 RCX: 0000000000000000
[ 1317.270230] RDX: ffffffff8439822e RSI: 00000000000c000a RDI: 0000000000000286
[ 1317.270230] RBP: ffff8803cd31be38 R08: 0000000000000000 R09: 0000000000000000
[ 1317.270230] R10: 0000000000000000 R11: 0000000000000001 R12: 0000000000000000
[ 1317.270230] R13: 0000000054086700 R14: 0000000000a25de0 R15: 0000000000000031
[ 1317.270230] FS: 00007ff40251d700(0000) GS:ffff88022e200000(0000) knlGS:000000000000
0000
[ 1317.270230] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[ 1317.270230] CR2: 0000000000000974 CR3: 00000003cd478000 CR4: 00000000000006e0
[ 1317.270230] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 1317.270230] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000090602
[ 1317.270230] Stack:
[ 1317.270230] 0000000054086700 5408670000a25de0 5408670000000002 0000000000000000
[ 1317.270230] ffffffff84223542 00000000ea54c767 0000000000000000 ffffffff86d26160
[ 1317.270230] ffff8803cd31be68 ffffffff84223556 ffff8803cd31beb8 ffff8800c6765280
[ 1317.270230] Call Trace:
[ 1317.270230] [<ffffffff84223542>] ? rds_trans_get_preferred+0x42/0xa0
[ 1317.270230] [<ffffffff84223556>] rds_trans_get_preferred+0x56/0xa0
[ 1317.270230] [<ffffffff8421c9c3>] rds_bind+0x73/0xf0
[ 1317.270230] [<ffffffff83e4ce62>] SYSC_bind+0x92/0xf0
[ 1317.270230] [<ffffffff812493f8>] ? context_tracking_user_exit+0xb8/0x1d0
[ 1317.270230] [<ffffffff8119313d>] ? trace_hardirqs_on+0xd/0x10
[ 1317.270230] [<ffffffff8107a852>] ? syscall_trace_enter+0x32/0x290
[ 1317.270230] [<ffffffff83e4cece>] SyS_bind+0xe/0x10
[ 1317.270230] [<ffffffff843a6ad0>] tracesys+0xdd/0xe2
[ 1317.270230] Code: 00 8b 45 cc 48 8d 75 d0 48 c7 45 d8 00 00 00 00 66 c7 45 d0 02 00
89 45 d4 48 89 df e8 78 49 76 ff 41 89 c4 85 c0 75 0c 48 8b 03 <80> b8 74 09 00 00 01 7
4 06 41 bc 9d ff ff ff f6 05 2a b6 c2 02
[ 1317.270230] RIP [<ffffffff84225f52>] rds_ib_laddr_check+0x82/0x110
[ 1317.270230] RSP <ffff8803cd31bdf8>
[ 1317.270230] CR2: 0000000000000974
Signed-off-by: Sasha Levin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int rds_ib_laddr_check(__be32 addr)
{
int ret;
struct rdma_cm_id *cm_id;
struct sockaddr_in sin;
/* Create a CMA ID and try to bind it. This catches both
* IB and iWARP capable NICs.
*/
cm_id = rdma_create_id(NULL, NULL, RDMA_PS_TCP, IB_QPT_RC);
if (IS_ERR(cm_id))
return PTR_ERR(cm_id);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = addr;
/* rdma_bind_addr will only succeed for IB & iWARP devices */
ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);
/* due to this, we will claim to support iWARP devices unless we
check node_type. */
if (ret || !cm_id->device ||
cm_id->device->node_type != RDMA_NODE_IB_CA)
ret = -EADDRNOTAVAIL;
rdsdebug("addr %pI4 ret %d node type %d\n",
&addr, ret,
cm_id->device ? cm_id->device->node_type : -1);
rdma_destroy_id(cm_id);
return ret;
}
| 166,469 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame,
WebKit::WebNode* node,
bool is_preview) {
DCHECK(frame);
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
&settings.params));
bool result = true;
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
if (!is_preview) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
result = false;
}
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
NOTREACHED();
result = false;
}
settings.pages.clear();
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
return result;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame,
bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame) {
DCHECK(frame);
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
&settings.params));
bool result = true;
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
result = false;
}
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
NOTREACHED();
result = false;
}
settings.pages.clear();
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
return result;
}
| 170,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static PassRefPtr<Uint8Array> copySkImageData(SkImage* input,
const SkImageInfo& info) {
size_t width = static_cast<size_t>(input->width());
RefPtr<ArrayBuffer> dstBuffer =
ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> dstPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0,
0);
return dstPixels;
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static PassRefPtr<Uint8Array> copySkImageData(SkImage* input,
const SkImageInfo& info) {
// width * height * bytesPerPixel will never overflow unsigned.
unsigned width = static_cast<unsigned>(input->width());
RefPtr<ArrayBuffer> dstBuffer =
ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> dstPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0,
0);
return dstPixels;
}
| 172,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
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 | virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.psnr.psnr[0] < min_psnr_)
min_psnr_ = pkt->data.psnr.psnr[0];
}
| 174,512 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: on_handler_appeared(GDBusConnection *connection,
const gchar *name,
const gchar *name_owner,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
info->connection = connection;
tcmur_register_handler(handler);
dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config));
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
info->register_invocation = NULL;
}
}
Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.
CWE ID: CWE-476 | on_handler_appeared(GDBusConnection *connection,
const gchar *name,
const gchar *name_owner,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
info->connection = connection;
tcmur_register_dbus_handler(handler);
dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config));
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
info->register_invocation = NULL;
}
}
| 167,631 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: path_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PATH *path;
int isopen;
char *s;
int npts;
int size;
int depth = 0;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
s = str;
while (isspace((unsigned char) *s))
s++;
/* skip single leading paren */
if ((*s == LDELIM) && (strrchr(s, LDELIM) == s))
{
s++;
depth++;
}
size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * npts;
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = npts;
if ((!path_decode(TRUE, npts, s, &isopen, &s, &(path->p[0])))
&& (!((depth == 0) && (*s == '\0'))) && !((depth >= 1) && (*s == RDELIM)))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
path->closed = (!isopen);
/* prevent instability in unused pad bytes */
path->dummy = 0;
PG_RETURN_PATH_P(path);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | path_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PATH *path;
int isopen;
char *s;
int npts;
int size;
int base_size;
int depth = 0;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
s = str;
while (isspace((unsigned char) *s))
s++;
/* skip single leading paren */
if ((*s == LDELIM) && (strrchr(s, LDELIM) == s))
{
s++;
depth++;
}
base_size = sizeof(path->p[0]) * npts;
size = offsetof(PATH, p[0]) + base_size;
/* Check for integer overflow */
if (base_size / npts != sizeof(path->p[0]) || size <= base_size)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("too many points requested")));
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = npts;
if ((!path_decode(TRUE, npts, s, &isopen, &s, &(path->p[0])))
&& (!((depth == 0) && (*s == '\0'))) && !((depth >= 1) && (*s == RDELIM)))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
path->closed = (!isopen);
/* prevent instability in unused pad bytes */
path->dummy = 0;
PG_RETURN_PATH_P(path);
}
| 166,409 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: modifier_color_encoding_is_set(PNG_CONST png_modifier *pm)
{
return pm->current_gamma != 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | modifier_color_encoding_is_set(PNG_CONST png_modifier *pm)
modifier_color_encoding_is_set(const png_modifier *pm)
{
return pm->current_gamma != 0;
}
| 173,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[1024];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
sprintf (pathName, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
int errCode = doc->savePageAs(gpageName, pageNo);
if ( errCode != errNone) {
delete gpageName;
delete gfileName;
return false;
}
delete gpageName;
}
delete gfileName;
return true;
}
Commit Message:
CWE ID: CWE-119 | bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
int errCode = doc->savePageAs(gpageName, pageNo);
if ( errCode != errNone) {
delete gpageName;
delete gfileName;
return false;
}
delete gpageName;
}
delete gfileName;
return true;
}
| 164,654 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> fooCallback(const v8::Arguments& args)
{
INC_STATS("DOM.Float64Array.foo");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
Float64Array* imp = V8Float64Array::toNative(args.Holder());
EXCEPTION_BLOCK(Float32Array*, array, V8Float32Array::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Float32Array::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
return toV8(imp->foo(array), args.GetIsolate());
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> fooCallback(const v8::Arguments& args)
{
INC_STATS("DOM.Float64Array.foo");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
Float64Array* imp = V8Float64Array::toNative(args.Holder());
EXCEPTION_BLOCK(Float32Array*, array, V8Float32Array::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Float32Array::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
return toV8(imp->foo(array), args.GetIsolate());
}
| 171,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t oz_cdev_write(struct file *filp, const char __user *buf,
size_t count, loff_t *fpos)
{
struct oz_pd *pd;
struct oz_elt_buf *eb;
struct oz_elt_info *ei;
struct oz_elt *elt;
struct oz_app_hdr *app_hdr;
struct oz_serial_ctx *ctx;
spin_lock_bh(&g_cdev.lock);
pd = g_cdev.active_pd;
if (pd)
oz_pd_get(pd);
spin_unlock_bh(&g_cdev.lock);
if (pd == NULL)
return -ENXIO;
if (!(pd->state & OZ_PD_S_CONNECTED))
return -EAGAIN;
eb = &pd->elt_buff;
ei = oz_elt_info_alloc(eb);
if (ei == NULL) {
count = 0;
goto out;
}
elt = (struct oz_elt *)ei->data;
app_hdr = (struct oz_app_hdr *)(elt+1);
elt->length = sizeof(struct oz_app_hdr) + count;
elt->type = OZ_ELT_APP_DATA;
ei->app_id = OZ_APPID_SERIAL;
ei->length = elt->length + sizeof(struct oz_elt);
app_hdr->app_id = OZ_APPID_SERIAL;
if (copy_from_user(app_hdr+1, buf, count))
goto out;
spin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]);
ctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1];
if (ctx) {
app_hdr->elt_seq_num = ctx->tx_seq_num++;
if (ctx->tx_seq_num == 0)
ctx->tx_seq_num = 1;
spin_lock(&eb->lock);
if (oz_queue_elt_info(eb, 0, 0, ei) == 0)
ei = NULL;
spin_unlock(&eb->lock);
}
spin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]);
out:
if (ei) {
count = 0;
spin_lock_bh(&eb->lock);
oz_elt_info_free(eb, ei);
spin_unlock_bh(&eb->lock);
}
oz_pd_put(pd);
return count;
}
Commit Message: staging: ozwpan: prevent overflow in oz_cdev_write()
We need to check "count" so we don't overflow the ei->data buffer.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119 | static ssize_t oz_cdev_write(struct file *filp, const char __user *buf,
size_t count, loff_t *fpos)
{
struct oz_pd *pd;
struct oz_elt_buf *eb;
struct oz_elt_info *ei;
struct oz_elt *elt;
struct oz_app_hdr *app_hdr;
struct oz_serial_ctx *ctx;
if (count > sizeof(ei->data) - sizeof(*elt) - sizeof(*app_hdr))
return -EINVAL;
spin_lock_bh(&g_cdev.lock);
pd = g_cdev.active_pd;
if (pd)
oz_pd_get(pd);
spin_unlock_bh(&g_cdev.lock);
if (pd == NULL)
return -ENXIO;
if (!(pd->state & OZ_PD_S_CONNECTED))
return -EAGAIN;
eb = &pd->elt_buff;
ei = oz_elt_info_alloc(eb);
if (ei == NULL) {
count = 0;
goto out;
}
elt = (struct oz_elt *)ei->data;
app_hdr = (struct oz_app_hdr *)(elt+1);
elt->length = sizeof(struct oz_app_hdr) + count;
elt->type = OZ_ELT_APP_DATA;
ei->app_id = OZ_APPID_SERIAL;
ei->length = elt->length + sizeof(struct oz_elt);
app_hdr->app_id = OZ_APPID_SERIAL;
if (copy_from_user(app_hdr+1, buf, count))
goto out;
spin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]);
ctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1];
if (ctx) {
app_hdr->elt_seq_num = ctx->tx_seq_num++;
if (ctx->tx_seq_num == 0)
ctx->tx_seq_num = 1;
spin_lock(&eb->lock);
if (oz_queue_elt_info(eb, 0, 0, ei) == 0)
ei = NULL;
spin_unlock(&eb->lock);
}
spin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]);
out:
if (ei) {
count = 0;
spin_lock_bh(&eb->lock);
oz_elt_info_free(eb, ei);
spin_unlock_bh(&eb->lock);
}
oz_pd_put(pd);
return count;
}
| 165,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
Commit Message: udf: Fortify loading of sparing table
Add sanity checks when loading sparing table from disk to avoid accessing
unallocated memory or writing to it.
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-119 | static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
if (udf_load_sparable_map(sb, map,
(struct sparablePartitionMap *)gpm) < 0)
goto out_bh;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
| 169,877 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
GetIndexedDBObserver()->TaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread,
base::Unretained(GetIndexedDBObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) {
if (!storage_partition_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
GetIndexedDBObserver()->TaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread,
base::Unretained(GetIndexedDBObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
| 172,779 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
PNG_CONST char *name)
{
/* Set the name for png_error */
safecat(ps->test, sizeof ps->test, 0, name);
if (ps->pread != NULL)
png_error(ps->pread, "read store already in use");
store_read_reset(ps);
/* Both the create APIs can return NULL if used in their default mode
* (because there is no other way of handling an error because the jmp_buf
* by default is stored in png_struct and that has not been allocated!)
* However, given that store_error works correctly in these circumstances
* we don't ever expect NULL in this program.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
store_error, store_warning, &ps->read_memory_pool, store_malloc,
store_free);
else
# endif
ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
store_warning);
if (ps->pread == NULL)
{
struct exception_context *the_exception_context = &ps->exception_context;
store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
1 /*error*/);
Throw ps;
}
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pread, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pread, "png option invalid");
}
# endif
store_read_set(ps, id);
if (ppi != NULL)
*ppi = ps->piread = png_create_info_struct(ps->pread);
return ps->pread;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
const char *name)
{
/* Set the name for png_error */
safecat(ps->test, sizeof ps->test, 0, name);
if (ps->pread != NULL)
png_error(ps->pread, "read store already in use");
store_read_reset(ps);
/* Both the create APIs can return NULL if used in their default mode
* (because there is no other way of handling an error because the jmp_buf
* by default is stored in png_struct and that has not been allocated!)
* However, given that store_error works correctly in these circumstances
* we don't ever expect NULL in this program.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
store_error, store_warning, &ps->read_memory_pool, store_malloc,
store_free);
else
# endif
ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
store_warning);
if (ps->pread == NULL)
{
struct exception_context *the_exception_context = &ps->exception_context;
store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
1 /*error*/);
Throw ps;
}
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pread, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pread, "png option invalid");
}
# endif
store_read_set(ps, id);
if (ppi != NULL)
*ppi = ps->piread = png_create_info_struct(ps->pread);
return ps->pread;
}
| 173,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
| 167,949 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (addr_len)
*addr_len = sizeof(struct sockaddr_in6);
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
}
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
*addr_len = sizeof(*sin6);
}
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 166,481 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int irssi_ssl_handshake(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
int ret, err;
X509 *cert;
const char *errstr;
ret = SSL_connect(chan->ssl);
if (ret <= 0) {
err = SSL_get_error(chan->ssl, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
return 1;
case SSL_ERROR_WANT_WRITE:
return 3;
case SSL_ERROR_ZERO_RETURN:
g_warning("SSL handshake failed: %s", "server closed connection");
return -1;
case SSL_ERROR_SYSCALL:
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret == -1)
errstr = strerror(errno);
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly");
return -1;
default:
errstr = ERR_reason_error_string(ERR_get_error());
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error");
return -1;
}
}
cert = SSL_get_peer_certificate(chan->ssl);
if (cert == NULL) {
g_warning("SSL server supplied no certificate");
return -1;
}
ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, cert);
X509_free(cert);
return ret ? 0 : -1;
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20 | int irssi_ssl_handshake(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
int ret, err;
X509 *cert;
const char *errstr;
ret = SSL_connect(chan->ssl);
if (ret <= 0) {
err = SSL_get_error(chan->ssl, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
return 1;
case SSL_ERROR_WANT_WRITE:
return 3;
case SSL_ERROR_ZERO_RETURN:
g_warning("SSL handshake failed: %s", "server closed connection");
return -1;
case SSL_ERROR_SYSCALL:
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret == -1)
errstr = strerror(errno);
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly");
return -1;
default:
errstr = ERR_reason_error_string(ERR_get_error());
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error");
return -1;
}
}
cert = SSL_get_peer_certificate(chan->ssl);
if (cert == NULL) {
g_warning("SSL server supplied no certificate");
return -1;
}
ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, chan->hostname, cert);
X509_free(cert);
return ret ? 0 : -1;
}
| 165,517 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IndexedDBCursor::~IndexedDBCursor() {
Close();
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: [email protected]
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416 | IndexedDBCursor::~IndexedDBCursor() {
if (transaction_)
transaction_->UnregisterOpenCursor(this);
Close();
}
| 172,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_request(int fd, debugger_request_t* out_request) {
ucred cr;
socklen_t len = sizeof(cr);
int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
if (status != 0) {
ALOGE("cannot get credentials");
return -1;
}
ALOGV("reading tid");
fcntl(fd, F_SETFL, O_NONBLOCK);
pollfd pollfds[1];
pollfds[0].fd = fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000));
if (status != 1) {
ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid);
return -1;
}
debugger_msg_t msg;
memset(&msg, 0, sizeof(msg));
status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg)));
if (status < 0) {
ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid);
return -1;
}
if (status != sizeof(debugger_msg_t)) {
ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid);
return -1;
}
out_request->action = static_cast<debugger_action_t>(msg.action);
out_request->tid = msg.tid;
out_request->pid = cr.pid;
out_request->uid = cr.uid;
out_request->gid = cr.gid;
out_request->abort_msg_address = msg.abort_msg_address;
out_request->original_si_code = msg.original_si_code;
if (msg.action == DEBUGGER_ACTION_CRASH) {
char buf[64];
struct stat s;
snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid);
if (stat(buf, &s)) {
ALOGE("tid %d does not exist in pid %d. ignoring debug request\n",
out_request->tid, out_request->pid);
return -1;
}
} else if (cr.uid == 0
|| (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) {
status = get_process_info(out_request->tid, &out_request->pid,
&out_request->uid, &out_request->gid);
if (status < 0) {
ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid);
return -1;
}
if (!selinux_action_allowed(fd, out_request))
return -1;
} else {
return -1;
}
return 0;
}
Commit Message: debuggerd: verify that traced threads belong to the right process.
Fix two races in debuggerd's PTRACE_ATTACH logic:
1. The target thread in a crash dump request could exit between the
/proc/<pid>/task/<tid> check and the PTRACE_ATTACH.
2. Sibling threads could exit between listing /proc/<pid>/task and the
PTRACE_ATTACH.
Bug: http://b/29555636
Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591
CWE ID: CWE-264 | static int read_request(int fd, debugger_request_t* out_request) {
ucred cr;
socklen_t len = sizeof(cr);
int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
if (status != 0) {
ALOGE("cannot get credentials");
return -1;
}
ALOGV("reading tid");
fcntl(fd, F_SETFL, O_NONBLOCK);
pollfd pollfds[1];
pollfds[0].fd = fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000));
if (status != 1) {
ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid);
return -1;
}
debugger_msg_t msg;
memset(&msg, 0, sizeof(msg));
status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg)));
if (status < 0) {
ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid);
return -1;
}
if (status != sizeof(debugger_msg_t)) {
ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid);
return -1;
}
out_request->action = static_cast<debugger_action_t>(msg.action);
out_request->tid = msg.tid;
out_request->pid = cr.pid;
out_request->uid = cr.uid;
out_request->gid = cr.gid;
out_request->abort_msg_address = msg.abort_msg_address;
out_request->original_si_code = msg.original_si_code;
if (msg.action == DEBUGGER_ACTION_CRASH) {
// This check needs to happen again after ptracing the requested thread to prevent a race.
if (!pid_contains_tid(out_request->pid, out_request->tid)) {
ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid,
out_request->pid);
return -1;
}
} else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) {
status = get_process_info(out_request->tid, &out_request->pid,
&out_request->uid, &out_request->gid);
if (status < 0) {
ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid);
return -1;
}
if (!selinux_action_allowed(fd, out_request))
return -1;
} else {
return -1;
}
return 0;
}
| 173,407 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
Commit Message:
CWE ID: CWE-17 | int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
| 164,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftMP3::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.mp3",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(const OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftMP3::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.mp3",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(const OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _exsltDateAdd (exsltDateValPtr dt, exsltDateValPtr dur)
{
exsltDateValPtr ret;
long carry, tempdays, temp;
exsltDateValDatePtr r, d;
exsltDateValDurationPtr u;
if ((dt == NULL) || (dur == NULL))
return NULL;
ret = exsltDateCreateDate(dt->type);
if (ret == NULL)
return NULL;
r = &(ret->value.date);
d = &(dt->value.date);
u = &(dur->value.dur);
/* normalization */
if (d->mon == 0)
d->mon = 1;
/* normalize for time zone offset */
u->sec -= (d->tzo * 60); /* changed from + to - (bug 153000) */
d->tzo = 0;
/* normalization */
if (d->day == 0)
d->day = 1;
/* month */
carry = d->mon + u->mon;
r->mon = (unsigned int)MODULO_RANGE(carry, 1, 13);
carry = (long)FQUOTIENT_RANGE(carry, 1, 13);
/* year (may be modified later) */
r->year = d->year + carry;
if (r->year == 0) {
if (d->year > 0)
r->year--;
else
r->year++;
}
/* time zone */
r->tzo = d->tzo;
r->tz_flag = d->tz_flag;
/* seconds */
r->sec = d->sec + u->sec;
carry = (long)FQUOTIENT((long)r->sec, 60);
if (r->sec != 0.0) {
r->sec = MODULO(r->sec, 60.0);
}
/* minute */
carry += d->min;
r->min = (unsigned int)MODULO(carry, 60);
carry = (long)FQUOTIENT(carry, 60);
/* hours */
carry += d->hour;
r->hour = (unsigned int)MODULO(carry, 24);
carry = (long)FQUOTIENT(carry, 24);
/*
* days
* Note we use tempdays because the temporary values may need more
* than 5 bits
*/
if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) &&
(d->day > MAX_DAYINMONTH(r->year, r->mon)))
tempdays = MAX_DAYINMONTH(r->year, r->mon);
else if (d->day < 1)
tempdays = 1;
else
tempdays = d->day;
tempdays += u->day + carry;
while (1) {
if (tempdays < 1) {
long tmon = (long)MODULO_RANGE((int)r->mon-1, 1, 13);
long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13);
if (tyr == 0)
tyr--;
/*
* Coverity detected an overrun in daysInMonth
* of size 12 at position 12 with index variable "((r)->mon - 1)"
*/
if (tmon < 0)
tmon = 0;
if (tmon > 12)
tmon = 12;
tempdays += MAX_DAYINMONTH(tyr, tmon);
carry = -1;
} else if (tempdays > (long)MAX_DAYINMONTH(r->year, r->mon)) {
tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon);
carry = 1;
} else
break;
temp = r->mon + carry;
r->mon = (unsigned int)MODULO_RANGE(temp, 1, 13);
r->year = r->year + (long)FQUOTIENT_RANGE(temp, 1, 13);
if (r->year == 0) {
if (temp < 1)
r->year--;
else
r->year++;
}
}
r->day = tempdays;
/*
* adjust the date/time type to the date values
*/
if (ret->type != XS_DATETIME) {
if ((r->hour) || (r->min) || (r->sec))
ret->type = XS_DATETIME;
else if (ret->type != XS_DATE) {
if (r->day != 1)
ret->type = XS_DATE;
else if ((ret->type != XS_GYEARMONTH) && (r->mon != 1))
ret->type = XS_GYEARMONTH;
}
}
return ret;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | _exsltDateAdd (exsltDateValPtr dt, exsltDateValPtr dur)
{
exsltDateValPtr ret;
long carry, tempdays, temp;
exsltDateValDatePtr r, d;
exsltDateValDurationPtr u;
if ((dt == NULL) || (dur == NULL))
return NULL;
ret = exsltDateCreateDate(dt->type);
if (ret == NULL)
return NULL;
r = &(ret->value.date);
d = &(dt->value.date);
u = &(dur->value.dur);
/* normalize for time zone offset */
u->sec -= (d->tzo * 60); /* changed from + to - (bug 153000) */
d->tzo = 0;
/* month */
carry = d->mon + u->mon;
r->mon = (unsigned int)MODULO_RANGE(carry, 1, 13);
carry = (long)FQUOTIENT_RANGE(carry, 1, 13);
/* year (may be modified later) */
r->year = d->year + carry;
if (r->year == 0) {
if (d->year > 0)
r->year--;
else
r->year++;
}
/* time zone */
r->tzo = d->tzo;
r->tz_flag = d->tz_flag;
/* seconds */
r->sec = d->sec + u->sec;
carry = (long)FQUOTIENT((long)r->sec, 60);
if (r->sec != 0.0) {
r->sec = MODULO(r->sec, 60.0);
}
/* minute */
carry += d->min;
r->min = (unsigned int)MODULO(carry, 60);
carry = (long)FQUOTIENT(carry, 60);
/* hours */
carry += d->hour;
r->hour = (unsigned int)MODULO(carry, 24);
carry = (long)FQUOTIENT(carry, 24);
/*
* days
* Note we use tempdays because the temporary values may need more
* than 5 bits
*/
if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) &&
(d->day > MAX_DAYINMONTH(r->year, r->mon)))
tempdays = MAX_DAYINMONTH(r->year, r->mon);
else if (d->day < 1)
tempdays = 1;
else
tempdays = d->day;
tempdays += u->day + carry;
while (1) {
if (tempdays < 1) {
long tmon = (long)MODULO_RANGE((int)r->mon-1, 1, 13);
long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13);
if (tyr == 0)
tyr--;
/*
* Coverity detected an overrun in daysInMonth
* of size 12 at position 12 with index variable "((r)->mon - 1)"
*/
if (tmon < 0)
tmon = 0;
if (tmon > 12)
tmon = 12;
tempdays += MAX_DAYINMONTH(tyr, tmon);
carry = -1;
} else if (tempdays > (long)MAX_DAYINMONTH(r->year, r->mon)) {
tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon);
carry = 1;
} else
break;
temp = r->mon + carry;
r->mon = (unsigned int)MODULO_RANGE(temp, 1, 13);
r->year = r->year + (long)FQUOTIENT_RANGE(temp, 1, 13);
if (r->year == 0) {
if (temp < 1)
r->year--;
else
r->year++;
}
}
r->day = tempdays;
/*
* adjust the date/time type to the date values
*/
if (ret->type != XS_DATETIME) {
if ((r->hour) || (r->min) || (r->sec))
ret->type = XS_DATETIME;
else if (ret->type != XS_DATE) {
if (r->day != 1)
ret->type = XS_DATE;
else if ((ret->type != XS_GYEARMONTH) && (r->mon != 1))
ret->type = XS_GYEARMONTH;
}
}
return ret;
}
| 173,289 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GDataDirectory::FromProto(const GDataDirectoryProto& proto) {
DCHECK(proto.gdata_entry().file_info().is_directory());
DCHECK(!proto.gdata_entry().has_file_specific_info());
for (int i = 0; i < proto.child_files_size(); ++i) {
scoped_ptr<GDataFile> file(new GDataFile(NULL, directory_service_));
if (!file->FromProto(proto.child_files(i))) {
RemoveChildren();
return false;
}
AddEntry(file.release());
}
for (int i = 0; i < proto.child_directories_size(); ++i) {
scoped_ptr<GDataDirectory> dir(new GDataDirectory(NULL,
directory_service_));
if (!dir->FromProto(proto.child_directories(i))) {
RemoveChildren();
return false;
}
AddEntry(dir.release());
}
if (!GDataEntry::FromProto(proto.gdata_entry()))
return false;
return true;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool GDataDirectory::FromProto(const GDataDirectoryProto& proto) {
DCHECK(proto.gdata_entry().file_info().is_directory());
DCHECK(!proto.gdata_entry().has_file_specific_info());
for (int i = 0; i < proto.child_files_size(); ++i) {
scoped_ptr<GDataFile> file(directory_service_->CreateGDataFile());
if (!file->FromProto(proto.child_files(i))) {
RemoveChildren();
return false;
}
AddEntry(file.release());
}
for (int i = 0; i < proto.child_directories_size(); ++i) {
scoped_ptr<GDataDirectory> dir(directory_service_->CreateGDataDirectory());
if (!dir->FromProto(proto.child_directories(i))) {
RemoveChildren();
return false;
}
AddEntry(dir.release());
}
if (!GDataEntry::FromProto(proto.gdata_entry()))
return false;
return true;
}
| 171,487 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string* GetTestingDMToken() {
static std::string dm_token;
return &dm_token;
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <[email protected]>
Reviewed-by: Tien Mai <[email protected]>
Reviewed-by: Daniel Rubery <[email protected]>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20 | std::string* GetTestingDMToken() {
const char** GetTestingDMTokenStorage() {
static const char* dm_token = "";
return &dm_token;
}
| 172,354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.