instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: flac_buffer_copy (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
const FLAC__Frame *frame = pflac->frame ;
const int32_t* const *buffer = pflac->wbuffer ;
unsigned i = 0, j, offset, channels, len ;
/*
** frame->header.blocksize is variable and we're using a constant blocksize
** of FLAC__MAX_BLOCK_SIZE.
** Check our assumptions here.
*/
if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
{ psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
psf->error = SFE_INTERNAL ;
return 0 ;
} ;
if (frame->header.channels > FLAC__MAX_CHANNELS)
psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ;
channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ;
if (pflac->ptr == NULL)
{ /*
** Not sure why this code is here and not elsewhere.
** Removing it causes valgrind errors.
*/
pflac->bufferbackup = SF_TRUE ;
for (i = 0 ; i < channels ; i++)
{
if (pflac->rbuffer [i] == NULL)
pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;
memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ;
} ;
pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;
return 0 ;
} ;
len = SF_MIN (pflac->len, frame->header.blocksize) ;
switch (pflac->pcmtype)
{ case PFLAC_PCM_SHORT :
{ short *retpcm = (short*) pflac->ptr ;
int shift = 16 - frame->header.bits_per_sample ;
if (shift < 0)
{ shift = abs (shift) ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
}
}
else
{ for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
} ;
break ;
case PFLAC_PCM_INT :
{ int *retpcm = (int*) pflac->ptr ;
int shift = 32 - frame->header.bits_per_sample ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_FLOAT :
{ float *retpcm = (float*) pflac->ptr ;
float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_DOUBLE :
{ double *retpcm = (double*) pflac->ptr ;
double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
default :
return 0 ;
} ;
offset = i * channels ;
pflac->pos += i * channels ;
return offset ;
} /* flac_buffer_copy */
Commit Message: src/flac.c: Improve error handling
Especially when dealing with corrupt or malicious files.
CWE ID: CWE-119 | flac_buffer_copy (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
const FLAC__Frame *frame = pflac->frame ;
const int32_t* const *buffer = pflac->wbuffer ;
unsigned i = 0, j, offset, channels, len ;
/*
** frame->header.blocksize is variable and we're using a constant blocksize
** of FLAC__MAX_BLOCK_SIZE.
** Check our assumptions here.
*/
if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
{ psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
psf->error = SFE_INTERNAL ;
return 0 ;
} ;
if (frame->header.channels > FLAC__MAX_CHANNELS)
psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ;
channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ;
if (pflac->ptr == NULL)
{ /*
** This pointer is reset to NULL each time the current frame has been
** decoded. Somehow its used during encoding and decoding.
*/
for (i = 0 ; i < channels ; i++)
{
if (pflac->rbuffer [i] == NULL)
pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;
memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ;
} ;
pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;
return 0 ;
} ;
len = SF_MIN (pflac->len, frame->header.blocksize) ;
if (pflac->remain % channels != 0)
{ psf_log_printf (psf, "Error: pflac->remain %u channels %u\n", pflac->remain, channels) ;
return 0 ;
} ;
switch (pflac->pcmtype)
{ case PFLAC_PCM_SHORT :
{ short *retpcm = (short*) pflac->ptr ;
int shift = 16 - frame->header.bits_per_sample ;
if (shift < 0)
{ shift = abs (shift) ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
}
}
else
{ for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
} ;
break ;
case PFLAC_PCM_INT :
{ int *retpcm = (int*) pflac->ptr ;
int shift = 32 - frame->header.bits_per_sample ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_FLOAT :
{ float *retpcm = (float*) pflac->ptr ;
float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_DOUBLE :
{ double *retpcm = (double*) pflac->ptr ;
double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
default :
return 0 ;
} ;
offset = i * channels ;
pflac->pos += i * channels ;
return offset ;
} /* flac_buffer_copy */
| 168,254 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
base::SharedMemory shared_memory(transfer_buffer, false);
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
uint32 size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
base::SharedMemory shared_memory(transfer_buffer, false);
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 171,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap,
cherokee_connection_t *conn)
{
int re;
ret_t ret;
size_t size;
char *dn;
LDAPMessage *message;
LDAPMessage *first;
char *attrs[] = { LDAP_NO_ATTRS, NULL };
cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap);
/* Sanity checks
*/
if ((conn->validator == NULL) ||
cherokee_buffer_is_empty (&conn->validator->user))
return ret_error;
size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()");
if (size != conn->validator->user.len)
return ret_error;
/* Build filter
*/
ret = init_filter (ldap, props, conn);
if (ret != ret_ok)
return ret;
/* Search
*/
re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message);
if (re != LDAP_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH,
props->filter.buf ? props->filter.buf : "");
return ret_error;
}
TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : "");
/* Check that there a single entry
*/
re = ldap_count_entries (ldap->conn, message);
if (re != 1) {
ldap_msgfree (message);
return ret_not_found;
}
/* Pick up the first one
*/
first = ldap_first_entry (ldap->conn, message);
if (first == NULL) {
ldap_msgfree (message);
return ret_not_found;
}
/* Get DN
*/
dn = ldap_get_dn (ldap->conn, first);
if (dn == NULL) {
ldap_msgfree (message);
return ret_error;
}
ldap_msgfree (message);
/* Check that it's right
*/
ret = validate_dn (props, dn, conn->validator->passwd.buf);
if (ret != ret_ok)
return ret;
/* Disconnect from the LDAP server
*/
re = ldap_unbind_s (ldap->conn);
if (re != LDAP_SUCCESS)
return ret_error;
/* Validated!
*/
TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf);
return ret_ok;
}
Commit Message: Prevent the LDAP validator from accepting an empty password.
CWE ID: CWE-287 | cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap,
cherokee_connection_t *conn)
{
int re;
ret_t ret;
size_t size;
char *dn;
LDAPMessage *message;
LDAPMessage *first;
char *attrs[] = { LDAP_NO_ATTRS, NULL };
cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap);
/* Sanity checks
*/
if ((conn->validator == NULL) ||
cherokee_buffer_is_empty (&conn->validator->user) ||
cherokee_buffer_is_empty (&conn->validator->passwd))
return ret_error;
size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()");
if (size != conn->validator->user.len)
return ret_error;
/* Build filter
*/
ret = init_filter (ldap, props, conn);
if (ret != ret_ok)
return ret;
/* Search
*/
re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message);
if (re != LDAP_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH,
props->filter.buf ? props->filter.buf : "");
return ret_error;
}
TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : "");
/* Check that there a single entry
*/
re = ldap_count_entries (ldap->conn, message);
if (re != 1) {
ldap_msgfree (message);
return ret_not_found;
}
/* Pick up the first one
*/
first = ldap_first_entry (ldap->conn, message);
if (first == NULL) {
ldap_msgfree (message);
return ret_not_found;
}
/* Get DN
*/
dn = ldap_get_dn (ldap->conn, first);
if (dn == NULL) {
ldap_msgfree (message);
return ret_error;
}
ldap_msgfree (message);
/* Check that it's right
*/
ret = validate_dn (props, dn, conn->validator->passwd.buf);
if (ret != ret_ok)
return ret;
/* Disconnect from the LDAP server
*/
re = ldap_unbind_s (ldap->conn);
if (re != LDAP_SUCCESS)
return ret_error;
/* Validated!
*/
TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf);
return ret_ok;
}
| 166,288 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) {
std::string path;
CHECK(args->GetString(0, &path));
DCHECK(StartsWithASCII(path, "chrome://favicon/", false)) << "path is "
<< path;
path = path.substr(arraysize("chrome://favicon/") - 1);
double id;
CHECK(args->GetDouble(1, &id));
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (!favicon_service || path.empty())
return;
FaviconService::Handle handle = favicon_service->GetFaviconForURL(
GURL(path),
history::FAVICON,
&consumer_,
NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable));
consumer_.SetClientData(favicon_service, handle, static_cast<int>(id));
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) {
std::string path;
CHECK(args->GetString(0, &path));
DCHECK(StartsWithASCII(path, "chrome://favicon/size/32/", false)) <<
"path is " << path;
path = path.substr(arraysize("chrome://favicon/size/32/") - 1);
double id;
CHECK(args->GetDouble(1, &id));
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (!favicon_service || path.empty())
return;
FaviconService::Handle handle = favicon_service->GetFaviconForURL(
GURL(path),
history::FAVICON,
&consumer_,
NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable));
consumer_.SetClientData(favicon_service, handle, static_cast<int>(id));
}
| 170,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: u32 h264bsdActivateParamSets(storage_t *pStorage, u32 ppsId, u32 isIdr)
{
/* Variables */
u32 tmp;
u32 flag;
/* Code */
ASSERT(pStorage);
ASSERT(ppsId < MAX_NUM_PIC_PARAM_SETS);
/* check that pps and corresponding sps exist */
if ( (pStorage->pps[ppsId] == NULL) ||
(pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId] == NULL) )
{
return(HANTRO_NOK);
}
/* check that pps parameters do not violate picture size constraints */
tmp = CheckPps(pStorage->pps[ppsId],
pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId]);
if (tmp != HANTRO_OK)
return(tmp);
/* first activation part1 */
if (pStorage->activePpsId == MAX_NUM_PIC_PARAM_SETS)
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
pStorage->activeSpsId = pStorage->activePps->seqParameterSetId;
pStorage->activeSps = pStorage->sps[pStorage->activeSpsId];
pStorage->picSizeInMbs =
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs;
pStorage->currImage->width = pStorage->activeSps->picWidthInMbs;
pStorage->currImage->height = pStorage->activeSps->picHeightInMbs;
pStorage->pendingActivation = HANTRO_TRUE;
}
/* first activation part2 */
else if (pStorage->pendingActivation)
{
pStorage->pendingActivation = HANTRO_FALSE;
FREE(pStorage->mb);
FREE(pStorage->sliceGroupMap);
ALLOCATE(pStorage->mb, pStorage->picSizeInMbs, mbStorage_t);
ALLOCATE(pStorage->sliceGroupMap, pStorage->picSizeInMbs, u32);
if (pStorage->mb == NULL || pStorage->sliceGroupMap == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(pStorage->mb, 0,
pStorage->picSizeInMbs * sizeof(mbStorage_t));
h264bsdInitMbNeighbours(pStorage->mb,
pStorage->activeSps->picWidthInMbs,
pStorage->picSizeInMbs);
/* dpb output reordering disabled if
* 1) application set noReordering flag
* 2) POC type equal to 2
* 3) num_reorder_frames in vui equal to 0 */
if ( pStorage->noReordering ||
pStorage->activeSps->picOrderCntType == 2 ||
(pStorage->activeSps->vuiParametersPresentFlag &&
pStorage->activeSps->vuiParameters->bitstreamRestrictionFlag &&
!pStorage->activeSps->vuiParameters->numReorderFrames) )
flag = HANTRO_TRUE;
else
flag = HANTRO_FALSE;
tmp = h264bsdResetDpb(pStorage->dpb,
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs,
pStorage->activeSps->maxDpbSize,
pStorage->activeSps->numRefFrames,
pStorage->activeSps->maxFrameNum,
flag);
if (tmp != HANTRO_OK)
return(tmp);
}
else if (ppsId != pStorage->activePpsId)
{
/* sequence parameter set shall not change but before an IDR picture */
if (pStorage->pps[ppsId]->seqParameterSetId != pStorage->activeSpsId)
{
DEBUG(("SEQ PARAM SET CHANGING...\n"));
if (isIdr)
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
pStorage->activeSpsId = pStorage->activePps->seqParameterSetId;
pStorage->activeSps = pStorage->sps[pStorage->activeSpsId];
pStorage->picSizeInMbs =
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs;
pStorage->currImage->width = pStorage->activeSps->picWidthInMbs;
pStorage->currImage->height =
pStorage->activeSps->picHeightInMbs;
pStorage->pendingActivation = HANTRO_TRUE;
}
else
{
DEBUG(("TRYING TO CHANGE SPS IN NON-IDR SLICE\n"));
return(HANTRO_NOK);
}
}
else
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
}
}
return(HANTRO_OK);
}
Commit Message: h264bsdActivateParamSets: Prevent multiplication overflow.
Report MEMORY_ALLOCATION_ERROR if pStorage->picSizeInMbs would
exceed UINT32_MAX bytes.
Bug: 28532266
Change-Id: Ia6f11efb18818afcdb5fa2a38a14f2a2d8c8447a
CWE ID: CWE-119 | u32 h264bsdActivateParamSets(storage_t *pStorage, u32 ppsId, u32 isIdr)
{
/* Variables */
u32 tmp;
u32 flag;
/* Code */
ASSERT(pStorage);
ASSERT(ppsId < MAX_NUM_PIC_PARAM_SETS);
/* check that pps and corresponding sps exist */
if ( (pStorage->pps[ppsId] == NULL) ||
(pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId] == NULL) )
{
return(HANTRO_NOK);
}
/* check that pps parameters do not violate picture size constraints */
tmp = CheckPps(pStorage->pps[ppsId],
pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId]);
if (tmp != HANTRO_OK)
return(tmp);
/* first activation part1 */
if (pStorage->activePpsId == MAX_NUM_PIC_PARAM_SETS)
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
pStorage->activeSpsId = pStorage->activePps->seqParameterSetId;
pStorage->activeSps = pStorage->sps[pStorage->activeSpsId];
/* report error before multiplication to prevent integer overflow */
if (pStorage->activeSps->picWidthInMbs == 0)
{
pStorage->picSizeInMbs = 0;
}
else if (pStorage->activeSps->picHeightInMbs >
UINT32_MAX / pStorage->activeSps->picWidthInMbs)
{
return(MEMORY_ALLOCATION_ERROR);
}
else
{
pStorage->picSizeInMbs =
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs;
}
pStorage->currImage->width = pStorage->activeSps->picWidthInMbs;
pStorage->currImage->height = pStorage->activeSps->picHeightInMbs;
pStorage->pendingActivation = HANTRO_TRUE;
}
/* first activation part2 */
else if (pStorage->pendingActivation)
{
pStorage->pendingActivation = HANTRO_FALSE;
FREE(pStorage->mb);
FREE(pStorage->sliceGroupMap);
ALLOCATE(pStorage->mb, pStorage->picSizeInMbs, mbStorage_t);
ALLOCATE(pStorage->sliceGroupMap, pStorage->picSizeInMbs, u32);
if (pStorage->mb == NULL || pStorage->sliceGroupMap == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(pStorage->mb, 0,
pStorage->picSizeInMbs * sizeof(mbStorage_t));
h264bsdInitMbNeighbours(pStorage->mb,
pStorage->activeSps->picWidthInMbs,
pStorage->picSizeInMbs);
/* dpb output reordering disabled if
* 1) application set noReordering flag
* 2) POC type equal to 2
* 3) num_reorder_frames in vui equal to 0 */
if ( pStorage->noReordering ||
pStorage->activeSps->picOrderCntType == 2 ||
(pStorage->activeSps->vuiParametersPresentFlag &&
pStorage->activeSps->vuiParameters->bitstreamRestrictionFlag &&
!pStorage->activeSps->vuiParameters->numReorderFrames) )
flag = HANTRO_TRUE;
else
flag = HANTRO_FALSE;
tmp = h264bsdResetDpb(pStorage->dpb,
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs,
pStorage->activeSps->maxDpbSize,
pStorage->activeSps->numRefFrames,
pStorage->activeSps->maxFrameNum,
flag);
if (tmp != HANTRO_OK)
return(tmp);
}
else if (ppsId != pStorage->activePpsId)
{
/* sequence parameter set shall not change but before an IDR picture */
if (pStorage->pps[ppsId]->seqParameterSetId != pStorage->activeSpsId)
{
DEBUG(("SEQ PARAM SET CHANGING...\n"));
if (isIdr)
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
pStorage->activeSpsId = pStorage->activePps->seqParameterSetId;
pStorage->activeSps = pStorage->sps[pStorage->activeSpsId];
pStorage->picSizeInMbs =
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs;
pStorage->currImage->width = pStorage->activeSps->picWidthInMbs;
pStorage->currImage->height =
pStorage->activeSps->picHeightInMbs;
pStorage->pendingActivation = HANTRO_TRUE;
}
else
{
DEBUG(("TRYING TO CHANGE SPS IN NON-IDR SLICE\n"));
return(HANTRO_NOK);
}
}
else
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
}
}
return(HANTRO_OK);
}
| 173,767 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static const char *check_secret(int module, const char *user, const char *group,
const char *challenge, const char *pass)
{
char line[1024];
char pass2[MAX_DIGEST_LEN*2];
const char *fname = lp_secrets_file(module);
STRUCT_STAT st;
int fd, ok = 1;
int user_len = strlen(user);
int group_len = group ? strlen(group) : 0;
char *err;
if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0)
return "no secrets file";
if (do_fstat(fd, &st) == -1) {
rsyserr(FLOG, errno, "fstat(%s)", fname);
ok = 0;
} else if (lp_strict_modes(module)) {
rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
ok = 0;
} else if (MY_UID() == 0 && st.st_uid != 0) {
rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
ok = 0;
}
}
Commit Message:
CWE ID: CWE-20 | static const char *check_secret(int module, const char *user, const char *group,
const char *challenge, const char *pass)
{
char line[1024];
char pass2[MAX_DIGEST_LEN*2];
const char *fname = lp_secrets_file(module);
STRUCT_STAT st;
int ok = 1;
int user_len = strlen(user);
int group_len = group ? strlen(group) : 0;
char *err;
FILE *fh;
if (!fname || !*fname || (fh = fopen(fname, "r")) == NULL)
return "no secrets file";
if (do_fstat(fileno(fh), &st) == -1) {
rsyserr(FLOG, errno, "fstat(%s)", fname);
ok = 0;
} else if (lp_strict_modes(module)) {
rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
ok = 0;
} else if (MY_UID() == 0 && st.st_uid != 0) {
rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
ok = 0;
}
}
| 165,208 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __sock_diag_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
int err;
struct sock_diag_req *req = nlmsg_data(nlh);
const struct sock_diag_handler *hndl;
if (nlmsg_len(nlh) < sizeof(*req))
return -EINVAL;
hndl = sock_diag_lock_handler(req->sdiag_family);
if (hndl == NULL)
err = -ENOENT;
else
err = hndl->dump(skb, nlh);
sock_diag_unlock_handler(hndl);
return err;
}
Commit Message: sock_diag: Fix out-of-bounds access to sock_diag_handlers[]
Userland can send a netlink message requesting SOCK_DIAG_BY_FAMILY
with a family greater or equal then AF_MAX -- the array size of
sock_diag_handlers[]. The current code does not test for this
condition therefore is vulnerable to an out-of-bound access opening
doors for a privilege escalation.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int __sock_diag_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
int err;
struct sock_diag_req *req = nlmsg_data(nlh);
const struct sock_diag_handler *hndl;
if (nlmsg_len(nlh) < sizeof(*req))
return -EINVAL;
if (req->sdiag_family >= AF_MAX)
return -EINVAL;
hndl = sock_diag_lock_handler(req->sdiag_family);
if (hndl == NULL)
err = -ENOENT;
else
err = hndl->dump(skb, nlh);
sock_diag_unlock_handler(hndl);
return err;
}
| 166,128 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PasswordAutofillManager::OnShowPasswordSuggestions(
int key,
base::i18n::TextDirection text_direction,
const base::string16& typed_username,
int options,
const gfx::RectF& bounds) {
std::vector<autofill::Suggestion> suggestions;
LoginToPasswordInfoMap::const_iterator fill_data_it =
login_to_password_info_.find(key);
if (fill_data_it == login_to_password_info_.end()) {
NOTREACHED();
return;
}
GetSuggestions(fill_data_it->second, typed_username, &suggestions,
(options & autofill::SHOW_ALL) != 0,
(options & autofill::IS_PASSWORD_FIELD) != 0);
form_data_key_ = key;
if (suggestions.empty()) {
autofill_client_->HideAutofillPopup();
return;
}
if (options & autofill::IS_PASSWORD_FIELD) {
autofill::Suggestion password_field_suggestions(l10n_util::GetStringUTF16(
IDS_AUTOFILL_PASSWORD_FIELD_SUGGESTIONS_TITLE));
password_field_suggestions.frontend_id = autofill::POPUP_ITEM_ID_TITLE;
suggestions.insert(suggestions.begin(), password_field_suggestions);
}
GURL origin = (fill_data_it->second).origin;
bool is_context_secure = autofill_client_->IsContextSecure() &&
(!origin.is_valid() || !origin.SchemeIs("http"));
if (!is_context_secure && security_state::IsHttpWarningInFormEnabled()) {
std::string icon_str;
if (origin.is_valid() && origin.SchemeIs("http")) {
icon_str = "httpWarning";
} else {
icon_str = "httpsInvalid";
}
autofill::Suggestion http_warning_suggestion(
l10n_util::GetStringUTF8(IDS_AUTOFILL_LOGIN_HTTP_WARNING_MESSAGE),
l10n_util::GetStringUTF8(IDS_AUTOFILL_HTTP_WARNING_LEARN_MORE),
icon_str, autofill::POPUP_ITEM_ID_HTTP_NOT_SECURE_WARNING_MESSAGE);
#if !defined(OS_ANDROID)
suggestions.insert(suggestions.begin(), autofill::Suggestion());
suggestions.front().frontend_id = autofill::POPUP_ITEM_ID_SEPARATOR;
#endif
suggestions.insert(suggestions.begin(), http_warning_suggestion);
if (!did_show_form_not_secure_warning_) {
did_show_form_not_secure_warning_ = true;
metrics_util::LogShowedFormNotSecureWarningOnCurrentNavigation();
}
}
if (ShouldShowManualFallbackForPreLollipop(
autofill_client_->GetSyncService())) {
if (base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksFilling) &&
(options & autofill::IS_PASSWORD_FIELD) && password_client_ &&
password_client_->IsFillingFallbackEnabledForCurrentPage()) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_SHOW_ALL_SAVED_FALLBACK,
autofill::POPUP_ITEM_ID_ALL_SAVED_PASSWORDS_ENTRY, &suggestions);
show_all_saved_passwords_shown_context_ =
metrics_util::SHOW_ALL_SAVED_PASSWORDS_CONTEXT_PASSWORD;
metrics_util::LogContextOfShowAllSavedPasswordsShown(
show_all_saved_passwords_shown_context_);
}
if (base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksGeneration) &&
password_manager_util::GetPasswordSyncState(
autofill_client_->GetSyncService()) == SYNCING_NORMAL_ENCRYPTION) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_GENERATE_PASSWORD_FALLBACK,
autofill::POPUP_ITEM_ID_GENERATE_PASSWORD_ENTRY, &suggestions);
}
}
autofill_client_->ShowAutofillPopup(bounds,
text_direction,
suggestions,
weak_ptr_factory_.GetWeakPtr());
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <[email protected]>
Commit-Queue: NIKHIL SAHNI <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534923}
CWE ID: CWE-264 | void PasswordAutofillManager::OnShowPasswordSuggestions(
int key,
base::i18n::TextDirection text_direction,
const base::string16& typed_username,
int options,
const gfx::RectF& bounds) {
std::vector<autofill::Suggestion> suggestions;
LoginToPasswordInfoMap::const_iterator fill_data_it =
login_to_password_info_.find(key);
if (fill_data_it == login_to_password_info_.end()) {
NOTREACHED();
return;
}
GetSuggestions(fill_data_it->second, typed_username, &suggestions,
(options & autofill::SHOW_ALL) != 0,
(options & autofill::IS_PASSWORD_FIELD) != 0);
form_data_key_ = key;
if (suggestions.empty()) {
autofill_client_->HideAutofillPopup();
return;
}
if (options & autofill::IS_PASSWORD_FIELD) {
autofill::Suggestion password_field_suggestions(l10n_util::GetStringUTF16(
IDS_AUTOFILL_PASSWORD_FIELD_SUGGESTIONS_TITLE));
password_field_suggestions.frontend_id = autofill::POPUP_ITEM_ID_TITLE;
suggestions.insert(suggestions.begin(), password_field_suggestions);
}
GURL origin = (fill_data_it->second).origin;
bool is_context_secure = autofill_client_->IsContextSecure() &&
(!origin.is_valid() || !origin.SchemeIs("http"));
if (!is_context_secure && security_state::IsHttpWarningInFormEnabled()) {
std::string icon_str;
if (origin.is_valid() && origin.SchemeIs("http")) {
icon_str = "httpWarning";
} else {
icon_str = "httpsInvalid";
}
autofill::Suggestion http_warning_suggestion(
l10n_util::GetStringUTF8(IDS_AUTOFILL_LOGIN_HTTP_WARNING_MESSAGE),
l10n_util::GetStringUTF8(IDS_AUTOFILL_HTTP_WARNING_LEARN_MORE),
icon_str, autofill::POPUP_ITEM_ID_HTTP_NOT_SECURE_WARNING_MESSAGE);
#if !defined(OS_ANDROID)
suggestions.insert(suggestions.begin(), autofill::Suggestion());
suggestions.front().frontend_id = autofill::POPUP_ITEM_ID_SEPARATOR;
#endif
suggestions.insert(suggestions.begin(), http_warning_suggestion);
if (!did_show_form_not_secure_warning_) {
did_show_form_not_secure_warning_ = true;
metrics_util::LogShowedFormNotSecureWarningOnCurrentNavigation();
}
}
if (ShouldShowManualFallbackForPreLollipop(
autofill_client_->GetSyncService())) {
if (base::FeatureList::IsEnabled(
password_manager::features::kManualFallbacksFilling) &&
(options & autofill::IS_PASSWORD_FIELD) && password_client_ &&
password_client_->IsFillingFallbackEnabledForCurrentPage()) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_SHOW_ALL_SAVED_FALLBACK,
autofill::POPUP_ITEM_ID_ALL_SAVED_PASSWORDS_ENTRY, &suggestions);
show_all_saved_passwords_shown_context_ =
metrics_util::SHOW_ALL_SAVED_PASSWORDS_CONTEXT_PASSWORD;
metrics_util::LogContextOfShowAllSavedPasswordsShown(
show_all_saved_passwords_shown_context_);
}
if (base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksGeneration) &&
password_manager_util::GetPasswordSyncState(
autofill_client_->GetSyncService()) == SYNCING_NORMAL_ENCRYPTION) {
AddSimpleSuggestionWithSeparatorOnTop(
IDS_AUTOFILL_GENERATE_PASSWORD_FALLBACK,
autofill::POPUP_ITEM_ID_GENERATE_PASSWORD_ENTRY, &suggestions);
}
}
autofill_client_->ShowAutofillPopup(bounds,
text_direction,
suggestions,
weak_ptr_factory_.GetWeakPtr());
}
| 171,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void usage_exit() {
fprintf(stderr, "Usage: %s <width> <height> <infile> <outfile> <frame>\n",
exec_name);
exit(EXIT_FAILURE);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void usage_exit() {
void usage_exit(void) {
fprintf(stderr, "Usage: %s <width> <height> <infile> <outfile> <frame>\n",
exec_name);
exit(EXIT_FAILURE);
}
| 174,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: crm_send_remote_msg(void *session, xmlNode * msg, gboolean encrypted)
{
if (encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
cib_send_tls(session, msg);
#else
CRM_ASSERT(encrypted == FALSE);
#endif
} else {
cib_send_plaintext(GPOINTER_TO_INT(session), msg);
}
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | crm_send_remote_msg(void *session, xmlNode * msg, gboolean encrypted)
static int
crm_send_remote_msg_raw(void *session, const char *buf, size_t len, gboolean encrypted)
{
int rc = -1;
if (encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
rc = crm_send_tls(session, buf, len);
#else
CRM_ASSERT(encrypted == FALSE);
#endif
} else {
rc = crm_send_plaintext(GPOINTER_TO_INT(session), buf, len);
}
return rc;
}
| 166,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DCTStream::reset() {
int row_stride;
str->reset();
if (row_buffer)
{
jpeg_destroy_decompress(&cinfo);
init();
}
bool startFound = false;
int c = 0, c2 = 0;
while (!startFound)
{
if (!c)
if (c == -1)
{
error(-1, "Could not find start of jpeg data");
src.abort = true;
return;
}
if (c != 0xFF) c = 0;
return;
}
if (c != 0xFF) c = 0;
}
Commit Message:
CWE ID: CWE-20 | void DCTStream::reset() {
int row_stride;
str->reset();
if (row_buffer)
{
jpeg_destroy_decompress(&cinfo);
init();
}
bool startFound = false;
int c = 0, c2 = 0;
while (!startFound)
{
if (!c)
if (c == -1)
{
error(-1, "Could not find start of jpeg data");
return;
}
if (c != 0xFF) c = 0;
return;
}
if (c != 0xFF) c = 0;
}
| 165,394 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */
{
char *buf;
size_t line_len = 0;
long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0;
spl_filesystem_file_free_line(intern TSRMLS_CC);
if (php_stream_eof(intern->u.file.stream)) {
if (!silent) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name);
}
return FAILURE;
}
if (intern->u.file.max_line_len > 0) {
buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0);
if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) {
efree(buf);
buf = NULL;
} else {
buf[line_len] = '\0';
}
} else {
buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len);
}
if (!buf) {
intern->u.file.current_line = estrdup("");
intern->u.file.current_line_len = 0;
} else {
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) {
line_len = strcspn(buf, "\r\n");
buf[line_len] = '\0';
}
intern->u.file.current_line = buf;
intern->u.file.current_line_len = line_len;
}
intern->u.file.current_line_num += line_add;
return SUCCESS;
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */
{
char *buf;
size_t line_len = 0;
long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0;
spl_filesystem_file_free_line(intern TSRMLS_CC);
if (php_stream_eof(intern->u.file.stream)) {
if (!silent) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name);
}
return FAILURE;
}
if (intern->u.file.max_line_len > 0) {
buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0);
if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) {
efree(buf);
buf = NULL;
} else {
buf[line_len] = '\0';
}
} else {
buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len);
}
if (!buf) {
intern->u.file.current_line = estrdup("");
intern->u.file.current_line_len = 0;
} else {
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) {
line_len = strcspn(buf, "\r\n");
buf[line_len] = '\0';
}
intern->u.file.current_line = buf;
intern->u.file.current_line_len = line_len;
}
intern->u.file.current_line_num += line_add;
return SUCCESS;
} /* }}} */
| 167,076 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ps_parser_skip_PS_token( PS_Parser parser )
{
/* Note: PostScript allows any non-delimiting, non-whitespace */
/* character in a name (PS Ref Manual, 3rd ed, p31). */
/* PostScript delimiters are (, ), <, >, [, ], {, }, /, and %. */
FT_Byte* cur = parser->cursor;
FT_Byte* limit = parser->limit;
FT_Error error = FT_Err_Ok;
skip_spaces( &cur, limit ); /* this also skips comments */
if ( cur >= limit )
goto Exit;
/* self-delimiting, single-character tokens */
if ( *cur == '[' || *cur == ']' )
{
cur++;
goto Exit;
}
/* skip balanced expressions (procedures and strings) */
if ( *cur == '{' ) /* {...} */
{
error = skip_procedure( &cur, limit );
goto Exit;
}
if ( *cur == '(' ) /* (...) */
{
error = skip_literal_string( &cur, limit );
goto Exit;
}
if ( *cur == '<' ) /* <...> */
{
if ( cur + 1 < limit && *(cur + 1) == '<' ) /* << */
{
cur++;
cur++;
}
else
error = skip_string( &cur, limit );
goto Exit;
}
if ( *cur == '>' )
{
cur++;
if ( cur >= limit || *cur != '>' ) /* >> */
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" unexpected closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
goto Exit;
}
if ( *cur == '/' )
cur++;
/* anything else */
while ( cur < limit )
{
/* *cur might be invalid (e.g., ')' or '}'), but this */
/* is handled by the test `cur == parser->cursor' below */
if ( IS_PS_DELIM( *cur ) )
break;
cur++;
}
Exit:
if ( cur < limit && cur == parser->cursor )
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" current token is `%c' which is self-delimiting\n"
" "
" but invalid at this point\n",
*cur ));
error = FT_THROW( Invalid_File_Format );
}
parser->error = error;
parser->cursor = cur;
}
Commit Message:
CWE ID: CWE-125 | ps_parser_skip_PS_token( PS_Parser parser )
{
/* Note: PostScript allows any non-delimiting, non-whitespace */
/* character in a name (PS Ref Manual, 3rd ed, p31). */
/* PostScript delimiters are (, ), <, >, [, ], {, }, /, and %. */
FT_Byte* cur = parser->cursor;
FT_Byte* limit = parser->limit;
FT_Error error = FT_Err_Ok;
skip_spaces( &cur, limit ); /* this also skips comments */
if ( cur >= limit )
goto Exit;
/* self-delimiting, single-character tokens */
if ( *cur == '[' || *cur == ']' )
{
cur++;
goto Exit;
}
/* skip balanced expressions (procedures and strings) */
if ( *cur == '{' ) /* {...} */
{
error = skip_procedure( &cur, limit );
goto Exit;
}
if ( *cur == '(' ) /* (...) */
{
error = skip_literal_string( &cur, limit );
goto Exit;
}
if ( *cur == '<' ) /* <...> */
{
if ( cur + 1 < limit && *(cur + 1) == '<' ) /* << */
{
cur++;
cur++;
}
else
error = skip_string( &cur, limit );
goto Exit;
}
if ( *cur == '>' )
{
cur++;
if ( cur >= limit || *cur != '>' ) /* >> */
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" unexpected closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
goto Exit;
}
if ( *cur == '/' )
cur++;
/* anything else */
while ( cur < limit )
{
/* *cur might be invalid (e.g., ')' or '}'), but this */
/* is handled by the test `cur == parser->cursor' below */
if ( IS_PS_DELIM( *cur ) )
break;
cur++;
}
Exit:
if ( cur < limit && cur == parser->cursor )
{
FT_ERROR(( "ps_parser_skip_PS_token:"
" current token is `%c' which is self-delimiting\n"
" "
" but invalid at this point\n",
*cur ));
error = FT_THROW( Invalid_File_Format );
}
if ( cur > limit )
cur = limit;
parser->error = error;
parser->cursor = cur;
}
| 165,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ScreenOrientationDispatcherHost::OnUnlockRequest(
RenderFrameHost* render_frame_host) {
if (current_lock_) {
NotifyLockError(current_lock_->request_id,
blink::WebLockOrientationErrorCanceled);
}
if (!provider_.get())
return;
provider_->UnlockOrientation();
}
Commit Message: Cleanups in ScreenOrientationDispatcherHost.
BUG=None
Review URL: https://codereview.chromium.org/408213003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void ScreenOrientationDispatcherHost::OnUnlockRequest(
RenderFrameHost* render_frame_host) {
if (current_lock_) {
NotifyLockError(current_lock_->request_id,
blink::WebLockOrientationErrorCanceled);
}
if (!provider_)
return;
provider_->UnlockOrientation();
}
| 171,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
BUG_ON(new->thread_keyring);
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings
This fixes CVE-2017-7472.
Running the following program as an unprivileged user exhausts kernel
memory by leaking thread keyrings:
#include <keyutils.h>
int main()
{
for (;;)
keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING);
}
Fix it by only creating a new thread keyring if there wasn't one before.
To make things more consistent, make install_thread_keyring_to_cred()
and install_process_keyring_to_cred() both return 0 if the corresponding
keyring is already present.
Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials")
Cc: [email protected] # 2.6.29+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-404 | static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
| 168,276 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
if (inet->hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions *opt_to_free = NULL;
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt) {
opt = txopt_get(np);
opt_to_free = opt;
}
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
if (inet->hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
txopt_put(opt_to_free);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
| 167,338 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Huff_transmit (huff_t *huff, int ch, byte *fout) {
int i;
if (huff->loc[ch] == NULL) {
/* node_t hasn't been transmitted, send a NYT, then the symbol */
Huff_transmit(huff, NYT, fout);
for (i = 7; i >= 0; i--) {
add_bit((char)((ch >> i) & 0x1), fout);
}
} else {
send(huff->loc[ch], NULL, fout);
}
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
CWE ID: CWE-119 | void Huff_transmit (huff_t *huff, int ch, byte *fout) {
void Huff_transmit (huff_t *huff, int ch, byte *fout, int maxoffset) {
int i;
if (huff->loc[ch] == NULL) {
/* node_t hasn't been transmitted, send a NYT, then the symbol */
Huff_transmit(huff, NYT, fout, maxoffset);
for (i = 7; i >= 0; i--) {
add_bit((char)((ch >> i) & 0x1), fout);
}
} else {
send(huff->loc[ch], NULL, fout, maxoffset);
}
}
| 167,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gfx::SwapResult GLSurfaceEGLSurfaceControl::CommitOverlayPlanes(
PresentationCallback callback) {
NOTREACHED();
return gfx::SwapResult::SWAP_FAILED;
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | gfx::SwapResult GLSurfaceEGLSurfaceControl::CommitOverlayPlanes(
gfx::SwapResult GLSurfaceEGLSurfaceControl::PostSubBuffer(
int x,
int y,
int width,
int height,
PresentationCallback callback) {
NOTREACHED();
return gfx::SwapResult::SWAP_FAILED;
}
| 172,106 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_client_hello(SSL *s)
{
int i, n;
unsigned long len;
unsigned char *p;
STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */
STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */
STACK_OF(SSL_CIPHER) *prio, *allow;
int z;
/*
* This is a bit of a hack to check for the correct packet type the first
* time round.
*/
if (s->state == SSL2_ST_GET_CLIENT_HELLO_A) {
s->first_packet = 1;
s->state = SSL2_ST_GET_CLIENT_HELLO_B;
}
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_HELLO_B) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 9 - s->init_num);
if (i < (9 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
s->init_num = 9;
if (*(p++) != SSL2_MT_CLIENT_HELLO) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_PEER_ERROR);
return (-1);
}
n2s(p, i);
if (i < s->version)
s->version = i;
n2s(p, i);
s->s2->tmp.cipher_spec_length = i;
n2s(p, i);
s->s2->tmp.session_id_length = i;
if ((i < 0) || (i > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
return -1;
}
n2s(p, i);
s->s2->challenge_length = i;
if ((i < SSL2_MIN_CHALLENGE_LENGTH) ||
(i > SSL2_MAX_CHALLENGE_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_INVALID_CHALLENGE_LENGTH);
return (-1);
}
s->state = SSL2_ST_GET_CLIENT_HELLO_C;
}
/* SSL2_ST_GET_CLIENT_HELLO_C */
p = (unsigned char *)s->init_buf->data;
len =
9 + (unsigned long)s->s2->tmp.cipher_spec_length +
(unsigned long)s->s2->challenge_length +
(unsigned long)s->s2->tmp.session_id_length;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
if (s->msg_callback) {
/* CLIENT-HELLO */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 9;
/*
* get session-id before cipher stuff so we can get out session structure
* if it is cached
*/
/* session-id */
if ((s->s2->tmp.session_id_length != 0) &&
(s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_BAD_SSL_SESSION_ID_LENGTH);
return (-1);
}
if (s->s2->tmp.session_id_length == 0) {
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
} else {
i = ssl_get_prev_session(s, &(p[s->s2->tmp.cipher_spec_length]),
s->s2->tmp.session_id_length, NULL);
if (i == 1) { /* previous session */
s->hit = 1;
} else if (i == -1) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
} else {
if (s->cert == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CERTIFICATE);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CERTIFICATE_SET);
return (-1);
}
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
}
if (!s->hit) {
cs = ssl_bytes_to_cipher_list(s, p, s->s2->tmp.cipher_spec_length,
&s->session->ciphers);
if (cs == NULL)
goto mem_err;
cl = SSL_get_ciphers(s);
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
prio = sk_SSL_CIPHER_dup(cl);
if (prio == NULL)
goto mem_err;
allow = cs;
} else {
prio = cs;
allow = cl;
}
for (z = 0; z < sk_SSL_CIPHER_num(prio); z++) {
if (sk_SSL_CIPHER_find(allow, sk_SSL_CIPHER_value(prio, z)) < 0) {
(void)sk_SSL_CIPHER_delete(prio, z);
z--;
}
}
/*
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = prio;
}
/*
* s->session->ciphers should now have a list of ciphers that are on
* both the client and server. This list is ordered by the order the
if (s->s2->challenge_length > sizeof s->s2->challenge) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(s->s2->challenge, p, (unsigned int)s->s2->challenge_length);
return (1);
mem_err:
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_MALLOC_FAILURE);
return (0);
}
Commit Message:
CWE ID: CWE-310 | static int get_client_hello(SSL *s)
{
int i, n;
unsigned long len;
unsigned char *p;
STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */
STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */
STACK_OF(SSL_CIPHER) *prio, *allow;
int z;
/*
* This is a bit of a hack to check for the correct packet type the first
* time round.
*/
if (s->state == SSL2_ST_GET_CLIENT_HELLO_A) {
s->first_packet = 1;
s->state = SSL2_ST_GET_CLIENT_HELLO_B;
}
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_HELLO_B) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 9 - s->init_num);
if (i < (9 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
s->init_num = 9;
if (*(p++) != SSL2_MT_CLIENT_HELLO) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_PEER_ERROR);
return (-1);
}
n2s(p, i);
if (i < s->version)
s->version = i;
n2s(p, i);
s->s2->tmp.cipher_spec_length = i;
n2s(p, i);
s->s2->tmp.session_id_length = i;
if ((i < 0) || (i > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
return -1;
}
n2s(p, i);
s->s2->challenge_length = i;
if ((i < SSL2_MIN_CHALLENGE_LENGTH) ||
(i > SSL2_MAX_CHALLENGE_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_INVALID_CHALLENGE_LENGTH);
return (-1);
}
s->state = SSL2_ST_GET_CLIENT_HELLO_C;
}
/* SSL2_ST_GET_CLIENT_HELLO_C */
p = (unsigned char *)s->init_buf->data;
len =
9 + (unsigned long)s->s2->tmp.cipher_spec_length +
(unsigned long)s->s2->challenge_length +
(unsigned long)s->s2->tmp.session_id_length;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
if (s->msg_callback) {
/* CLIENT-HELLO */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 9;
/*
* get session-id before cipher stuff so we can get out session structure
* if it is cached
*/
/* session-id */
if ((s->s2->tmp.session_id_length != 0) &&
(s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_BAD_SSL_SESSION_ID_LENGTH);
return (-1);
}
if (s->s2->tmp.session_id_length == 0) {
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
} else {
i = ssl_get_prev_session(s, &(p[s->s2->tmp.cipher_spec_length]),
s->s2->tmp.session_id_length, NULL);
if (i == 1) { /* previous session */
s->hit = 1;
} else if (i == -1) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
} else {
if (s->cert == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CERTIFICATE);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CERTIFICATE_SET);
return (-1);
}
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
}
if (!s->hit) {
cs = ssl_bytes_to_cipher_list(s, p, s->s2->tmp.cipher_spec_length,
&s->session->ciphers);
if (cs == NULL)
goto mem_err;
cl = SSL_get_ciphers(s);
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
prio = sk_SSL_CIPHER_dup(cl);
if (prio == NULL)
goto mem_err;
allow = cs;
} else {
prio = cs;
allow = cl;
}
/* Generate list of SSLv2 ciphers shared between client and server */
for (z = 0; z < sk_SSL_CIPHER_num(prio); z++) {
const SSL_CIPHER *cp = sk_SSL_CIPHER_value(prio, z);
if ((cp->algorithm_ssl & SSL_SSLV2) == 0 ||
sk_SSL_CIPHER_find(allow, cp) < 0) {
(void)sk_SSL_CIPHER_delete(prio, z);
z--;
}
}
/*
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = prio;
}
/* Make sure we have at least one cipher in common */
if (sk_SSL_CIPHER_num(s->session->ciphers) == 0) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CIPHER_MATCH);
return -1;
}
/*
* s->session->ciphers should now have a list of ciphers that are on
* both the client and server. This list is ordered by the order the
if (s->s2->challenge_length > sizeof s->s2->challenge) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(s->s2->challenge, p, (unsigned int)s->s2->challenge_length);
return (1);
mem_err:
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_MALLOC_FAILURE);
return (0);
}
| 165,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
| 165,294 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *curl_easy_escape(CURL *handle, const char *string, int inlength)
{
size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;
char *ns;
char *testing_ptr = NULL;
unsigned char in; /* we need to treat the characters unsigned */
size_t newlen = alloc;
int strindex=0;
size_t length;
CURLcode res;
ns = malloc(alloc);
if(!ns)
return NULL;
length = alloc-1;
while(length--) {
in = *string;
if(Curl_isunreserved(in))
/* just copy this */
ns[strindex++]=in;
else {
/* encode it */
newlen += 2; /* the size grows with two, since this'll become a %XX */
if(newlen > alloc) {
alloc *= 2;
testing_ptr = realloc(ns, alloc);
if(!testing_ptr) {
free( ns );
return NULL;
}
else {
ns = testing_ptr;
}
}
res = Curl_convert_to_network(handle, &in, 1);
if(res) {
/* Curl_convert_to_network calls failf if unsuccessful */
free(ns);
return NULL;
}
snprintf(&ns[strindex], 4, "%%%02X", in);
strindex+=3;
}
string++;
}
ns[strindex]=0; /* terminate it */
return ns;
}
Commit Message: URL sanitize: reject URLs containing bad data
Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a
decoded manner now use the new Curl_urldecode() function to reject URLs
with embedded control codes (anything that is or decodes to a byte value
less than 32).
URLs containing such codes could easily otherwise be used to do harm and
allow users to do unintended actions with otherwise innocent tools and
applications. Like for example using a URL like
pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get
a mail and instead this would delete one.
This flaw is considered a security vulnerability: CVE-2012-0036
Security advisory at: http://curl.haxx.se/docs/adv_20120124.html
Reported by: Dan Fandrich
CWE ID: CWE-89 | char *curl_easy_escape(CURL *handle, const char *string, int inlength)
{
size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;
char *ns;
char *testing_ptr = NULL;
unsigned char in; /* we need to treat the characters unsigned */
size_t newlen = alloc;
size_t strindex=0;
size_t length;
CURLcode res;
ns = malloc(alloc);
if(!ns)
return NULL;
length = alloc-1;
while(length--) {
in = *string;
if(Curl_isunreserved(in))
/* just copy this */
ns[strindex++]=in;
else {
/* encode it */
newlen += 2; /* the size grows with two, since this'll become a %XX */
if(newlen > alloc) {
alloc *= 2;
testing_ptr = realloc(ns, alloc);
if(!testing_ptr) {
free( ns );
return NULL;
}
else {
ns = testing_ptr;
}
}
res = Curl_convert_to_network(handle, &in, 1);
if(res) {
/* Curl_convert_to_network calls failf if unsuccessful */
free(ns);
return NULL;
}
snprintf(&ns[strindex], 4, "%%%02X", in);
strindex+=3;
}
string++;
}
ns[strindex]=0; /* terminate it */
return ns;
}
| 165,664 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void *hashtable_iter_at(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return &pair->list;
}
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 | void *hashtable_iter_at(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash & hashmask(hashtable->order)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return &pair->list;
}
| 166,532 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_one(struct crypto_alg *alg,
struct crypto_user_alg *ualg, struct sk_buff *skb)
{
strlcpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name));
strlcpy(ualg->cru_driver_name, alg->cra_driver_name,
sizeof(ualg->cru_driver_name));
strlcpy(ualg->cru_module_name, module_name(alg->cra_module),
sizeof(ualg->cru_module_name));
ualg->cru_type = 0;
ualg->cru_mask = 0;
ualg->cru_flags = alg->cra_flags;
ualg->cru_refcnt = refcount_read(&alg->cra_refcnt);
if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))
goto nla_put_failure;
if (alg->cra_flags & CRYPTO_ALG_LARVAL) {
struct crypto_report_larval rl;
strlcpy(rl.type, "larval", sizeof(rl.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,
sizeof(struct crypto_report_larval), &rl))
goto nla_put_failure;
goto out;
}
if (alg->cra_type && alg->cra_type->report) {
if (alg->cra_type->report(skb, alg))
goto nla_put_failure;
goto out;
}
switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {
case CRYPTO_ALG_TYPE_CIPHER:
if (crypto_report_cipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_COMPRESS:
if (crypto_report_comp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_ACOMPRESS:
if (crypto_report_acomp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_AKCIPHER:
if (crypto_report_akcipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_KPP:
if (crypto_report_kpp(skb, alg))
goto nla_put_failure;
break;
}
out:
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_one(struct crypto_alg *alg,
struct crypto_user_alg *ualg, struct sk_buff *skb)
{
strncpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name));
strncpy(ualg->cru_driver_name, alg->cra_driver_name,
sizeof(ualg->cru_driver_name));
strncpy(ualg->cru_module_name, module_name(alg->cra_module),
sizeof(ualg->cru_module_name));
ualg->cru_type = 0;
ualg->cru_mask = 0;
ualg->cru_flags = alg->cra_flags;
ualg->cru_refcnt = refcount_read(&alg->cra_refcnt);
if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))
goto nla_put_failure;
if (alg->cra_flags & CRYPTO_ALG_LARVAL) {
struct crypto_report_larval rl;
strncpy(rl.type, "larval", sizeof(rl.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,
sizeof(struct crypto_report_larval), &rl))
goto nla_put_failure;
goto out;
}
if (alg->cra_type && alg->cra_type->report) {
if (alg->cra_type->report(skb, alg))
goto nla_put_failure;
goto out;
}
switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {
case CRYPTO_ALG_TYPE_CIPHER:
if (crypto_report_cipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_COMPRESS:
if (crypto_report_comp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_ACOMPRESS:
if (crypto_report_acomp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_AKCIPHER:
if (crypto_report_akcipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_KPP:
if (crypto_report_kpp(skb, alg))
goto nla_put_failure;
break;
}
out:
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,968 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct n_tty_data *ldata = tty->disc_data;
if (!old || (old->c_lflag ^ tty->termios.c_lflag) & ICANON) {
bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
ldata->line_start = ldata->read_tail;
if (!L_ICANON(tty) || !read_cnt(ldata)) {
ldata->canon_head = ldata->read_tail;
ldata->push = 0;
} else {
set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
ldata->read_flags);
ldata->canon_head = ldata->read_head;
ldata->push = 1;
}
ldata->commit_head = ldata->read_head;
ldata->erasing = 0;
ldata->lnext = 0;
}
ldata->icanon = (L_ICANON(tty) != 0);
if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
I_PARMRK(tty)) {
bitmap_zero(ldata->char_map, 256);
if (I_IGNCR(tty) || I_ICRNL(tty))
set_bit('\r', ldata->char_map);
if (I_INLCR(tty))
set_bit('\n', ldata->char_map);
if (L_ICANON(tty)) {
set_bit(ERASE_CHAR(tty), ldata->char_map);
set_bit(KILL_CHAR(tty), ldata->char_map);
set_bit(EOF_CHAR(tty), ldata->char_map);
set_bit('\n', ldata->char_map);
set_bit(EOL_CHAR(tty), ldata->char_map);
if (L_IEXTEN(tty)) {
set_bit(WERASE_CHAR(tty), ldata->char_map);
set_bit(LNEXT_CHAR(tty), ldata->char_map);
set_bit(EOL2_CHAR(tty), ldata->char_map);
if (L_ECHO(tty))
set_bit(REPRINT_CHAR(tty),
ldata->char_map);
}
}
if (I_IXON(tty)) {
set_bit(START_CHAR(tty), ldata->char_map);
set_bit(STOP_CHAR(tty), ldata->char_map);
}
if (L_ISIG(tty)) {
set_bit(INTR_CHAR(tty), ldata->char_map);
set_bit(QUIT_CHAR(tty), ldata->char_map);
set_bit(SUSP_CHAR(tty), ldata->char_map);
}
clear_bit(__DISABLED_CHAR, ldata->char_map);
ldata->raw = 0;
ldata->real_raw = 0;
} else {
ldata->raw = 1;
if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
(I_IGNPAR(tty) || !I_INPCK(tty)) &&
(tty->driver->flags & TTY_DRIVER_REAL_RAW))
ldata->real_raw = 1;
else
ldata->real_raw = 0;
}
/*
* Fix tty hang when I_IXON(tty) is cleared, but the tty
* been stopped by STOP_CHAR(tty) before it.
*/
if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
start_tty(tty);
process_echoes(tty);
}
/* The termios change make the tty ready for I/O */
wake_up_interruptible(&tty->write_wait);
wake_up_interruptible(&tty->read_wait);
}
Commit Message: n_tty: fix EXTPROC vs ICANON interaction with TIOCINQ (aka FIONREAD)
We added support for EXTPROC back in 2010 in commit 26df6d13406d ("tty:
Add EXTPROC support for LINEMODE") and the intent was to allow it to
override some (all?) ICANON behavior. Quoting from that original commit
message:
There is a new bit in the termios local flag word, EXTPROC.
When this bit is set, several aspects of the terminal driver
are disabled. Input line editing, character echo, and mapping
of signals are all disabled. This allows the telnetd to turn
off these functions when in linemode, but still keep track of
what state the user wants the terminal to be in.
but the problem turns out that "several aspects of the terminal driver
are disabled" is a bit ambiguous, and you can really confuse the n_tty
layer by setting EXTPROC and then causing some of the ICANON invariants
to no longer be maintained.
This fixes at least one such case (TIOCINQ) becoming unhappy because of
the confusion over whether ICANON really means ICANON when EXTPROC is set.
This basically makes TIOCINQ match the case of read: if EXTPROC is set,
we ignore ICANON. Also, make sure to reset the ICANON state ie EXTPROC
changes, not just if ICANON changes.
Fixes: 26df6d13406d ("tty: Add EXTPROC support for LINEMODE")
Reported-by: Tetsuo Handa <[email protected]>
Reported-by: syzkaller <[email protected]>
Cc: Jiri Slaby <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-704 | static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct n_tty_data *ldata = tty->disc_data;
if (!old || (old->c_lflag ^ tty->termios.c_lflag) & (ICANON | EXTPROC)) {
bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
ldata->line_start = ldata->read_tail;
if (!L_ICANON(tty) || !read_cnt(ldata)) {
ldata->canon_head = ldata->read_tail;
ldata->push = 0;
} else {
set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
ldata->read_flags);
ldata->canon_head = ldata->read_head;
ldata->push = 1;
}
ldata->commit_head = ldata->read_head;
ldata->erasing = 0;
ldata->lnext = 0;
}
ldata->icanon = (L_ICANON(tty) != 0);
if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
I_PARMRK(tty)) {
bitmap_zero(ldata->char_map, 256);
if (I_IGNCR(tty) || I_ICRNL(tty))
set_bit('\r', ldata->char_map);
if (I_INLCR(tty))
set_bit('\n', ldata->char_map);
if (L_ICANON(tty)) {
set_bit(ERASE_CHAR(tty), ldata->char_map);
set_bit(KILL_CHAR(tty), ldata->char_map);
set_bit(EOF_CHAR(tty), ldata->char_map);
set_bit('\n', ldata->char_map);
set_bit(EOL_CHAR(tty), ldata->char_map);
if (L_IEXTEN(tty)) {
set_bit(WERASE_CHAR(tty), ldata->char_map);
set_bit(LNEXT_CHAR(tty), ldata->char_map);
set_bit(EOL2_CHAR(tty), ldata->char_map);
if (L_ECHO(tty))
set_bit(REPRINT_CHAR(tty),
ldata->char_map);
}
}
if (I_IXON(tty)) {
set_bit(START_CHAR(tty), ldata->char_map);
set_bit(STOP_CHAR(tty), ldata->char_map);
}
if (L_ISIG(tty)) {
set_bit(INTR_CHAR(tty), ldata->char_map);
set_bit(QUIT_CHAR(tty), ldata->char_map);
set_bit(SUSP_CHAR(tty), ldata->char_map);
}
clear_bit(__DISABLED_CHAR, ldata->char_map);
ldata->raw = 0;
ldata->real_raw = 0;
} else {
ldata->raw = 1;
if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
(I_IGNPAR(tty) || !I_INPCK(tty)) &&
(tty->driver->flags & TTY_DRIVER_REAL_RAW))
ldata->real_raw = 1;
else
ldata->real_raw = 0;
}
/*
* Fix tty hang when I_IXON(tty) is cleared, but the tty
* been stopped by STOP_CHAR(tty) before it.
*/
if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
start_tty(tty);
process_echoes(tty);
}
/* The termios change make the tty ready for I/O */
wake_up_interruptible(&tty->write_wait);
wake_up_interruptible(&tty->read_wait);
}
| 169,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
{
u32 data;
void *vapic;
if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
vapic = kmap_atomic(vcpu->arch.apic->vapic_page);
data = *(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr));
kunmap_atomic(vapic);
apic_set_tpr(vcpu->arch.apic, data & 0xff);
}
Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
{
u32 data;
if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
sizeof(u32));
apic_set_tpr(vcpu->arch.apic, data & 0xff);
}
| 165,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_init (MyObject *obj)
{
obj->val = 0;
}
Commit Message:
CWE ID: CWE-264 | my_object_init (MyObject *obj)
| 165,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
header->nFilledLen = 0;
header->nOffset = 0;
header->nFlags = 0;
status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput);
if (res != OK) {
CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd));
return res;
}
{
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.add(header);
CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd)));
}
OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header);
if (err != OMX_ErrorNone) {
CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd));
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.remove(header);
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexOutput);
if (header == NULL) {
return BAD_VALUE;
}
header->nFilledLen = 0;
header->nOffset = 0;
header->nFlags = 0;
status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput);
if (res != OK) {
CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd));
return res;
}
{
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.add(header);
CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd)));
}
OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header);
if (err != OMX_ErrorNone) {
CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd));
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.remove(header);
}
return StatusFromOMXError(err);
}
| 173,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void _xml_characterDataHandler(void *userData, const XML_Char *s, int len)
{
xml_parser *parser = (xml_parser *)userData;
if (parser) {
zval *retval, *args[2];
if (parser->characterDataHandler) {
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) {
zval_ptr_dtor(&retval);
}
}
if (parser->data) {
int i;
int doprint = 0;
char *decoded_value;
int decoded_len;
decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding);
for (i = 0; i < decoded_len; i++) {
switch (decoded_value[i]) {
case ' ':
case '\t':
case '\n':
continue;
default:
doprint = 1;
break;
}
if (doprint) {
break;
}
}
if (doprint || (! parser->skipwhite)) {
if (parser->lastwasopen) {
zval **myval;
/* check if the current tag already has a value - if yes append to that! */
if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
} else {
add_assoc_string(*(parser->ctag),"value",decoded_value,0);
}
} else {
zval *tag;
zval **curtag, **mytype, **myval;
HashPosition hpos=NULL;
zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos);
if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) {
if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
return;
}
}
}
}
if (parser->level <= XML_MAXLEVEL) {
MAKE_STD_ZVAL(tag);
array_init(tag);
_xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset);
add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1);
add_assoc_string(tag,"value",decoded_value,0);
add_assoc_string(tag,"type","cdata",1);
add_assoc_long(tag,"level",parser->level);
zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);
} else if (parser->level == (XML_MAXLEVEL + 1)) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated");
}
}
} else {
efree(decoded_value);
}
}
}
}
Commit Message:
CWE ID: CWE-119 | void _xml_characterDataHandler(void *userData, const XML_Char *s, int len)
{
xml_parser *parser = (xml_parser *)userData;
if (parser) {
zval *retval, *args[2];
if (parser->characterDataHandler) {
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) {
zval_ptr_dtor(&retval);
}
}
if (parser->data) {
int i;
int doprint = 0;
char *decoded_value;
int decoded_len;
decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding);
for (i = 0; i < decoded_len; i++) {
switch (decoded_value[i]) {
case ' ':
case '\t':
case '\n':
continue;
default:
doprint = 1;
break;
}
if (doprint) {
break;
}
}
if (doprint || (! parser->skipwhite)) {
if (parser->lastwasopen) {
zval **myval;
/* check if the current tag already has a value - if yes append to that! */
if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
} else {
add_assoc_string(*(parser->ctag),"value",decoded_value,0);
}
} else {
zval *tag;
zval **curtag, **mytype, **myval;
HashPosition hpos=NULL;
zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos);
if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) {
if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
return;
}
}
}
}
if (parser->level <= XML_MAXLEVEL && parser->level > 0) {
MAKE_STD_ZVAL(tag);
array_init(tag);
_xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset);
add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1);
add_assoc_string(tag,"value",decoded_value,0);
add_assoc_string(tag,"type","cdata",1);
add_assoc_long(tag,"level",parser->level);
zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);
} else if (parser->level == (XML_MAXLEVEL + 1)) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated");
}
}
} else {
efree(decoded_value);
}
}
}
}
| 165,040 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Cluster::GetTimeCode() const
{
long long pos;
long len;
const long status = Load(pos, len);
if (status < 0) //error
return status;
return m_timecode;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Cluster::GetTimeCode() const
const long status = Load(pos, len);
if (status < 0) // error
return status;
return m_timecode;
}
long long Cluster::GetTime() const {
const long long tc = GetTimeCode();
if (tc < 0)
return tc;
const SegmentInfo* const pInfo = m_pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long t = m_timecode * scale;
return t;
}
long long Cluster::GetFirstTime() const {
const BlockEntry* pEntry;
const long status = GetFirst(pEntry);
if (status < 0) // error
return status;
if (pEntry == NULL) // empty cluster
return GetTime();
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
return pBlock->GetTime(this);
}
long long Cluster::GetLastTime() const {
const BlockEntry* pEntry;
const long status = GetLast(pEntry);
if (status < 0) // error
return status;
if (pEntry == NULL) // empty cluster
return GetTime();
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
return pBlock->GetTime(this);
}
long Cluster::CreateBlock(long long id,
long long pos, // absolute pos of payload
long long size, long long discard_padding) {
assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock
if (m_entries_count < 0) { // haven't parsed anything yet
assert(m_entries == NULL);
assert(m_entries_size == 0);
m_entries_size = 1024;
m_entries = new BlockEntry* [m_entries_size];
m_entries_count = 0;
} else {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (m_entries_count >= m_entries_size) {
const long entries_size = 2 * m_entries_size;
BlockEntry** const entries = new BlockEntry* [entries_size];
assert(entries);
BlockEntry** src = m_entries;
BlockEntry** const src_end = src + m_entries_count;
BlockEntry** dst = entries;
while (src != src_end)
*dst++ = *src++;
delete[] m_entries;
m_entries = entries;
m_entries_size = entries_size;
}
}
if (id == 0x20) // BlockGroup ID
return CreateBlockGroup(pos, size, discard_padding);
else // SimpleBlock ID
return CreateSimpleBlock(pos, size);
}
long Cluster::CreateBlockGroup(long long start_offset, long long size,
long long discard_padding) {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count >= 0);
assert(m_entries_count < m_entries_size);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = start_offset;
const long long stop = start_offset + size;
// For WebM files, there is a bias towards previous reference times
//(in order to support alt-ref frames, which refer back to the previous
// keyframe). Normally a 0 value is not possible, but here we tenatively
// allow 0 as the value of a reference frame, with the interpretation
// that this is a "previous" reference time.
long long prev = 1; // nonce
long long next = 0; // nonce
long long duration = -1; // really, this is unsigned
long long bpos = -1;
long long bsize = -1;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume size
if (id == 0x21) { // Block ID
if (bpos < 0) { // Block ID
bpos = pos;
bsize = size;
}
} else if (id == 0x1B) { // Duration ID
assert(size <= 8);
duration = UnserializeUInt(pReader, pos, size);
assert(duration >= 0); // TODO
} else if (id == 0x7B) { // ReferenceBlock
assert(size <= 8);
const long size_ = static_cast<long>(size);
long long time;
long status = UnserializeInt(pReader, pos, size_, time);
assert(status == 0);
if (status != 0)
return -1;
if (time <= 0) // see note above
prev = time;
else // weird
next = time;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
assert(bpos >= 0);
assert(bsize >= 0);
const long idx = m_entries_count;
BlockEntry** const ppEntry = m_entries + idx;
BlockEntry*& pEntry = *ppEntry;
pEntry = new (std::nothrow)
BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding);
if (pEntry == NULL)
return -1; // generic error
BlockGroup* const p = static_cast<BlockGroup*>(pEntry);
const long status = p->Parse();
if (status == 0) { // success
++m_entries_count;
return 0;
}
delete pEntry;
pEntry = 0;
return status;
}
long Cluster::CreateSimpleBlock(long long st, long long sz) {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count >= 0);
assert(m_entries_count < m_entries_size);
const long idx = m_entries_count;
BlockEntry** const ppEntry = m_entries + idx;
BlockEntry*& pEntry = *ppEntry;
pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz);
if (pEntry == NULL)
return -1; // generic error
SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry);
const long status = p->Parse();
if (status == 0) {
++m_entries_count;
return 0;
}
delete pEntry;
pEntry = 0;
return status;
}
long Cluster::GetFirst(const BlockEntry*& pFirst) const {
if (m_entries_count <= 0) {
long long pos;
long len;
const long status = Parse(pos, len);
| 174,365 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: run_cmd(int fd, ...)
{
pid_t pid;
sigset_t sigm, sigm_old;
/* block signals, let child establish its own handlers */
sigemptyset(&sigm);
sigaddset(&sigm, SIGTERM);
sigprocmask(SIG_BLOCK, &sigm, &sigm_old);
pid = fork();
if ( pid < 0 ) {
sigprocmask(SIG_SETMASK, &sigm_old, NULL);
fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno));
return -1;
} else if ( pid ) {
/* father: picocom */
int status, r;
/* reset the mask */
sigprocmask(SIG_SETMASK, &sigm_old, NULL);
/* wait for child to finish */
do {
r = waitpid(pid, &status, 0);
} while ( r < 0 && errno == EINTR );
/* reset terminal (back to raw mode) */
term_apply(STI);
/* check and report child return status */
if ( WIFEXITED(status) ) {
fd_printf(STO, "\r\n*** exit status: %d ***\r\n",
WEXITSTATUS(status));
return WEXITSTATUS(status);
} else if ( WIFSIGNALED(status) ) {
fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n",
WTERMSIG(status));
return -1;
} else {
fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r);
return -1;
}
} else {
/* child: external program */
long fl;
char cmd[512];
/* unmanage terminal, and reset it to canonical mode */
term_remove(STI);
/* unmanage serial port fd, without reset */
term_erase(fd);
/* set serial port fd to blocking mode */
fl = fcntl(fd, F_GETFL);
fl &= ~O_NONBLOCK;
fcntl(fd, F_SETFL, fl);
/* connect stdin and stdout to serial port */
close(STI);
close(STO);
dup2(fd, STI);
dup2(fd, STO);
{
/* build command-line */
char *c, *ce;
const char *s;
int n;
va_list vls;
strcpy(cmd, EXEC);
c = &cmd[sizeof(EXEC)- 1];
ce = cmd + sizeof(cmd) - 1;
va_start(vls, fd);
while ( (s = va_arg(vls, const char *)) ) {
n = strlen(s);
if ( c + n + 1 >= ce ) break;
memcpy(c, s, n); c += n;
*c++ = ' ';
}
va_end(vls);
*c = '\0';
}
/* run extenral command */
fd_printf(STDERR_FILENO, "%s\n", &cmd[sizeof(EXEC) - 1]);
establish_child_signal_handlers();
sigprocmask(SIG_SETMASK, &sigm_old, NULL);
execl("/bin/sh", "sh", "-c", cmd, NULL);
exit(42);
}
}
Commit Message: Do not use "/bin/sh" to run external commands.
Picocom no longer uses /bin/sh to run external commands for
file-transfer operations. Parsing the command line and spliting it into
arguments is now performed internally by picocom, using quoting rules
very similar to those of the Unix shell. Hopefully, this makes it
impossible to inject shell-commands when supplying filenames or
extra arguments to the send- and receive-file commands.
CWE ID: CWE-77 | run_cmd(int fd, ...)
run_cmd(int fd, const char *cmd, const char *args_extra)
{
pid_t pid;
sigset_t sigm, sigm_old;
/* block signals, let child establish its own handlers */
sigemptyset(&sigm);
sigaddset(&sigm, SIGTERM);
sigprocmask(SIG_BLOCK, &sigm, &sigm_old);
pid = fork();
if ( pid < 0 ) {
sigprocmask(SIG_SETMASK, &sigm_old, NULL);
fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno));
return -1;
} else if ( pid ) {
/* father: picocom */
int status, r;
/* reset the mask */
sigprocmask(SIG_SETMASK, &sigm_old, NULL);
/* wait for child to finish */
do {
r = waitpid(pid, &status, 0);
} while ( r < 0 && errno == EINTR );
/* reset terminal (back to raw mode) */
term_apply(STI);
/* check and report child return status */
if ( WIFEXITED(status) ) {
fd_printf(STO, "\r\n*** exit status: %d ***\r\n",
WEXITSTATUS(status));
return WEXITSTATUS(status);
} else if ( WIFSIGNALED(status) ) {
fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n",
WTERMSIG(status));
return -1;
} else {
fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r);
return -1;
}
} else {
/* child: external program */
long fl;
int argc;
char *argv[RUNCMD_ARGS_MAX + 1];
int r;
/* unmanage terminal, and reset it to canonical mode */
term_remove(STI);
/* unmanage serial port fd, without reset */
term_erase(fd);
/* set serial port fd to blocking mode */
fl = fcntl(fd, F_GETFL);
fl &= ~O_NONBLOCK;
fcntl(fd, F_SETFL, fl);
/* connect stdin and stdout to serial port */
close(STI);
close(STO);
dup2(fd, STI);
dup2(fd, STO);
/* build command arguments vector */
argc = 0;
r = split_quoted(cmd, &argc, argv, RUNCMD_ARGS_MAX);
if ( r < 0 ) {
fd_printf(STDERR_FILENO, "Cannot parse command\n");
exit(RUNCMD_EXEC_FAIL);
}
r = split_quoted(args_extra, &argc, argv, RUNCMD_ARGS_MAX);
if ( r < 0 ) {
fd_printf(STDERR_FILENO, "Cannot parse extra args\n");
exit(RUNCMD_EXEC_FAIL);
}
if ( argc < 1 ) {
fd_printf(STDERR_FILENO, "No command given\n");
exit(RUNCMD_EXEC_FAIL);
}
argv[argc] = NULL;
/* run extenral command */
fd_printf(STDERR_FILENO, "$ %s %s\n", cmd, args_extra);
establish_child_signal_handlers();
sigprocmask(SIG_SETMASK, &sigm_old, NULL);
execvp(argv[0], argv);
fd_printf(STDERR_FILENO, "exec: %s\n", strerror(errno));
exit(RUNCMD_EXEC_FAIL);
}
}
| 168,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromeOSSetImeConfig(InputMethodStatusConnection* connection,
const char* section,
const char* config_name,
const ImeConfigValue& value) {
DCHECK(section);
DCHECK(config_name);
g_return_val_if_fail(connection, FALSE);
return connection->SetImeConfig(section, config_name, value);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ChromeOSSetImeConfig(InputMethodStatusConnection* connection,
| 170,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret;
unsigned long __user *datap = (unsigned long __user *) data;
switch (request) {
case PTRACE_PEEKUSR:
ret = ptrace_read_user(child, addr, datap);
break;
case PTRACE_POKEUSR:
ret = ptrace_write_user(child, addr, data);
break;
case PTRACE_GETREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_SETREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_GETFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
case PTRACE_SETFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
#ifdef CONFIG_IWMMXT
case PTRACE_GETWMMXREGS:
ret = ptrace_getwmmxregs(child, datap);
break;
case PTRACE_SETWMMXREGS:
ret = ptrace_setwmmxregs(child, datap);
break;
#endif
case PTRACE_GET_THREAD_AREA:
ret = put_user(task_thread_info(child)->tp_value,
datap);
break;
case PTRACE_SET_SYSCALL:
task_thread_info(child)->syscall = data;
ret = 0;
break;
#ifdef CONFIG_CRUNCH
case PTRACE_GETCRUNCHREGS:
ret = ptrace_getcrunchregs(child, datap);
break;
case PTRACE_SETCRUNCHREGS:
ret = ptrace_setcrunchregs(child, datap);
break;
#endif
#ifdef CONFIG_VFP
case PTRACE_GETVFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
case PTRACE_SETVFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
case PTRACE_GETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_gethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
case PTRACE_SETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_sethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork
Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to
prevent it from being used as a covert channel between two tasks.
There are more and more applications coming to Windows RT,
Wine could support them, but mostly they expect to have
the thread environment block (TEB) in TPIDRURW.
This patch preserves that register per thread instead of clearing it.
Unlike the TPIDRURO, which is already switched, the TPIDRURW
can be updated from userspace so needs careful treatment in the case that we
modify TPIDRURW and call fork(). To avoid this we must always read
TPIDRURW in copy_thread.
Signed-off-by: André Hentschel <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Jonathan Austin <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-264 | long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret;
unsigned long __user *datap = (unsigned long __user *) data;
switch (request) {
case PTRACE_PEEKUSR:
ret = ptrace_read_user(child, addr, datap);
break;
case PTRACE_POKEUSR:
ret = ptrace_write_user(child, addr, data);
break;
case PTRACE_GETREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_SETREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_GETFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
case PTRACE_SETFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
#ifdef CONFIG_IWMMXT
case PTRACE_GETWMMXREGS:
ret = ptrace_getwmmxregs(child, datap);
break;
case PTRACE_SETWMMXREGS:
ret = ptrace_setwmmxregs(child, datap);
break;
#endif
case PTRACE_GET_THREAD_AREA:
ret = put_user(task_thread_info(child)->tp_value[0],
datap);
break;
case PTRACE_SET_SYSCALL:
task_thread_info(child)->syscall = data;
ret = 0;
break;
#ifdef CONFIG_CRUNCH
case PTRACE_GETCRUNCHREGS:
ret = ptrace_getcrunchregs(child, datap);
break;
case PTRACE_SETCRUNCHREGS:
ret = ptrace_setcrunchregs(child, datap);
break;
#endif
#ifdef CONFIG_VFP
case PTRACE_GETVFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
case PTRACE_SETVFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
case PTRACE_GETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_gethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
case PTRACE_SETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_sethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
| 167,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
int *len, int *strid, int read_packet) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE, startpos;
int ret;
recover:
startpos = avio_tell(pb);
syncword = avio_rb16(pb);
streamid = avio_r8(pb);
avio_r8(pb); /* counter not used */
reserved = avio_r8(pb);
flags = avio_r8(pb);
length = avio_rb16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = avio_rb32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
/* PVA Audio Packets either start with a signaled PES packet or
* are a continuation of the previous PES packet. New PES packets
* always start at the beginning of a PVA Packet, never somewhere in
* the middle. */
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = avio_rb24(pb);
avio_r8(pb);
pes_packet_length = avio_rb16(pb);
pes_flags = avio_rb16(pb);
pes_header_data_length = avio_r8(pb);
if (pes_signal != 1 || pes_header_data_length == 0) {
pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "
"trying to recover\n");
avio_skip(pb, length - 9);
if (!read_packet)
return AVERROR(EIO);
goto recover;
}
ret = avio_read(pb, pes_header_data, pes_header_data_length);
if (ret != pes_header_data_length)
return ret < 0 ? ret : AVERROR_INVALIDDATA;
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {
if (pes_header_data_length < 5) {
pva_log(s, AV_LOG_ERROR, "header too short\n");
avio_skip(pb, length);
return AVERROR_INVALIDDATA;
}
pva_pts = ff_parse_pes_pts(pes_header_data);
}
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if (pva_pts != AV_NOPTS_VALUE)
av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
*pts = pva_pts;
*len = length;
*strid = streamid;
return 0;
}
Commit Message: avformat/pva: Check for EOF before retrying in read_part_of_packet()
Fixes: Infinite loop
Fixes: pva-4b1835dbc2027bf3c567005dcc78e85199240d06
Found-by: Paul Ch <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-835 | static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
int *len, int *strid, int read_packet) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE, startpos;
int ret;
recover:
startpos = avio_tell(pb);
syncword = avio_rb16(pb);
streamid = avio_r8(pb);
avio_r8(pb); /* counter not used */
reserved = avio_r8(pb);
flags = avio_r8(pb);
length = avio_rb16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = avio_rb32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
/* PVA Audio Packets either start with a signaled PES packet or
* are a continuation of the previous PES packet. New PES packets
* always start at the beginning of a PVA Packet, never somewhere in
* the middle. */
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = avio_rb24(pb);
avio_r8(pb);
pes_packet_length = avio_rb16(pb);
pes_flags = avio_rb16(pb);
pes_header_data_length = avio_r8(pb);
if (avio_feof(pb)) {
return AVERROR_EOF;
}
if (pes_signal != 1 || pes_header_data_length == 0) {
pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "
"trying to recover\n");
avio_skip(pb, length - 9);
if (!read_packet)
return AVERROR(EIO);
goto recover;
}
ret = avio_read(pb, pes_header_data, pes_header_data_length);
if (ret != pes_header_data_length)
return ret < 0 ? ret : AVERROR_INVALIDDATA;
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {
if (pes_header_data_length < 5) {
pva_log(s, AV_LOG_ERROR, "header too short\n");
avio_skip(pb, length);
return AVERROR_INVALIDDATA;
}
pva_pts = ff_parse_pes_pts(pes_header_data);
}
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if (pva_pts != AV_NOPTS_VALUE)
av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
*pts = pva_pts;
*len = length;
*strid = streamid;
return 0;
}
| 168,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
const HeapVector<VRLayer>& layers) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
UseCounter::Count(execution_context, UseCounter::kVRRequestPresent);
if (!execution_context->IsSecureContext()) {
UseCounter::Count(execution_context,
UseCounter::kVRRequestPresentInsecureOrigin);
}
ReportPresentationResult(PresentationResult::kRequested);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!capabilities_->canPresent()) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRDisplay cannot present.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kVRDisplayCannotPresent);
return promise;
}
bool first_present = !is_presenting_;
if (first_present && !UserGestureIndicator::UtilizeUserGesture() &&
!in_display_activate_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "API can only be initiated by a user gesture.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kNotInitiatedByUserGesture);
return promise;
}
if (layers.size() == 0 || layers.size() > capabilities_->maxLayers()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid number of layers.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidNumberOfLayers);
return promise;
}
if (layers[0].source().isNull()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid layer source.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerSource);
return promise;
}
layer_ = layers[0];
CanvasRenderingContext* rendering_context;
if (layer_.source().isHTMLCanvasElement()) {
rendering_context =
layer_.source().getAsHTMLCanvasElement()->RenderingContext();
} else {
DCHECK(layer_.source().isOffscreenCanvas());
rendering_context =
layer_.source().getAsOffscreenCanvas()->RenderingContext();
}
if (!rendering_context || !rendering_context->Is3d()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "Layer source must have a WebGLRenderingContext");
resolver->Reject(exception);
ReportPresentationResult(
PresentationResult::kLayerSourceMissingWebGLContext);
return promise;
}
rendering_context_ = ToWebGLRenderingContextBase(rendering_context);
context_gl_ = rendering_context_->ContextGL();
if ((layer_.leftBounds().size() != 0 && layer_.leftBounds().size() != 4) ||
(layer_.rightBounds().size() != 0 && layer_.rightBounds().size() != 4)) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError,
"Layer bounds must either be an empty array or have 4 values");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerBounds);
return promise;
}
if (!pending_present_resolvers_.IsEmpty()) {
pending_present_resolvers_.push_back(resolver);
} else if (first_present) {
bool secure_context =
ExecutionContext::From(script_state)->IsSecureContext();
if (!display_) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "The service is no longer active.");
resolver->Reject(exception);
return promise;
}
pending_present_resolvers_.push_back(resolver);
submit_frame_client_binding_.Close();
display_->RequestPresent(
secure_context,
submit_frame_client_binding_.CreateInterfacePtrAndBind(),
ConvertToBaseCallback(
WTF::Bind(&VRDisplay::OnPresentComplete, WrapPersistent(this))));
} else {
UpdateLayerBounds();
resolver->Resolve();
ReportPresentationResult(PresentationResult::kSuccessAlreadyPresenting);
}
return promise;
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
const HeapVector<VRLayer>& layers) {
DVLOG(1) << __FUNCTION__;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
UseCounter::Count(execution_context, UseCounter::kVRRequestPresent);
if (!execution_context->IsSecureContext()) {
UseCounter::Count(execution_context,
UseCounter::kVRRequestPresentInsecureOrigin);
}
ReportPresentationResult(PresentationResult::kRequested);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!capabilities_->canPresent()) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRDisplay cannot present.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kVRDisplayCannotPresent);
return promise;
}
bool first_present = !is_presenting_;
if (first_present && !UserGestureIndicator::UtilizeUserGesture() &&
!in_display_activate_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "API can only be initiated by a user gesture.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kNotInitiatedByUserGesture);
return promise;
}
if (layers.size() == 0 || layers.size() > capabilities_->maxLayers()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid number of layers.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidNumberOfLayers);
return promise;
}
if (layers[0].source().isNull()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid layer source.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerSource);
return promise;
}
layer_ = layers[0];
CanvasRenderingContext* rendering_context;
if (layer_.source().isHTMLCanvasElement()) {
rendering_context =
layer_.source().getAsHTMLCanvasElement()->RenderingContext();
} else {
DCHECK(layer_.source().isOffscreenCanvas());
rendering_context =
layer_.source().getAsOffscreenCanvas()->RenderingContext();
}
if (!rendering_context || !rendering_context->Is3d()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "Layer source must have a WebGLRenderingContext");
resolver->Reject(exception);
ReportPresentationResult(
PresentationResult::kLayerSourceMissingWebGLContext);
return promise;
}
rendering_context_ = ToWebGLRenderingContextBase(rendering_context);
context_gl_ = rendering_context_->ContextGL();
if ((layer_.leftBounds().size() != 0 && layer_.leftBounds().size() != 4) ||
(layer_.rightBounds().size() != 0 && layer_.rightBounds().size() != 4)) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError,
"Layer bounds must either be an empty array or have 4 values");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerBounds);
return promise;
}
if (!pending_present_resolvers_.IsEmpty()) {
pending_present_resolvers_.push_back(resolver);
} else if (first_present) {
bool secure_context =
ExecutionContext::From(script_state)->IsSecureContext();
if (!display_) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "The service is no longer active.");
resolver->Reject(exception);
return promise;
}
pending_present_resolvers_.push_back(resolver);
submit_frame_client_binding_.Close();
display_->RequestPresent(
secure_context,
submit_frame_client_binding_.CreateInterfacePtrAndBind(),
ConvertToBaseCallback(
WTF::Bind(&VRDisplay::OnPresentComplete, WrapPersistent(this))));
} else {
UpdateLayerBounds();
resolver->Resolve();
ReportPresentationResult(PresentationResult::kSuccessAlreadyPresenting);
}
return promise;
}
| 172,003 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) {
const char *symstr;
struct symbol_t *symbols;
int from, to, i, j, s, stridx, symbols_size, symbols_count;
SdbHash *hash;
if (!bin || !bin->symtab || !bin->symstr) {
return NULL;
}
/* parse symbol table */
/* parse dynamic symbol table */
symbols_count = (bin->dysymtab.nextdefsym + \
bin->dysymtab.nlocalsym + \
bin->dysymtab.nundefsym );
symbols_count += bin->nsymtab;
symbols_size = (symbols_count + 1) * 2 * sizeof (struct symbol_t);
if (symbols_size < 1) {
return NULL;
}
if (!(symbols = calloc (1, symbols_size))) {
return NULL;
}
hash = sdb_ht_new ();
j = 0; // symbol_idx
for (s = 0; s < 2; s++) {
switch (s) {
case 0:
from = bin->dysymtab.iextdefsym;
to = from + bin->dysymtab.nextdefsym;
break;
case 1:
from = bin->dysymtab.ilocalsym;
to = from + bin->dysymtab.nlocalsym;
break;
#if NOT_USED
case 2:
from = bin->dysymtab.iundefsym;
to = from + bin->dysymtab.nundefsym;
break;
#endif
}
if (from == to) {
continue;
}
#define OLD 1
#if OLD
from = R_MIN (R_MAX (0, from), symbols_size / sizeof (struct symbol_t));
to = R_MIN (to , symbols_size / sizeof (struct symbol_t));
to = R_MIN (to, bin->nsymtab);
#else
from = R_MIN (R_MAX (0, from), symbols_size/sizeof (struct symbol_t));
to = symbols_count; //symbols_size/sizeof(struct symbol_t);
#endif
int maxsymbols = symbols_size / sizeof (struct symbol_t);
if (to > 0x500000) {
bprintf ("WARNING: corrupted mach0 header: symbol table is too big %d\n", to);
free (symbols);
sdb_ht_free (hash);
return NULL;
}
if (symbols_count >= maxsymbols) {
symbols_count = maxsymbols - 1;
}
for (i = from; i < to && j < symbols_count; i++, j++) {
symbols[j].offset = addr_to_offset (bin, bin->symtab[i].n_value);
symbols[j].addr = bin->symtab[i].n_value;
symbols[j].size = 0; /* TODO: Is it anywhere? */
if (bin->symtab[i].n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
stridx = bin->symtab[i].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
{
int i = 0;
int len = 0;
len = bin->symstrlen - stridx;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((ut8)(symstr[i] & 0xff) == 0xff || !symstr[i]) {
len = i;
break;
}
}
char *symstr_dup = NULL;
if (len > 0) {
symstr_dup = r_str_ndup (symstr, len);
}
if (!symstr_dup) {
symbols[j].name[0] = 0;
} else {
r_str_ncpy (symbols[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (symbols[j].name, -1);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
}
free (symstr_dup);
} else {
symbols[j].name[0] = 0;
}
symbols[j].last = 0;
}
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
j--;
}
}
}
to = R_MIN (bin->nsymtab, bin->dysymtab.iundefsym + bin->dysymtab.nundefsym);
for (i = bin->dysymtab.iundefsym; i < to; i++) {
if (j > symbols_count) {
bprintf ("mach0-get-symbols: error\n");
break;
}
if (parse_import_stub(bin, &symbols[j], i))
symbols[j++].last = 0;
}
#if 1
for (i = 0; i < bin->nsymtab; i++) {
struct MACH0_(nlist) *st = &bin->symtab[i];
#if 0
bprintf ("stridx %d -> section %d type %d value = %d\n",
st->n_strx, st->n_sect, st->n_type, st->n_value);
#endif
stridx = st->n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
int section = st->n_sect;
if (section == 1 && j < symbols_count) { // text ??st->n_type == 1)
/* is symbol */
symbols[j].addr = st->n_value; // + text_base;
symbols[j].offset = addr_to_offset (bin, symbols[j].addr);
symbols[j].size = 0; /* find next symbol and crop */
if (st->n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
strncpy (symbols[j].name, symstr, R_BIN_MACH0_STRING_LENGTH);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 1] = 0;
symbols[j].last = 0;
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
} else {
j++;
}
}
}
#endif
sdb_ht_free (hash);
symbols[j].last = 1;
return symbols;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125 | struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) {
const char *symstr;
struct symbol_t *symbols;
int from, to, i, j, s, stridx, symbols_size, symbols_count;
SdbHash *hash;
if (!bin || !bin->symtab || !bin->symstr) {
return NULL;
}
/* parse symbol table */
/* parse dynamic symbol table */
symbols_count = (bin->dysymtab.nextdefsym + \
bin->dysymtab.nlocalsym + \
bin->dysymtab.nundefsym );
symbols_count += bin->nsymtab;
symbols_size = (symbols_count + 1) * 2 * sizeof (struct symbol_t);
if (symbols_size < 1) {
return NULL;
}
if (!(symbols = calloc (1, symbols_size))) {
return NULL;
}
hash = sdb_ht_new ();
j = 0; // symbol_idx
for (s = 0; s < 2; s++) {
switch (s) {
case 0:
from = bin->dysymtab.iextdefsym;
to = from + bin->dysymtab.nextdefsym;
break;
case 1:
from = bin->dysymtab.ilocalsym;
to = from + bin->dysymtab.nlocalsym;
break;
#if NOT_USED
case 2:
from = bin->dysymtab.iundefsym;
to = from + bin->dysymtab.nundefsym;
break;
#endif
}
if (from == to) {
continue;
}
#define OLD 1
#if OLD
from = R_MIN (R_MAX (0, from), symbols_size / sizeof (struct symbol_t));
to = R_MIN (to , symbols_size / sizeof (struct symbol_t));
to = R_MIN (to, bin->nsymtab);
#else
from = R_MIN (R_MAX (0, from), symbols_size/sizeof (struct symbol_t));
to = symbols_count; //symbols_size/sizeof(struct symbol_t);
#endif
int maxsymbols = symbols_size / sizeof (struct symbol_t);
if (to > 0x500000) {
bprintf ("WARNING: corrupted mach0 header: symbol table is too big %d\n", to);
free (symbols);
sdb_ht_free (hash);
return NULL;
}
if (symbols_count >= maxsymbols) {
symbols_count = maxsymbols - 1;
}
for (i = from; i < to && j < symbols_count; i++, j++) {
symbols[j].offset = addr_to_offset (bin, bin->symtab[i].n_value);
symbols[j].addr = bin->symtab[i].n_value;
symbols[j].size = 0; /* TODO: Is it anywhere? */
if (bin->symtab[i].n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
stridx = bin->symtab[i].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
{
int i = 0;
int len = 0;
len = bin->symstrlen - stridx;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((ut8)(symstr[i] & 0xff) == 0xff || !symstr[i]) {
len = i;
break;
}
}
char *symstr_dup = NULL;
if (len > 0) {
symstr_dup = r_str_ndup (symstr, len);
}
if (!symstr_dup) {
symbols[j].name[0] = 0;
} else {
r_str_ncpy (symbols[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (symbols[j].name, -1);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
}
free (symstr_dup);
} else {
symbols[j].name[0] = 0;
}
symbols[j].last = 0;
}
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
j--;
}
}
}
to = R_MIN (bin->nsymtab, bin->dysymtab.iundefsym + bin->dysymtab.nundefsym);
for (i = bin->dysymtab.iundefsym; i < to; i++) {
if (j > symbols_count) {
bprintf ("mach0-get-symbols: error\n");
break;
}
if (parse_import_stub(bin, &symbols[j], i)) {
symbols[j++].last = 0;
}
}
#if 1
for (i = 0; i < bin->nsymtab; i++) {
struct MACH0_(nlist) *st = &bin->symtab[i];
#if 0
bprintf ("stridx %d -> section %d type %d value = %d\n",
st->n_strx, st->n_sect, st->n_type, st->n_value);
#endif
stridx = st->n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
int section = st->n_sect;
if (section == 1 && j < symbols_count) { // text ??st->n_type == 1)
/* is symbol */
symbols[j].addr = st->n_value; // + text_base;
symbols[j].offset = addr_to_offset (bin, symbols[j].addr);
symbols[j].size = 0; /* find next symbol and crop */
if (st->n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
strncpy (symbols[j].name, symstr, R_BIN_MACH0_STRING_LENGTH);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 1] = 0;
symbols[j].last = 0;
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
} else {
j++;
}
}
}
#endif
sdb_ht_free (hash);
symbols[j].last = 1;
return symbols;
}
| 169,226 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udp_push_pending_frames(struct sock *sk)
{
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
struct sk_buff *skb;
int err = 0;
skb = ip_finish_skb(sk, fl4);
if (!skb)
goto out;
err = udp_send_skb(skb, fl4);
out:
up->len = 0;
up->pending = 0;
return err;
}
Commit Message: ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data
We accidentally call down to ip6_push_pending_frames when uncorking
pending AF_INET data on a ipv6 socket. This results in the following
splat (from Dave Jones):
skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL>
------------[ cut here ]------------
kernel BUG at net/core/skbuff.c:126!
invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC
Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth
+netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c
CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37
task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000
RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282
RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006
RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520
RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800
R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800
FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600
Stack:
ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4
ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6
ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0
Call Trace:
[<ffffffff8159a9aa>] skb_push+0x3a/0x40
[<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0
[<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140
[<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0
[<ffffffff81694660>] ? udplite_getfrag+0x20/0x20
[<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0
[<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0
[<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40
[<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20
[<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0
[<ffffffff816f5d54>] tracesys+0xdd/0xe2
Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55
RIP [<ffffffff816e759c>] skb_panic+0x63/0x65
RSP <ffff8801e6431de8>
This patch adds a check if the pending data is of address family AF_INET
and directly calls udp_push_ending_frames from udp_v6_push_pending_frames
if that is the case.
This bug was found by Dave Jones with trinity.
(Also move the initialization of fl6 below the AF_INET check, even if
not strictly necessary.)
Cc: Dave Jones <[email protected]>
Cc: YOSHIFUJI Hideaki <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int udp_push_pending_frames(struct sock *sk)
int udp_push_pending_frames(struct sock *sk)
{
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
struct sk_buff *skb;
int err = 0;
skb = ip_finish_skb(sk, fl4);
if (!skb)
goto out;
err = udp_send_skb(skb, fl4);
out:
up->len = 0;
up->pending = 0;
return err;
}
| 166,016 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int huft_build(const unsigned *b, const unsigned n,
const unsigned s, const unsigned short *d,
const unsigned char *e, huft_t **t, unsigned *m)
{
unsigned a; /* counter for codes of length k */
unsigned c[BMAX + 1]; /* bit length count table */
unsigned eob_len; /* length of end-of-block code (value 256) */
unsigned f; /* i repeats in table every f entries */
int g; /* maximum code length */
int htl; /* table level */
unsigned i; /* counter, current code */
unsigned j; /* counter */
int k; /* number of bits in current code */
unsigned *p; /* pointer into c[], b[], or v[] */
huft_t *q; /* points to current table */
huft_t r; /* table entry for structure assignment */
huft_t *u[BMAX]; /* table stack */
unsigned v[N_MAX]; /* values in order of bit length */
int ws[BMAX + 1]; /* bits decoded stack */
int w; /* bits decoded */
unsigned x[BMAX + 1]; /* bit offsets, then code stack */
int y; /* number of dummy codes added */
unsigned z; /* number of entries in current table */
/* Length of EOB code, if any */
eob_len = n > 256 ? b[256] : BMAX;
*t = NULL;
/* Generate counts for each bit length */
memset(c, 0, sizeof(c));
p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */
i = n;
do {
c[*p]++; /* assume all entries <= BMAX */
} while (--i);
if (c[0] == n) { /* null input - all zero length codes */
*m = 0;
return 2;
}
/* Find minimum and maximum length, bound *m by those */
for (j = 1; (j <= BMAX) && (c[j] == 0); j++)
continue;
k = j; /* minimum code length */
for (i = BMAX; (c[i] == 0) && i; i--)
continue;
g = i; /* maximum code length */
*m = (*m < j) ? j : ((*m > i) ? i : *m);
/* Adjust last length count to fill out codes, if needed */
for (y = 1 << j; j < i; j++, y <<= 1) {
y -= c[j];
if (y < 0)
return 2; /* bad input: more codes than bits */
}
y -= c[i];
if (y < 0)
return 2;
c[i] += y;
/* Generate starting offsets into the value table for each length */
x[1] = j = 0;
p = c + 1;
xp = x + 2;
while (--i) { /* note that i == g from above */
j += *p++;
*xp++ = j;
}
}
Commit Message:
CWE ID: CWE-476 | static int huft_build(const unsigned *b, const unsigned n,
const unsigned s, const unsigned short *d,
const unsigned char *e, huft_t **t, unsigned *m)
{
unsigned a; /* counter for codes of length k */
unsigned c[BMAX + 1]; /* bit length count table */
unsigned eob_len; /* length of end-of-block code (value 256) */
unsigned f; /* i repeats in table every f entries */
int g; /* maximum code length */
int htl; /* table level */
unsigned i; /* counter, current code */
unsigned j; /* counter */
int k; /* number of bits in current code */
const unsigned *p; /* pointer into c[], b[], or v[] */
huft_t *q; /* points to current table */
huft_t r; /* table entry for structure assignment */
huft_t *u[BMAX]; /* table stack */
unsigned v[N_MAX]; /* values in order of bit length */
unsigned v_end;
int ws[BMAX + 1]; /* bits decoded stack */
int w; /* bits decoded */
unsigned x[BMAX + 1]; /* bit offsets, then code stack */
int y; /* number of dummy codes added */
unsigned z; /* number of entries in current table */
/* Length of EOB code, if any */
eob_len = n > 256 ? b[256] : BMAX;
*t = NULL;
/* Generate counts for each bit length */
memset(c, 0, sizeof(c));
p = b;
i = n;
do {
c[*p]++; /* assume all entries <= BMAX */
} while (--i);
if (c[0] == n) { /* null input - all zero length codes */
*m = 0;
return 2;
}
/* Find minimum and maximum length, bound *m by those */
for (j = 1; (j <= BMAX) && (c[j] == 0); j++)
continue;
k = j; /* minimum code length */
for (i = BMAX; (c[i] == 0) && i; i--)
continue;
g = i; /* maximum code length */
*m = (*m < j) ? j : ((*m > i) ? i : *m);
/* Adjust last length count to fill out codes, if needed */
for (y = 1 << j; j < i; j++, y <<= 1) {
y -= c[j];
if (y < 0)
return 2; /* bad input: more codes than bits */
}
y -= c[i];
if (y < 0)
return 2;
c[i] += y;
/* Generate starting offsets into the value table for each length */
x[1] = j = 0;
p = c + 1;
xp = x + 2;
while (--i) { /* note that i == g from above */
j += *p++;
*xp++ = j;
}
}
| 165,508 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void queue_delete(struct snd_seq_queue *q)
{
/* stop and release the timer */
snd_seq_timer_stop(q->timer);
snd_seq_timer_close(q);
/* wait until access free */
snd_use_lock_sync(&q->use_lock);
/* release resources... */
snd_seq_prioq_delete(&q->tickq);
snd_seq_prioq_delete(&q->timeq);
snd_seq_timer_delete(&q->timer);
kfree(q);
}
Commit Message: ALSA: seq: Fix race at timer setup and close
ALSA sequencer code has an open race between the timer setup ioctl and
the close of the client. This was triggered by syzkaller fuzzer, and
a use-after-free was caught there as a result.
This patch papers over it by adding a proper queue->timer_mutex lock
around the timer-related calls in the relevant code path.
Reported-by: Dmitry Vyukov <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362 | static void queue_delete(struct snd_seq_queue *q)
{
/* stop and release the timer */
mutex_lock(&q->timer_mutex);
snd_seq_timer_stop(q->timer);
snd_seq_timer_close(q);
mutex_unlock(&q->timer_mutex);
/* wait until access free */
snd_use_lock_sync(&q->use_lock);
/* release resources... */
snd_seq_prioq_delete(&q->tickq);
snd_seq_prioq_delete(&q->timeq);
snd_seq_timer_delete(&q->timer);
kfree(q);
}
| 167,409 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
Commit Message: ...
CWE ID: CWE-754 | static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
| 167,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
Commit Message: KEYS: prevent creating a different user's keyrings
It was possible for an unprivileged user to create the user and user
session keyrings for another user. For example:
sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u
keyctl add keyring _uid_ses.4000 "" @u
sleep 15' &
sleep 1
sudo -u '#4000' keyctl describe @u
sudo -u '#4000' keyctl describe @us
This is problematic because these "fake" keyrings won't have the right
permissions. In particular, the user who created them first will own
them and will have full access to them via the possessor permissions,
which can be used to compromise the security of a user's keys:
-4: alswrv-----v------------ 3000 0 keyring: _uid.4000
-5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000
Fix it by marking user and user session keyrings with a flag
KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session
keyring by name, skip all keyrings that don't have the flag set.
Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed")
Cc: <[email protected]> [v2.6.26+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: | int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
| 169,376 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
return follow_dotdot_rcu(nd);
} else
follow_dotdot(nd);
}
return 0;
}
Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root
In rare cases a directory can be renamed out from under a bind mount.
In those cases without special handling it becomes possible to walk up
the directory tree to the root dentry of the filesystem and down
from the root dentry to every other file or directory on the filesystem.
Like division by zero .. from an unconnected path can not be given
a useful semantic as there is no predicting at which path component
the code will realize it is unconnected. We certainly can not match
the current behavior as the current behavior is a security hole.
Therefore when encounting .. when following an unconnected path
return -ENOENT.
- Add a function path_connected to verify path->dentry is reachable
from path->mnt.mnt_root. AKA to validate that rename did not do
something nasty to the bind mount.
To avoid races path_connected must be called after following a path
component to it's next path component.
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-254 | static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
return follow_dotdot_rcu(nd);
} else
return follow_dotdot(nd);
}
return 0;
}
| 166,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: iakerb_gss_init_sec_context(OM_uint32 *minor_status,
gss_cred_id_t claimant_cred_handle,
gss_ctx_id_t *context_handle,
gss_name_t target_name,
gss_OID mech_type,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_channel_bindings_t input_chan_bindings,
gss_buffer_t input_token,
gss_OID *actual_mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec)
{
OM_uint32 major_status = GSS_S_FAILURE;
krb5_error_code code;
iakerb_ctx_id_t ctx;
krb5_gss_cred_id_t kcred;
krb5_gss_name_t kname;
krb5_boolean cred_locked = FALSE;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) {
major_status = iakerb_gss_acquire_cred(minor_status, NULL,
GSS_C_INDEFINITE,
GSS_C_NULL_OID_SET,
GSS_C_INITIATE,
&ctx->defcred, NULL, NULL);
if (GSS_ERROR(major_status))
goto cleanup;
claimant_cred_handle = ctx->defcred;
}
} else {
ctx = (iakerb_ctx_id_t)*context_handle;
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL)
claimant_cred_handle = ctx->defcred;
}
kname = (krb5_gss_name_t)target_name;
major_status = kg_cred_resolve(minor_status, ctx->k5c,
claimant_cred_handle, target_name);
if (GSS_ERROR(major_status))
goto cleanup;
cred_locked = TRUE;
kcred = (krb5_gss_cred_id_t)claimant_cred_handle;
major_status = GSS_S_FAILURE;
if (initialContextToken) {
code = iakerb_get_initial_state(ctx, kcred, kname, time_req,
&ctx->state);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
*context_handle = (gss_ctx_id_t)ctx;
}
if (ctx->state != IAKERB_AP_REQ) {
/* We need to do IAKERB. */
code = iakerb_initiator_step(ctx,
kcred,
kname,
time_req,
input_token,
output_token);
if (code == KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0) {
*minor_status = code;
goto cleanup;
}
}
if (ctx->state == IAKERB_AP_REQ) {
krb5_gss_ctx_ext_rec exts;
if (cred_locked) {
k5_mutex_unlock(&kcred->lock);
cred_locked = FALSE;
}
iakerb_make_exts(ctx, &exts);
if (ctx->gssc == GSS_C_NO_CONTEXT)
input_token = GSS_C_NO_BUFFER;
/* IAKERB is finished, or we skipped to Kerberos directly. */
major_status = krb5_gss_init_sec_context_ext(minor_status,
(gss_cred_id_t) kcred,
&ctx->gssc,
target_name,
(gss_OID)gss_mech_iakerb,
req_flags,
time_req,
input_chan_bindings,
input_token,
NULL,
output_token,
ret_flags,
time_rec,
&exts);
if (major_status == GSS_S_COMPLETE) {
*context_handle = ctx->gssc;
ctx->gssc = GSS_C_NO_CONTEXT;
iakerb_release_context(ctx);
}
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_krb5;
} else {
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
major_status = GSS_S_CONTINUE_NEEDED;
}
cleanup:
if (cred_locked)
k5_mutex_unlock(&kcred->lock);
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return major_status;
}
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_gss_init_sec_context(OM_uint32 *minor_status,
gss_cred_id_t claimant_cred_handle,
gss_ctx_id_t *context_handle,
gss_name_t target_name,
gss_OID mech_type,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_channel_bindings_t input_chan_bindings,
gss_buffer_t input_token,
gss_OID *actual_mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec)
{
OM_uint32 major_status = GSS_S_FAILURE;
krb5_error_code code;
iakerb_ctx_id_t ctx;
krb5_gss_cred_id_t kcred;
krb5_gss_name_t kname;
krb5_boolean cred_locked = FALSE;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx, 1);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) {
major_status = iakerb_gss_acquire_cred(minor_status, NULL,
GSS_C_INDEFINITE,
GSS_C_NULL_OID_SET,
GSS_C_INITIATE,
&ctx->defcred, NULL, NULL);
if (GSS_ERROR(major_status))
goto cleanup;
claimant_cred_handle = ctx->defcred;
}
} else {
ctx = (iakerb_ctx_id_t)*context_handle;
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL)
claimant_cred_handle = ctx->defcred;
}
kname = (krb5_gss_name_t)target_name;
major_status = kg_cred_resolve(minor_status, ctx->k5c,
claimant_cred_handle, target_name);
if (GSS_ERROR(major_status))
goto cleanup;
cred_locked = TRUE;
kcred = (krb5_gss_cred_id_t)claimant_cred_handle;
major_status = GSS_S_FAILURE;
if (initialContextToken) {
code = iakerb_get_initial_state(ctx, kcred, kname, time_req,
&ctx->state);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
*context_handle = (gss_ctx_id_t)ctx;
}
if (ctx->state != IAKERB_AP_REQ) {
/* We need to do IAKERB. */
code = iakerb_initiator_step(ctx,
kcred,
kname,
time_req,
input_token,
output_token);
if (code == KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0) {
*minor_status = code;
goto cleanup;
}
}
if (ctx->state == IAKERB_AP_REQ) {
krb5_gss_ctx_ext_rec exts;
if (cred_locked) {
k5_mutex_unlock(&kcred->lock);
cred_locked = FALSE;
}
iakerb_make_exts(ctx, &exts);
if (ctx->gssc == GSS_C_NO_CONTEXT)
input_token = GSS_C_NO_BUFFER;
/* IAKERB is finished, or we skipped to Kerberos directly. */
major_status = krb5_gss_init_sec_context_ext(minor_status,
(gss_cred_id_t) kcred,
&ctx->gssc,
target_name,
(gss_OID)gss_mech_iakerb,
req_flags,
time_req,
input_chan_bindings,
input_token,
NULL,
output_token,
ret_flags,
time_rec,
&exts);
if (major_status == GSS_S_COMPLETE)
ctx->established = 1;
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_krb5;
} else {
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
major_status = GSS_S_CONTINUE_NEEDED;
}
cleanup:
if (cred_locked)
k5_mutex_unlock(&kcred->lock);
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return major_status;
}
| 166,646 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
| 170,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: }static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | }static inline void WriteResourceLong(unsigned char *p,
}
static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
| 169,950 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int build_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_sm_info *sm_info;
int err;
sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
if (!sm_info)
return -ENOMEM;
/* init sm info */
sbi->sm_info = sm_info;
sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
sm_info->rec_prefree_segments = sm_info->main_segments *
DEF_RECLAIM_PREFREE_SEGMENTS / 100;
if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
if (!test_opt(sbi, LFS))
sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
INIT_LIST_HEAD(&sm_info->sit_entry_set);
if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) {
err = create_flush_cmd_control(sbi);
if (err)
return err;
}
err = create_discard_cmd_control(sbi);
if (err)
return err;
err = build_sit_info(sbi);
if (err)
return err;
err = build_free_segmap(sbi);
if (err)
return err;
err = build_curseg(sbi);
if (err)
return err;
/* reinit free segmap based on SIT */
build_sit_entries(sbi);
init_free_segmap(sbi);
err = build_dirty_segmap(sbi);
if (err)
return err;
init_min_max_mtime(sbi);
return 0;
}
Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control
Mount fs with option noflush_merge, boot failed for illegal address
fcc in function f2fs_issue_flush:
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush); -> Here, fcc illegal
return ret;
}
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-476 | int build_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_sm_info *sm_info;
int err;
sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
if (!sm_info)
return -ENOMEM;
/* init sm info */
sbi->sm_info = sm_info;
sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
sm_info->rec_prefree_segments = sm_info->main_segments *
DEF_RECLAIM_PREFREE_SEGMENTS / 100;
if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
if (!test_opt(sbi, LFS))
sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
INIT_LIST_HEAD(&sm_info->sit_entry_set);
if (!f2fs_readonly(sbi->sb)) {
err = create_flush_cmd_control(sbi);
if (err)
return err;
}
err = create_discard_cmd_control(sbi);
if (err)
return err;
err = build_sit_info(sbi);
if (err)
return err;
err = build_free_segmap(sbi);
if (err)
return err;
err = build_curseg(sbi);
if (err)
return err;
/* reinit free segmap based on SIT */
build_sit_entries(sbi);
init_free_segmap(sbi);
err = build_dirty_segmap(sbi);
if (err)
return err;
init_min_max_mtime(sbi);
return 0;
}
| 169,381 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LockScreenMediaControlsView::OnMouseExited(const ui::MouseEvent& event) {
if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating())
return;
close_button_->SetVisible(false);
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | void LockScreenMediaControlsView::OnMouseExited(const ui::MouseEvent& event) {
if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating())
return;
header_row_->SetCloseButtonVisibility(false);
}
| 172,341 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_callback(png_structp pp, png_unknown_chunkp pc)
{
/* This function mimics the behavior of png_set_keep_unknown_chunks by
* returning '0' to keep the chunk and '1' to discard it.
*/
display *d = voidcast(display*, png_get_user_chunk_ptr(pp));
int chunk = findb(pc->name);
int keep, discard;
if (chunk < 0) /* not one in our list, so not a known chunk */
keep = d->keep;
else
{
keep = chunk_info[chunk].keep;
if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
{
/* See the comments in png.h - use the default for unknown chunks,
* do not keep known chunks.
*/
if (chunk_info[chunk].unknown)
keep = d->keep;
else
keep = PNG_HANDLE_CHUNK_NEVER;
}
}
switch (keep)
{
default:
fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file,
d->test, chunk_info[chunk].keep);
display_exit(d);
case PNG_HANDLE_CHUNK_AS_DEFAULT:
case PNG_HANDLE_CHUNK_NEVER:
discard = 1/*handled; discard*/;
break;
case PNG_HANDLE_CHUNK_IF_SAFE:
case PNG_HANDLE_CHUNK_ALWAYS:
discard = 0/*not handled; keep*/;
break;
}
/* Also store information about this chunk in the display, the relevant flag
* is set if the chunk is to be kept ('not handled'.)
*/
if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */
{
png_uint_32 flag = chunk_info[chunk].flag;
if (pc->location & PNG_AFTER_IDAT)
d->after_IDAT |= flag;
else
d->before_IDAT |= flag;
}
/* However if there is no support to store unknown chunks don't ask libpng to
* do it; there will be an png_error.
*/
# ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
return discard;
# else
return 1; /*handled; discard*/
# endif
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | read_callback(png_structp pp, png_unknown_chunkp pc)
{
/* This function mimics the behavior of png_set_keep_unknown_chunks by
* returning '0' to keep the chunk and '1' to discard it.
*/
display *d = voidcast(display*, png_get_user_chunk_ptr(pp));
int chunk = findb(pc->name);
int keep, discard;
if (chunk < 0) /* not one in our list, so not a known chunk */
keep = d->keep;
else
{
keep = chunk_info[chunk].keep;
if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
{
/* See the comments in png.h - use the default for unknown chunks,
* do not keep known chunks.
*/
if (chunk_info[chunk].unknown)
keep = d->keep;
else
keep = PNG_HANDLE_CHUNK_NEVER;
}
}
switch (keep)
{
default:
fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file,
d->test, chunk_info[chunk].keep);
display_exit(d);
case PNG_HANDLE_CHUNK_AS_DEFAULT:
case PNG_HANDLE_CHUNK_NEVER:
discard = 1/*handled; discard*/;
break;
case PNG_HANDLE_CHUNK_IF_SAFE:
case PNG_HANDLE_CHUNK_ALWAYS:
discard = 0/*not handled; keep*/;
break;
}
/* Also store information about this chunk in the display, the relevant flag
* is set if the chunk is to be kept ('not handled'.)
*/
if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */
{
png_uint_32 flag = chunk_info[chunk].flag;
if (pc->location & PNG_AFTER_IDAT)
d->after_IDAT |= flag;
else
d->before_IDAT |= flag;
}
/* However if there is no support to store unknown chunks don't ask libpng to
* do it; there will be an png_error.
*/
# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
return discard;
# else
return 1; /*handled; discard*/
# endif
}
| 173,599 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
Commit Message: Fixed ##72433: Use After Free Vulnerability in PHP's GC algorithm and unserialize
CWE ID: CWE-416 | PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.get_gc = spl_array_get_gc;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
| 167,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
down_write(&card->controls_rwsem);
_kctl = snd_ctl_find_id(card, &info->id);
err = 0;
if (_kctl) {
if (replace)
err = snd_ctl_remove(card, _kctl);
else
err = -EBUSY;
} else {
if (replace)
err = -ENOENT;
}
up_write(&card->controls_rwsem);
if (err < 0)
return err;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->card = card;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
Commit Message: ALSA: control: Fix replacing user controls
There are two issues with the current implementation for replacing user
controls. The first is that the code does not check if the control is actually a
user control and neither does it check if the control is owned by the process
that tries to remove it. That allows userspace applications to remove arbitrary
controls, which can cause a user after free if a for example a driver does not
expect a control to be removed from under its feed.
The second issue is that on one hand when a control is replaced the
user_ctl_count limit is not checked and on the other hand the user_ctl_count is
increased (even though the number of user controls does not change). This allows
userspace, once the user_ctl_count limit as been reached, to repeatedly replace
a control until user_ctl_count overflows. Once that happens new controls can be
added effectively bypassing the user_ctl_count limit.
Both issues can be fixed by instead of open-coding the removal of the control
that is to be replaced to use snd_ctl_remove_user_ctl(). This function does
proper permission checks as well as decrements user_ctl_count after the control
has been removed.
Note that by using snd_ctl_remove_user_ctl() the check which returns -EBUSY at
beginning of the function if the control already exists is removed. This is not
a problem though since the check is quite useless, because the lock that is
protecting the control list is released between the check and before adding the
new control to the list, which means that it is possible that a different
control with the same settings is added to the list after the check. Luckily
there is another check that is done while holding the lock in snd_ctl_add(), so
we'll rely on that to make sure that the same control is not added twice.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189 | static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
if (replace) {
err = snd_ctl_remove_user_ctl(file, &info->id);
if (err)
return err;
}
if (card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->card = card;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
| 166,291 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PaymentRequest::CanMakePayment() {
if (observer_for_testing_)
observer_for_testing_->OnCanMakePaymentCalled();
if (!delegate_->GetPrefService()->GetBoolean(kCanMakePaymentEnabled) ||
!state_) {
CanMakePaymentCallback(/*can_make_payment=*/false);
} else {
state_->CanMakePayment(
base::BindOnce(&PaymentRequest::CanMakePaymentCallback,
weak_ptr_factory_.GetWeakPtr()));
}
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189 | void PaymentRequest::CanMakePayment() {
if (!IsInitialized()) {
log_.Error("Attempted canMakePayment without initialization");
OnConnectionTerminated();
return;
}
// It's valid to call canMakePayment() without calling show() first.
if (observer_for_testing_)
observer_for_testing_->OnCanMakePaymentCalled();
if (!delegate_->GetPrefService()->GetBoolean(kCanMakePaymentEnabled) ||
!state_) {
CanMakePaymentCallback(/*can_make_payment=*/false);
} else {
state_->CanMakePayment(
base::BindOnce(&PaymentRequest::CanMakePaymentCallback,
weak_ptr_factory_.GetWeakPtr()));
}
}
| 173,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 8);
return MagickTrue;
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20 | static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
return(SkipDXTMipmaps(image,dds_info,8,exception));
}
| 168,899 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MediaElementAudioSourceHandler::WouldTaintOrigin() {
if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) {
return false;
}
if (!MediaElement()->HasSingleSecurityOrigin()) {
return true;
}
return Context()->WouldTaintOrigin(MediaElement()->currentSrc());
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool MediaElementAudioSourceHandler::WouldTaintOrigin() {
return MediaElement()->GetWebMediaPlayer()->WouldTaintOrigin();
}
| 172,634 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FidoCableHandshakeHandler::ValidateAuthenticatorHandshakeMessage(
base::span<const uint8_t> response) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(handshake_key_))
return false;
if (response.size() != kCableAuthenticatorHandshakeMessageSize) {
return false;
}
const auto authenticator_hello = response.first(
kCableAuthenticatorHandshakeMessageSize - kCableHandshakeMacMessageSize);
if (!hmac.VerifyTruncated(
fido_parsing_utils::ConvertToStringPiece(authenticator_hello),
fido_parsing_utils::ConvertToStringPiece(
response.subspan(authenticator_hello.size())))) {
return false;
}
const auto authenticator_hello_cbor =
cbor::CBORReader::Read(authenticator_hello);
if (!authenticator_hello_cbor || !authenticator_hello_cbor->is_map() ||
authenticator_hello_cbor->GetMap().size() != 2) {
return false;
}
const auto authenticator_hello_msg =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(0));
if (authenticator_hello_msg == authenticator_hello_cbor->GetMap().end() ||
!authenticator_hello_msg->second.is_string() ||
authenticator_hello_msg->second.GetString() !=
kCableAuthenticatorHelloMessage) {
return false;
}
const auto authenticator_random_nonce =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(1));
if (authenticator_random_nonce == authenticator_hello_cbor->GetMap().end() ||
!authenticator_random_nonce->second.is_bytestring() ||
authenticator_random_nonce->second.GetBytestring().size() != 16) {
return false;
}
cable_device_->SetEncryptionData(
GetEncryptionKeyAfterSuccessfulHandshake(
authenticator_random_nonce->second.GetBytestring()),
nonce_);
return true;
}
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586657}
CWE ID: CWE-22 | bool FidoCableHandshakeHandler::ValidateAuthenticatorHandshakeMessage(
base::span<const uint8_t> response) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(handshake_key_))
return false;
if (response.size() != kCableAuthenticatorHandshakeMessageSize) {
return false;
}
const auto authenticator_hello = response.first(
kCableAuthenticatorHandshakeMessageSize - kCableHandshakeMacMessageSize);
if (!hmac.VerifyTruncated(
fido_parsing_utils::ConvertToStringPiece(authenticator_hello),
fido_parsing_utils::ConvertToStringPiece(
response.subspan(authenticator_hello.size())))) {
return false;
}
const auto authenticator_hello_cbor =
cbor::CBORReader::Read(authenticator_hello);
if (!authenticator_hello_cbor || !authenticator_hello_cbor->is_map() ||
authenticator_hello_cbor->GetMap().size() != 2) {
return false;
}
const auto authenticator_hello_msg =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(0));
if (authenticator_hello_msg == authenticator_hello_cbor->GetMap().end() ||
!authenticator_hello_msg->second.is_string() ||
authenticator_hello_msg->second.GetString() !=
kCableAuthenticatorHelloMessage) {
return false;
}
const auto authenticator_random_nonce =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(1));
if (authenticator_random_nonce == authenticator_hello_cbor->GetMap().end() ||
!authenticator_random_nonce->second.is_bytestring() ||
authenticator_random_nonce->second.GetBytestring().size() != 16) {
return false;
}
cable_device_->SetEncryptionData(
GetEncryptionKeyAfterSuccessfulHandshake(base::make_span<16>(
authenticator_random_nonce->second.GetBytestring())),
nonce_);
return true;
}
| 172,274 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXIBarrierReleasePointer(ClientPtr client)
{
xXIBarrierReleasePointerInfo *info;
REQUEST(xXIBarrierReleasePointerReq);
int i;
swaps(&stuff->length);
REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq);
swapl(&stuff->num_barriers);
REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo));
info = (xXIBarrierReleasePointerInfo*) &stuff[1];
swapl(&info->barrier);
swapl(&info->eventid);
}
Commit Message:
CWE ID: CWE-190 | SProcXIBarrierReleasePointer(ClientPtr client)
{
xXIBarrierReleasePointerInfo *info;
REQUEST(xXIBarrierReleasePointerReq);
int i;
swaps(&stuff->length);
REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq);
swapl(&stuff->num_barriers);
if (stuff->num_barriers > UINT32_MAX / sizeof(xXIBarrierReleasePointerInfo))
return BadLength;
REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo));
info = (xXIBarrierReleasePointerInfo*) &stuff[1];
swapl(&info->barrier);
swapl(&info->eventid);
}
| 165,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval)
{
GetByteContext *gb = &s->gb;
RangeCoder *rc = &s->rc;
unsigned totfr = pixel->total_freq;
unsigned value, x = 0, cumfr = 0, cnt_x = 0;
int i, j, ret, c, cnt_c;
if ((ret = s->get_freq(rc, totfr, &value)) < 0)
return ret;
while (x < 16) {
cnt_x = pixel->lookup[x];
if (value >= cumfr + cnt_x)
cumfr += cnt_x;
else
break;
x++;
}
c = x * 16;
cnt_c = 0;
while (c < 256) {
cnt_c = pixel->freq[c];
if (value >= cumfr + cnt_c)
cumfr += cnt_c;
else
break;
c++;
}
if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0)
return ret;
pixel->freq[c] = cnt_c + step;
pixel->lookup[x] = cnt_x + step;
totfr += step;
if (totfr > BOT) {
totfr = 0;
for (i = 0; i < 256; i++) {
unsigned nc = (pixel->freq[i] >> 1) + 1;
pixel->freq[i] = nc;
totfr += nc;
}
for (i = 0; i < 16; i++) {
unsigned sum = 0;
unsigned i16_17 = i << 4;
for (j = 0; j < 16; j++)
sum += pixel->freq[i16_17 + j];
pixel->lookup[i] = sum;
}
}
pixel->total_freq = totfr;
*rval = c & s->cbits;
return 0;
}
Commit Message: avcodec/scpr: Fix multiple runtime error: index 256 out of bounds for type 'unsigned int [256]'
Fixes: 1519/clusterfuzz-testcase-minimized-5286680976162816
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval)
{
GetByteContext *gb = &s->gb;
RangeCoder *rc = &s->rc;
unsigned totfr = pixel->total_freq;
unsigned value, x = 0, cumfr = 0, cnt_x = 0;
int i, j, ret, c, cnt_c;
if ((ret = s->get_freq(rc, totfr, &value)) < 0)
return ret;
while (x < 16) {
cnt_x = pixel->lookup[x];
if (value >= cumfr + cnt_x)
cumfr += cnt_x;
else
break;
x++;
}
c = x * 16;
cnt_c = 0;
while (c < 256) {
cnt_c = pixel->freq[c];
if (value >= cumfr + cnt_c)
cumfr += cnt_c;
else
break;
c++;
}
if (x >= 16 || c >= 256) {
return AVERROR_INVALIDDATA;
}
if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0)
return ret;
pixel->freq[c] = cnt_c + step;
pixel->lookup[x] = cnt_x + step;
totfr += step;
if (totfr > BOT) {
totfr = 0;
for (i = 0; i < 256; i++) {
unsigned nc = (pixel->freq[i] >> 1) + 1;
pixel->freq[i] = nc;
totfr += nc;
}
for (i = 0; i < 16; i++) {
unsigned sum = 0;
unsigned i16_17 = i << 4;
for (j = 0; j < 16; j++)
sum += pixel->freq[i16_17 + j];
pixel->lookup[i] = sum;
}
}
pixel->total_freq = totfr;
*rval = c & s->cbits;
return 0;
}
| 170,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMXNodeInstance::OMXNodeInstance(
OMX *owner, const sp<IOMXObserver> &observer, const char *name)
: mOwner(owner),
mNodeID(0),
mHandle(NULL),
mObserver(observer),
mDying(false),
mBufferIDCount(0)
{
mName = ADebug::GetDebugName(name);
DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug");
ALOGV("debug level for %s is %d", name, DEBUG);
DEBUG_BUMP = DEBUG;
mNumPortBuffers[0] = 0;
mNumPortBuffers[1] = 0;
mDebugLevelBumpPendingBuffers[0] = 0;
mDebugLevelBumpPendingBuffers[1] = 0;
mMetadataType[0] = kMetadataBufferTypeInvalid;
mMetadataType[1] = kMetadataBufferTypeInvalid;
mSecureBufferType[0] = kSecureBufferTypeUnknown;
mSecureBufferType[1] = kSecureBufferTypeUnknown;
mIsSecure = AString(name).endsWith(".secure");
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | OMXNodeInstance::OMXNodeInstance(
OMX *owner, const sp<IOMXObserver> &observer, const char *name)
: mOwner(owner),
mNodeID(0),
mHandle(NULL),
mObserver(observer),
mDying(false),
mSailed(false),
mQueriedProhibitedExtensions(false),
mBufferIDCount(0)
{
mName = ADebug::GetDebugName(name);
DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug");
ALOGV("debug level for %s is %d", name, DEBUG);
DEBUG_BUMP = DEBUG;
mNumPortBuffers[0] = 0;
mNumPortBuffers[1] = 0;
mDebugLevelBumpPendingBuffers[0] = 0;
mDebugLevelBumpPendingBuffers[1] = 0;
mMetadataType[0] = kMetadataBufferTypeInvalid;
mMetadataType[1] = kMetadataBufferTypeInvalid;
mSecureBufferType[0] = kSecureBufferTypeUnknown;
mSecureBufferType[1] = kSecureBufferTypeUnknown;
mIsSecure = AString(name).endsWith(".secure");
}
| 174,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = disconnect_mount(p, how);
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
struct mnt_namespace *ns;
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
ns = p->mnt_ns;
if (ns) {
ns->mounts--;
__touch_mnt_namespace(ns);
}
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = disconnect_mount(p, how);
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
| 167,011 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int rc;
ConstructResourceBytesCtx ctx;
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(ctx.specs[0]));
(void*) ((char*) stuff +
sz_xXResQueryResourceBytesReq))) {
return BadAlloc;
}
rc = ConstructResourceBytes(stuff->client, &ctx);
if (rc == Success) {
xXResQueryResourceBytesReply rep = {
.type = X_Reply,
.sequenceNumber = client->sequence,
.length = bytes_to_int32(ctx.resultBytes),
.numSizes = ctx.numSizes
};
if (client->swapped) {
swaps (&rep.sequenceNumber);
swapl (&rep.length);
swapl (&rep.numSizes);
SwapXResQueryResourceBytes(&ctx.response);
}
WriteToClient(client, sizeof(rep), &rep);
WriteFragmentsToClient(client, &ctx.response);
}
DestroyConstructResourceBytesCtx(&ctx);
return rc;
}
Commit Message:
CWE ID: CWE-20 | ProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int rc;
ConstructResourceBytesCtx ctx;
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
if (stuff->numSpecs > UINT32_MAX / sizeof(ctx.specs[0]))
return BadLength;
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(ctx.specs[0]));
(void*) ((char*) stuff +
sz_xXResQueryResourceBytesReq))) {
return BadAlloc;
}
rc = ConstructResourceBytes(stuff->client, &ctx);
if (rc == Success) {
xXResQueryResourceBytesReply rep = {
.type = X_Reply,
.sequenceNumber = client->sequence,
.length = bytes_to_int32(ctx.resultBytes),
.numSizes = ctx.numSizes
};
if (client->swapped) {
swaps (&rep.sequenceNumber);
swapl (&rep.length);
swapl (&rep.numSizes);
SwapXResQueryResourceBytes(&ctx.response);
}
WriteToClient(client, sizeof(rep), &rep);
WriteFragmentsToClient(client, &ctx.response);
}
DestroyConstructResourceBytesCtx(&ctx);
return rc;
}
| 165,434 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame(
BrowserFrame* browser_frame,
BrowserView* browser_view) {
if (views::Widget::IsPureViews())
return new BrowserFrameViews(browser_frame, browser_view);
return new BrowserFrameGtk(browser_frame, browser_view);
}
Commit Message: Fixed brekage when PureViews are enable but Desktop is not
[email protected]
BUG=none
TEST=chrome starts with --use-pure-views with touchui
Review URL: http://codereview.chromium.org/7210037
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91197 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame(
BrowserFrame* browser_frame,
BrowserView* browser_view) {
if (views::Widget::IsPureViews() &&
views::ViewsDelegate::views_delegate->GetDefaultParentView())
return new BrowserFrameViews(browser_frame, browser_view);
return new BrowserFrameGtk(browser_frame, browser_view);
}
| 170,315 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAACEncoder::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_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAACEncoder::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_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,189 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
{
int s_den;
unsigned u_den;
switch(format) {
case TAG_FMT_SBYTE: return *(signed char *)value;
case TAG_FMT_BYTE: return *(uchar *)value;
case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel);
case TAG_FMT_URATIONAL:
u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
if (u_den == 0) {
return 0;
} else {
return php_ifd_get32u(value, motorola_intel) / u_den;
}
case TAG_FMT_SRATIONAL:
s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
if (s_den == 0) {
return 0;
} else {
return php_ifd_get32s(value, motorola_intel) / s_den;
}
case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel);
/* Not sure if this is correct (never seen float used in Exif format) */
case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
#endif
return (size_t)*(float *)value;
case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
#endif
return (size_t)*(double *)value;
}
return 0;
}
Commit Message: Fix bug #73737 FPE when parsing a tag format
CWE ID: CWE-189 | static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
{
int s_den;
unsigned u_den;
switch(format) {
case TAG_FMT_SBYTE: return *(signed char *)value;
case TAG_FMT_BYTE: return *(uchar *)value;
case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel);
case TAG_FMT_URATIONAL:
u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
if (u_den == 0) {
return 0;
} else {
return php_ifd_get32u(value, motorola_intel) / u_den;
}
case TAG_FMT_SRATIONAL:
s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
if (s_den == 0) {
return 0;
} else {
return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den);
}
case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel);
/* Not sure if this is correct (never seen float used in Exif format) */
case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
#endif
return (size_t)*(float *)value;
case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
#endif
return (size_t)*(double *)value;
}
return 0;
}
| 168,516 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintingMessageFilter::OnUpdatePrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_PrintPages_Params params;
if (printer_query->last_status() != printing::PrintingContext::OK) {
params.Reset();
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);
params.params.document_cookie = printer_query->cookie();
params.pages =
printing::PageRange::GetPages(printer_query->settings().ranges);
}
PrintHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
if (printer_query->cookie() && printer_query->settings().dpi())
print_job_manager_->QueuePrinterQuery(printer_query.get());
else
printer_query->StopWorker();
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PrintingMessageFilter::OnUpdatePrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_PrintPages_Params params;
if (!printer_query.get() ||
printer_query->last_status() != printing::PrintingContext::OK) {
params.Reset();
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);
params.params.document_cookie = printer_query->cookie();
params.pages =
printing::PageRange::GetPages(printer_query->settings().ranges);
}
PrintHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
if (printer_query.get()) {
if (printer_query->cookie() && printer_query->settings().dpi())
print_job_manager_->QueuePrinterQuery(printer_query.get());
else
printer_query->StopWorker();
}
}
| 170,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return ERROR_SUCCESS;
const wchar_t* integrity_level_str = GetIntegrityLevelString(integrity_level);
if (!integrity_level_str) {
return ERROR_SUCCESS;
}
std::wstring ace_access = SDDL_NO_READ_UP;
ace_access += SDDL_NO_WRITE_UP;
DWORD error = SetObjectIntegrityLabel(::GetCurrentProcess(), SE_KERNEL_OBJECT,
ace_access.c_str(),
integrity_level_str);
if (ERROR_SUCCESS != error)
return error;
HANDLE token_handle;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
&token_handle))
return ::GetLastError();
base::win::ScopedHandle token(token_handle);
return SetTokenIntegrityLevel(token.Get(), integrity_level);
}
Commit Message: Prevent sandboxed processes from opening each other
TBR=brettw
BUG=117627
BUG=119150
TEST=sbox_validation_tests
Review URL: https://chromiumcodereview.appspot.com/9716027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return ERROR_SUCCESS;
// We don't check for an invalid level here because we'll just let it
// fail on the SetTokenIntegrityLevel call later on.
if (integrity_level == INTEGRITY_LEVEL_LAST) {
return ERROR_SUCCESS;
}
HANDLE token_handle;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
&token_handle))
return ::GetLastError();
base::win::ScopedHandle token(token_handle);
return SetTokenIntegrityLevel(token.Get(), integrity_level);
}
| 170,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyTrespass(
short * /* dst */,
const int *const * /* src */,
unsigned /* nSamples */,
unsigned /* nChannels */) {
TRESPASS();
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyTrespass(
short * /* dst */,
const int *[FLACParser::kMaxChannels] /* src */,
unsigned /* nSamples */,
unsigned /* nChannels */) {
TRESPASS();
}
| 174,024 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetLoginLibrary(
LoginLibrary* library, bool own) {
library_->login_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::SetLoginLibrary(
| 170,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DiceResponseHandler::OnTokenExchangeSuccess(
DiceTokenFetcher* token_fetcher,
const std::string& refresh_token,
bool is_under_advanced_protection) {
const std::string& email = token_fetcher->email();
const std::string& gaia_id = token_fetcher->gaia_id();
if (!CanGetTokenForAccount(gaia_id, email))
return;
VLOG(1) << "[Dice] OAuth success for email " << email;
bool should_enable_sync = token_fetcher->should_enable_sync();
std::string account_id =
account_tracker_service_->SeedAccountInfo(gaia_id, email);
account_tracker_service_->SetIsAdvancedProtectionAccount(
account_id, is_under_advanced_protection);
token_service_->UpdateCredentials(account_id, refresh_token);
about_signin_internals_->OnRefreshTokenReceived(
base::StringPrintf("Successful (%s)", account_id.c_str()));
if (should_enable_sync)
token_fetcher->delegate()->EnableSync(account_id);
DeleteTokenFetcher(token_fetcher);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void DiceResponseHandler::OnTokenExchangeSuccess(
DiceTokenFetcher* token_fetcher,
const std::string& refresh_token,
bool is_under_advanced_protection) {
const std::string& email = token_fetcher->email();
const std::string& gaia_id = token_fetcher->gaia_id();
if (!CanGetTokenForAccount(gaia_id, email))
return;
VLOG(1) << "[Dice] OAuth success for email " << email;
bool should_enable_sync = token_fetcher->should_enable_sync();
std::string account_id =
account_tracker_service_->SeedAccountInfo(gaia_id, email);
account_tracker_service_->SetIsAdvancedProtectionAccount(
account_id, is_under_advanced_protection);
token_service_->UpdateCredentials(
account_id, refresh_token,
signin_metrics::SourceForRefreshTokenOperation::
kDiceResponseHandler_Signin);
about_signin_internals_->OnRefreshTokenReceived(
base::StringPrintf("Successful (%s)", account_id.c_str()));
if (should_enable_sync)
token_fetcher->delegate()->EnableSync(account_id);
DeleteTokenFetcher(token_fetcher);
}
| 172,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Cluster::GetEntry(
const CuePoint& cp,
const CuePoint::TrackPosition& tp) const
{
assert(m_pSegment);
#if 0
LoadBlockEntries();
if (m_entries == NULL)
return NULL;
const long long count = m_entries_count;
if (count <= 0)
return NULL;
const long long tc = cp.GetTimeCode();
if ((tp.m_block > 0) && (tp.m_block <= count))
{
const size_t block = static_cast<size_t>(tp.m_block);
const size_t index = block - 1;
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
const BlockEntry* const* i = m_entries;
const BlockEntry* const* const j = i + count;
while (i != j)
{
#ifdef _DEBUG
const ptrdiff_t idx = i - m_entries;
idx;
#endif
const BlockEntry* const pEntry = *i++;
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
continue;
const long long tc_ = pBlock->GetTimeCode(this);
assert(tc_ >= 0);
if (tc_ < tc)
continue;
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
return NULL;
#else
const long long tc = cp.GetTimeCode();
if (tp.m_block > 0)
{
const long block = static_cast<long>(tp.m_block);
const long index = block - 1;
while (index >= m_entries_count)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //TODO: can this happen?
return NULL;
if (status > 0) //nothing remains to be parsed
return NULL;
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
long index = 0;
for (;;)
{
if (index >= m_entries_count)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //TODO: can this happen?
return NULL;
if (status > 0) //nothing remains to be parsed
return NULL;
assert(m_entries);
assert(index < m_entries_count);
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
{
++index;
continue;
}
const long long tc_ = pBlock->GetTimeCode(this);
if (tc_ < tc)
{
++index;
continue;
}
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
#endif
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Cluster::GetEntry(
const BlockEntry* Cluster::GetEntry(const CuePoint& cp,
const CuePoint::TrackPosition& tp) const {
assert(m_pSegment);
#if 0
LoadBlockEntries();
if (m_entries == NULL)
return NULL;
const long long count = m_entries_count;
if (count <= 0)
return NULL;
const long long tc = cp.GetTimeCode();
if ((tp.m_block > 0) && (tp.m_block <= count))
{
const size_t block = static_cast<size_t>(tp.m_block);
const size_t index = block - 1;
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
const BlockEntry* const* i = m_entries;
const BlockEntry* const* const j = i + count;
while (i != j)
{
#ifdef _DEBUG
const ptrdiff_t idx = i - m_entries;
idx;
#endif
const BlockEntry* const pEntry = *i++;
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
continue;
const long long tc_ = pBlock->GetTimeCode(this);
assert(tc_ >= 0);
if (tc_ < tc)
continue;
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
return NULL;
#else
const long long tc = cp.GetTimeCode();
if (tp.m_block > 0) {
const long block = static_cast<long>(tp.m_block);
const long index = block - 1;
while (index >= m_entries_count) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) // TODO: can this happen?
return NULL;
if (status > 0) // nothing remains to be parsed
return NULL;
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc)) {
return pEntry;
}
}
long index = 0;
for (;;) {
if (index >= m_entries_count) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) // TODO: can this happen?
return NULL;
if (status > 0) // nothing remains to be parsed
return NULL;
assert(m_entries);
assert(index < m_entries_count);
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track) {
++index;
continue;
}
const long long tc_ = pBlock->GetTimeCode(this);
if (tc_ < tc) {
++index;
continue;
}
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) // audio
return pEntry;
if (type != 1) // not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
#endif
}
| 174,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
Commit Message: KVM: x86: Reload pit counters for all channels when restoring state
Currently if userspace restores the pit counters with a count of 0
on channels 1 or 2 and the guest attempts to read the count on those
channels, then KVM will perform a mod of 0 and crash. This will ensure
that 0 values are converted to 65536 as per the spec.
This is CVE-2015-7513.
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: | static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int start = 0;
int i;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
for (i = 0; i < 3; i++)
kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
| 167,561 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
unsigned x, y;
AVFilterContext *ctx = inlink->dst;
VignetteContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
if (s->eval_mode == EVAL_MODE_FRAME)
update_context(s, inlink, in);
if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) {
uint8_t *dst = out->data[0];
const uint8_t *src = in ->data[0];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[0];
const int src_linesize = in ->linesize[0];
const int fmap_linesize = s->fmap_linesize;
for (y = 0; y < inlink->h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) {
const float f = fmap[x];
dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s));
dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s));
dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s));
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize;
}
} else {
int plane;
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
uint8_t *dst = out->data[plane];
const uint8_t *src = in ->data[plane];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[plane];
const int src_linesize = in ->linesize[plane];
const int fmap_linesize = s->fmap_linesize;
const int chroma = plane == 1 || plane == 2;
const int hsub = chroma ? s->desc->log2_chroma_w : 0;
const int vsub = chroma ? s->desc->log2_chroma_h : 0;
const int w = FF_CEIL_RSHIFT(inlink->w, hsub);
const int h = FF_CEIL_RSHIFT(inlink->h, vsub);
for (y = 0; y < h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < w; x++) {
const double dv = get_dither_value(s);
if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv);
else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv);
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize << vsub;
}
}
}
return ff_filter_frame(outlink, out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
unsigned x, y;
AVFilterContext *ctx = inlink->dst;
VignetteContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
if (s->eval_mode == EVAL_MODE_FRAME)
update_context(s, inlink, in);
if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) {
uint8_t *dst = out->data[0];
const uint8_t *src = in ->data[0];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[0];
const int src_linesize = in ->linesize[0];
const int fmap_linesize = s->fmap_linesize;
for (y = 0; y < inlink->h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) {
const float f = fmap[x];
dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s));
dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s));
dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s));
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize;
}
} else {
int plane;
for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) {
uint8_t *dst = out->data[plane];
const uint8_t *src = in ->data[plane];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[plane];
const int src_linesize = in ->linesize[plane];
const int fmap_linesize = s->fmap_linesize;
const int chroma = plane == 1 || plane == 2;
const int hsub = chroma ? s->desc->log2_chroma_w : 0;
const int vsub = chroma ? s->desc->log2_chroma_h : 0;
const int w = FF_CEIL_RSHIFT(inlink->w, hsub);
const int h = FF_CEIL_RSHIFT(inlink->h, vsub);
for (y = 0; y < h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < w; x++) {
const double dv = get_dither_value(s);
if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv);
else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv);
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize << vsub;
}
}
}
return ff_filter_frame(outlink, out);
}
| 166,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: __imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax)
{
ImlibUpdate *nu = NULL, *uu;
struct _tile *t;
int tw, th, x, y, i;
int *gaps = NULL;
/* if theres no rects to process.. return NULL */
if (!u)
return NULL;
tw = w >> TB;
if (w & TM)
tw++;
th = h >> TB;
if (h & TM)
th++;
t = malloc(tw * th * sizeof(struct _tile));
/* fill in tiles to be all not used */
for (i = 0, y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
t[i++].used = T_UNUSED;
}
/* fill in all tiles */
for (uu = u; uu; uu = uu->next)
{
CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h);
for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++)
{
for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++)
T(x, y).used = T_USED;
}
}
/* scan each line - if > hgapmax gaps between tiles, then fill smallest */
gaps = malloc(tw * sizeof(int));
for (y = 0; y < th; y++)
{
int hgaps = 0, start = -1, min;
char have = 1, gap = 0;
for (x = 0; x < tw; x++)
gaps[x] = 0;
for (x = 0; x < tw; x++)
{
if ((have) && (T(x, y).used == T_UNUSED))
{
start = x;
gap = 1;
have = 0;
}
else if ((!have) && (gap) && (T(x, y).used & T_USED))
{
gap = 0;
hgaps++;
have = 1;
gaps[start] = x - start;
}
else if (T(x, y).used & T_USED)
have = 1;
}
while (hgaps > hgapmax)
{
start = -1;
min = tw;
for (x = 0; x < tw; x++)
{
if ((gaps[x] > 0) && (gaps[x] < min))
{
start = x;
min = gaps[x];
}
}
if (start >= 0)
{
gaps[start] = 0;
for (x = start;
T(x, y).used == T_UNUSED; T(x++, y).used = T_USED);
hgaps--;
}
}
}
free(gaps);
/* coalesce tiles into larger blocks and make new rect list */
for (y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
{
if (T(x, y).used & T_USED)
{
int xx, yy, ww, hh, ok, xww;
for (xx = x + 1, ww = 1;
(T(xx, y).used & T_USED) && (xx < tw); xx++, ww++);
xww = x + ww;
for (yy = y + 1, hh = 1, ok = 1;
(yy < th) && (ok); yy++, hh++)
{
for (xx = x; xx < xww; xx++)
{
if (!(T(xx, yy).used & T_USED))
{
ok = 0;
hh--;
break;
}
}
}
for (yy = y; yy < (y + hh); yy++)
{
for (xx = x; xx < xww; xx++)
T(xx, yy).used = T_UNUSED;
}
nu = __imlib_AddUpdate(nu, (x << TB), (y << TB),
(ww << TB), (hh << TB));
}
}
}
free(t);
__imlib_FreeUpdates(u);
return nu;
}
Commit Message:
CWE ID: CWE-119 | __imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax)
{
ImlibUpdate *nu = NULL, *uu;
struct _tile *t;
int tw, th, x, y, i;
int *gaps = NULL;
/* if theres no rects to process.. return NULL */
if (!u)
return NULL;
tw = w >> TB;
if (w & TM)
tw++;
th = h >> TB;
if (h & TM)
th++;
t = malloc(tw * th * sizeof(struct _tile));
/* fill in tiles to be all not used */
for (i = 0, y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
t[i++].used = T_UNUSED;
}
/* fill in all tiles */
for (uu = u; uu; uu = uu->next)
{
CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h);
for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++)
{
for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++)
T(x, y).used = T_USED;
}
}
/* scan each line - if > hgapmax gaps between tiles, then fill smallest */
gaps = malloc(tw * sizeof(int));
for (y = 0; y < th; y++)
{
int hgaps = 0, start = -1, min;
char have = 1, gap = 0;
for (x = 0; x < tw; x++)
gaps[x] = 0;
for (x = 0; x < tw; x++)
{
if ((have) && (T(x, y).used == T_UNUSED))
{
start = x;
gap = 1;
have = 0;
}
else if ((!have) && (gap) && (T(x, y).used & T_USED))
{
gap = 0;
hgaps++;
have = 1;
gaps[start] = x - start;
}
else if (T(x, y).used & T_USED)
have = 1;
}
while (hgaps > hgapmax)
{
start = -1;
min = tw;
for (x = 0; x < tw; x++)
{
if ((gaps[x] > 0) && (gaps[x] < min))
{
start = x;
min = gaps[x];
}
}
if (start >= 0)
{
gaps[start] = 0;
for (x = start;
T(x, y).used == T_UNUSED; T(x++, y).used = T_USED);
hgaps--;
}
}
}
free(gaps);
/* coalesce tiles into larger blocks and make new rect list */
for (y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
{
if (T(x, y).used & T_USED)
{
int xx, yy, ww, hh, ok, xww;
for (xx = x + 1, ww = 1;
(xx < tw) && (T(xx, y).used & T_USED); xx++, ww++);
xww = x + ww;
for (yy = y + 1, hh = 1, ok = 1;
(yy < th) && (ok); yy++, hh++)
{
for (xx = x; xx < xww; xx++)
{
if (!(T(xx, yy).used & T_USED))
{
ok = 0;
hh--;
break;
}
}
}
for (yy = y; yy < (y + hh); yy++)
{
for (xx = x; xx < xww; xx++)
T(xx, yy).used = T_UNUSED;
}
nu = __imlib_AddUpdate(nu, (x << TB), (y << TB),
(ww << TB), (hh << TB));
}
}
}
free(t);
__imlib_FreeUpdates(u);
return nu;
}
| 165,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, *header;
size_t cb1_len, cb2_len, alloc_len;
unsigned char *cb1, *cb2;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = json_array_string(val, 5);
nbit = json_array_string(val, 6);
ntime = json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (prev_hash)
free(prev_hash);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
if (bbversion)
free(bbversion);
if (nbit)
free(nbit);
if (ntime)
free(ntime);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
free(pool->swork.prev_hash);
free(pool->swork.bbversion);
free(pool->swork.nbit);
free(pool->swork.ntime);
pool->swork.job_id = job_id;
pool->swork.prev_hash = prev_hash;
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
pool->swork.bbversion = bbversion;
pool->swork.nbit = nbit;
pool->swork.ntime = ntime;
pool->swork.clean = clean;
alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->swork.merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin,
sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++) {
char *merkle = json_array_string(arr, i);
pool->swork.merkle_bin[i] = (unsigned char *)malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
}
}
pool->swork.merkles = merkles;
if (clean)
pool->nonce2 = 0;
pool->merkle_offset = strlen(pool->swork.bbversion) +
strlen(pool->swork.prev_hash);
pool->swork.header_len = pool->merkle_offset +
/* merkle_hash */ 32 +
strlen(pool->swork.ntime) +
strlen(pool->swork.nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
pool->merkle_offset /= 2;
pool->swork.header_len = pool->swork.header_len * 2 + 1;
align_len(&pool->swork.header_len);
header = (char *)alloca(pool->swork.header_len);
snprintf(header, pool->swork.header_len,
"%s%s%s%s%s%s%s",
pool->swork.bbversion,
pool->swork.prev_hash,
blank_merkel,
pool->swork.ntime,
pool->swork.nbit,
"00000000", /* nonce */
workpadding);
if (unlikely(!hex2bin(pool->header_bin, header, 128)))
quit(1, "Failed to convert header to header_bin in parse_notify");
cb1 = (unsigned char *)calloc(cb1_len, 1);
if (unlikely(!cb1))
quithere(1, "Failed to calloc cb1 in parse_notify");
hex2bin(cb1, coinbase1, cb1_len);
cb2 = (unsigned char *)calloc(cb2_len, 1);
if (unlikely(!cb2))
quithere(1, "Failed to calloc cb2 in parse_notify");
hex2bin(cb2, coinbase2, cb2_len);
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = (unsigned char *)calloc(alloc_len, 1);
if (unlikely(!pool->coinbase))
quit(1, "Failed to calloc pool coinbase in parse_notify");
memcpy(pool->coinbase, cb1, cb1_len);
memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
cg_wunlock(&pool->data_lock);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
free(coinbase1);
free(coinbase2);
free(cb1);
free(cb2);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
ret = true;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime.
Might have introduced a memory leak, don't have time to check. :(
Should the other hex2bin()'s be checked?
Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this.
CWE ID: CWE-20 | static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, *header;
size_t cb1_len, cb2_len, alloc_len;
unsigned char *cb1, *cb2;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = json_array_string(val, 5);
nbit = json_array_string(val, 6);
ntime = json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (prev_hash)
free(prev_hash);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
if (bbversion)
free(bbversion);
if (nbit)
free(nbit);
if (ntime)
free(ntime);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
free(pool->swork.prev_hash);
free(pool->swork.bbversion);
free(pool->swork.nbit);
free(pool->swork.ntime);
pool->swork.job_id = job_id;
pool->swork.prev_hash = prev_hash;
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
pool->swork.bbversion = bbversion;
pool->swork.nbit = nbit;
pool->swork.ntime = ntime;
pool->swork.clean = clean;
alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->swork.merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin,
sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++) {
char *merkle = json_array_string(arr, i);
pool->swork.merkle_bin[i] = (unsigned char *)malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
}
}
pool->swork.merkles = merkles;
if (clean)
pool->nonce2 = 0;
pool->merkle_offset = strlen(pool->swork.bbversion) +
strlen(pool->swork.prev_hash);
pool->swork.header_len = pool->merkle_offset +
/* merkle_hash */ 32 +
strlen(pool->swork.ntime) +
strlen(pool->swork.nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
pool->merkle_offset /= 2;
pool->swork.header_len = pool->swork.header_len * 2 + 1;
align_len(&pool->swork.header_len);
header = (char *)alloca(pool->swork.header_len);
snprintf(header, pool->swork.header_len,
"%s%s%s%s%s%s%s",
pool->swork.bbversion,
pool->swork.prev_hash,
blank_merkel,
pool->swork.ntime,
pool->swork.nbit,
"00000000", /* nonce */
workpadding);
if (unlikely(!hex2bin(pool->header_bin, header, 128))) {
applog(LOG_WARNING, "%s: Failed to convert header to header_bin, got %s", __func__, header);
pool_failed(pool);
// TODO: memory leaks? goto out, clean up there?
return false;
}
cb1 = (unsigned char *)calloc(cb1_len, 1);
if (unlikely(!cb1))
quithere(1, "Failed to calloc cb1 in parse_notify");
hex2bin(cb1, coinbase1, cb1_len);
cb2 = (unsigned char *)calloc(cb2_len, 1);
if (unlikely(!cb2))
quithere(1, "Failed to calloc cb2 in parse_notify");
hex2bin(cb2, coinbase2, cb2_len);
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = (unsigned char *)calloc(alloc_len, 1);
if (unlikely(!pool->coinbase))
quit(1, "Failed to calloc pool coinbase in parse_notify");
memcpy(pool->coinbase, cb1, cb1_len);
memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
// NOTE: gap for nonce2, filled at work generation time
memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
cg_wunlock(&pool->data_lock);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
free(coinbase1);
free(coinbase2);
free(cb1);
free(cb2);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
ret = true;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
| 166,303 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintingMessageFilter::OnCheckForCancel(const std::string& preview_ui_addr,
int preview_request_id,
bool* cancel) {
PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_addr,
preview_request_id,
cancel);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintingMessageFilter::OnCheckForCancel(const std::string& preview_ui_addr,
void PrintingMessageFilter::OnCheckForCancel(int32 preview_ui_id,
int preview_request_id,
bool* cancel) {
PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_id,
preview_request_id,
cancel);
}
| 170,826 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void setRewriteURLFolder(const char* folder)
{
m_rewriteFolder = folder;
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void setRewriteURLFolder(const char* folder)
| 171,577 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
{
static const char module[] = "NeXTDecode";
unsigned char *bp, *op;
tmsize_t cc;
uint8* row;
tmsize_t scanline, n;
(void) s;
/*
* Each scanline is assumed to start off as all
* white (we assume a PhotometricInterpretation
* of ``min-is-black'').
*/
for (op = (unsigned char*) buf, cc = occ; cc-- > 0;)
*op++ = 0xff;
bp = (unsigned char *)tif->tif_rawcp;
cc = tif->tif_rawcc;
scanline = tif->tif_scanlinesize;
if (occ % scanline)
{
TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read");
return (0);
}
for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {
n = *bp++, cc--;
switch (n) {
case LITERALROW:
/*
* The entire scanline is given as literal values.
*/
if (cc < scanline)
goto bad;
_TIFFmemcpy(row, bp, scanline);
bp += scanline;
cc -= scanline;
break;
case LITERALSPAN: {
tmsize_t off;
/*
* The scanline has a literal span that begins at some
* offset.
*/
if( cc < 4 )
goto bad;
off = (bp[0] * 256) + bp[1];
n = (bp[2] * 256) + bp[3];
if (cc < 4+n || off+n > scanline)
goto bad;
_TIFFmemcpy(row+off, bp+4, n);
bp += 4+n;
cc -= 4+n;
break;
}
default: {
uint32 npixels = 0, grey;
uint32 imagewidth = tif->tif_dir.td_imagewidth;
if( isTiled(tif) )
imagewidth = tif->tif_dir.td_tilewidth;
/*
* The scanline is composed of a sequence of constant
* color ``runs''. We shift into ``run mode'' and
* interpret bytes as codes of the form
* <color><npixels> until we've filled the scanline.
*/
op = row;
for (;;) {
grey = (uint32)((n>>6) & 0x3);
n &= 0x3f;
/*
* Ensure the run does not exceed the scanline
* bounds, potentially resulting in a security
* issue.
*/
while (n-- > 0 && npixels < imagewidth)
SETPIXEL(op, grey);
if (npixels >= imagewidth)
break;
if (cc == 0)
goto bad;
n = *bp++, cc--;
}
break;
}
}
}
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld",
(long) tif->tif_row);
return (0);
}
Commit Message: * libtiff/tif_next.c: fix potential out-of-bound write in NeXTDecode()
triggered by http://lcamtuf.coredump.cx/afl/vulns/libtiff5.tif
(bugzilla #2508)
CWE ID: CWE-119 | NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
{
static const char module[] = "NeXTDecode";
unsigned char *bp, *op;
tmsize_t cc;
uint8* row;
tmsize_t scanline, n;
(void) s;
/*
* Each scanline is assumed to start off as all
* white (we assume a PhotometricInterpretation
* of ``min-is-black'').
*/
for (op = (unsigned char*) buf, cc = occ; cc-- > 0;)
*op++ = 0xff;
bp = (unsigned char *)tif->tif_rawcp;
cc = tif->tif_rawcc;
scanline = tif->tif_scanlinesize;
if (occ % scanline)
{
TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read");
return (0);
}
for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {
n = *bp++, cc--;
switch (n) {
case LITERALROW:
/*
* The entire scanline is given as literal values.
*/
if (cc < scanline)
goto bad;
_TIFFmemcpy(row, bp, scanline);
bp += scanline;
cc -= scanline;
break;
case LITERALSPAN: {
tmsize_t off;
/*
* The scanline has a literal span that begins at some
* offset.
*/
if( cc < 4 )
goto bad;
off = (bp[0] * 256) + bp[1];
n = (bp[2] * 256) + bp[3];
if (cc < 4+n || off+n > scanline)
goto bad;
_TIFFmemcpy(row+off, bp+4, n);
bp += 4+n;
cc -= 4+n;
break;
}
default: {
uint32 npixels = 0, grey;
uint32 imagewidth = tif->tif_dir.td_imagewidth;
if( isTiled(tif) )
imagewidth = tif->tif_dir.td_tilewidth;
tmsize_t op_offset = 0;
/*
* The scanline is composed of a sequence of constant
* color ``runs''. We shift into ``run mode'' and
* interpret bytes as codes of the form
* <color><npixels> until we've filled the scanline.
*/
op = row;
for (;;) {
grey = (uint32)((n>>6) & 0x3);
n &= 0x3f;
/*
* Ensure the run does not exceed the scanline
* bounds, potentially resulting in a security
* issue.
*/
while (n-- > 0 && npixels < imagewidth && op_offset < scanline)
SETPIXEL(op, grey);
if (npixels >= imagewidth)
break;
if (op_offset >= scanline ) {
TIFFErrorExt(tif->tif_clientdata, module, "Invalid data for scanline %ld",
(long) tif->tif_row);
return (0);
}
if (cc == 0)
goto bad;
n = *bp++, cc--;
}
break;
}
}
}
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld",
(long) tif->tif_row);
return (0);
}
| 167,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message: Moved EOF check.
CWE ID: CWE-20 | static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 170,155 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
Commit Message: fix #58 : access to invalid address by reg->dmin value
CWE ID: CWE-125 | forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
| 168,108 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
unsigned long flags;
if (PCM_RUNTIME_CHECK(substream))
return;
runtime = substream->runtime;
snd_pcm_stream_lock_irqsave(substream, flags);
if (!snd_pcm_running(substream) ||
snd_pcm_update_hw_ptr0(substream, 1) < 0)
goto _end;
#ifdef CONFIG_SND_PCM_TIMER
if (substream->timer_running)
snd_timer_interrupt(substream->timer, 1);
#endif
_end:
snd_pcm_stream_unlock_irqrestore(substream, flags);
kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
}
Commit Message: ALSA: pcm : Call kill_fasync() in stream lock
Currently kill_fasync() is called outside the stream lock in
snd_pcm_period_elapsed(). This is potentially racy, since the stream
may get released even during the irq handler is running. Although
snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't
guarantee that the irq handler finishes, thus the kill_fasync() call
outside the stream spin lock may be invoked after the substream is
detached, as recently reported by KASAN.
As a quick workaround, move kill_fasync() call inside the stream
lock. The fasync is rarely used interface, so this shouldn't have a
big impact from the performance POV.
Ideally, we should implement some sync mechanism for the proper finish
of stream and irq handler. But this oneliner should suffice for most
cases, so far.
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416 | void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
unsigned long flags;
if (PCM_RUNTIME_CHECK(substream))
return;
runtime = substream->runtime;
snd_pcm_stream_lock_irqsave(substream, flags);
if (!snd_pcm_running(substream) ||
snd_pcm_update_hw_ptr0(substream, 1) < 0)
goto _end;
#ifdef CONFIG_SND_PCM_TIMER
if (substream->timer_running)
snd_timer_interrupt(substream->timer, 1);
#endif
_end:
kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
snd_pcm_stream_unlock_irqrestore(substream, flags);
}
| 166,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PluginInfoMessageFilter::PluginsLoaded(
const GetPluginInfo_Params& params,
IPC::Message* reply_msg,
const std::vector<WebPluginInfo>& plugins) {
ChromeViewHostMsg_GetPluginInfo_Output output;
scoped_ptr<PluginMetadata> plugin_metadata;
if (context_.FindEnabledPlugin(params.render_view_id, params.url,
params.top_origin_url, params.mime_type,
&output.status, &output.plugin,
&output.actual_mime_type,
&plugin_metadata)) {
context_.DecidePluginStatus(params, output.plugin, plugin_metadata.get(),
&output.status);
}
if (plugin_metadata) {
output.group_identifier = plugin_metadata->identifier();
output.group_name = plugin_metadata->name();
}
context_.GrantAccess(output.status, output.plugin.path);
ChromeViewHostMsg_GetPluginInfo::WriteReplyParams(reply_msg, output);
Send(reply_msg);
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | void PluginInfoMessageFilter::PluginsLoaded(
const GetPluginInfo_Params& params,
IPC::Message* reply_msg,
const std::vector<WebPluginInfo>& plugins) {
ChromeViewHostMsg_GetPluginInfo_Output output;
scoped_ptr<PluginMetadata> plugin_metadata;
if (context_.FindEnabledPlugin(params.render_view_id, params.url,
params.top_origin_url, params.mime_type,
&output.status, &output.plugin,
&output.actual_mime_type,
&plugin_metadata)) {
context_.DecidePluginStatus(params, output.plugin, plugin_metadata.get(),
&output.status);
}
if (plugin_metadata) {
output.group_identifier = plugin_metadata->identifier();
output.group_name = plugin_metadata->name();
}
context_.MaybeGrantAccess(output.status, output.plugin.path);
ChromeViewHostMsg_GetPluginInfo::WriteReplyParams(reply_msg, output);
Send(reply_msg);
}
| 171,473 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_get_mmx_rowbytes_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0L: 0L);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_mmx_rowbytes_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
PNG_UNUSED(png_ptr)
return 0L;
}
| 172,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
hdrlen += printer(ndo, h, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
Commit Message: CVE-2017-13007/PKTAP: Pass a properly updated struct pcap_pkthdr to the sub-dissector.
The sub-dissector expects that the length and captured length will
reflect the actual remaining data in the packet, not the raw amount
including the PKTAP header; pass an updated header, just as we do for
PPI.
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 | pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
struct pcap_pkthdr nhdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
nhdr = *h;
nhdr.caplen = caplen;
nhdr.len = length;
hdrlen += printer(ndo, &nhdr, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
| 167,888 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PageRequestSummary::UpdateOrAddToOrigins(
const content::mojom::ResourceLoadInfo& resource_load_info) {
for (const auto& redirect_info : resource_load_info.redirect_info_chain)
UpdateOrAddToOrigins(redirect_info->url, redirect_info->network_info);
UpdateOrAddToOrigins(resource_load_info.url, resource_load_info.network_info);
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | void PageRequestSummary::UpdateOrAddToOrigins(
const content::mojom::ResourceLoadInfo& resource_load_info) {
for (const auto& redirect_info : resource_load_info.redirect_info_chain) {
UpdateOrAddToOrigins(url::Origin::Create(redirect_info->url),
redirect_info->network_info);
}
UpdateOrAddToOrigins(url::Origin::Create(resource_load_info.url),
resource_load_info.network_info);
}
| 172,367 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
int valid_eku;
const struct certauth_req_opts *req_opts = opts;
*authinds_out = NULL;
/* Verify the client EKU. */
ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx,
&valid_eku);
if (ret)
return ret;
if (!valid_eku) {
TRACE_PKINIT_SERVER_EKU_REJECT(context);
return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
}
return 0;
}
Commit Message: Fix certauth built-in module returns
The PKINIT certauth eku module should never authoritatively authorize
a certificate, because an extended key usage does not establish a
relationship between the certificate and any specific user; it only
establishes that the certificate was created for PKINIT client
authentication. Therefore, pkinit_eku_authorize() should return
KRB5_PLUGIN_NO_HANDLE on success, not 0.
The certauth san module should pass if it does not find any SANs of
the types it can match against; the presence of other types of SANs
should not cause it to explicitly deny a certificate. Check for an
empty result from crypto_retrieve_cert_sans() in verify_client_san(),
instead of returning ENOENT from crypto_retrieve_cert_sans() when
there are no SANs at all.
ticket: 8561
CWE ID: CWE-287 | pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
int valid_eku;
const struct certauth_req_opts *req_opts = opts;
*authinds_out = NULL;
/* Verify the client EKU. */
ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx,
&valid_eku);
if (ret)
return ret;
if (!valid_eku) {
TRACE_PKINIT_SERVER_EKU_REJECT(context);
return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
}
return KRB5_PLUGIN_NO_HANDLE;
}
| 170,174 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int key_notify_sa_flush(const struct km_event *c)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
hdr->sadb_msg_type = SADB_FLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
Commit Message: af_key: fix info leaks in notify messages
key_notify_sa_flush() and key_notify_policy_flush() miss to initialize
the sadb_msg_reserved member of the broadcasted message and thereby
leak 2 bytes of heap memory to listeners. Fix that.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Cc: "David S. Miller" <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int key_notify_sa_flush(const struct km_event *c)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
hdr->sadb_msg_type = SADB_FLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
hdr->sadb_msg_reserved = 0;
pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
| 166,075 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::OnPairError(
const ConnectErrorCallback& error_callback,
const std::string& error_name,
const std::string& error_message) {
if (--num_connecting_calls_ == 0)
adapter_->NotifyDeviceChanged(this);
DCHECK(num_connecting_calls_ >= 0);
LOG(WARNING) << object_path_.value() << ": Failed to pair device: "
<< error_name << ": " << error_message;
VLOG(1) << object_path_.value() << ": " << num_connecting_calls_
<< " still in progress";
UnregisterAgent();
ConnectErrorCode error_code = ERROR_UNKNOWN;
if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) {
error_code = ERROR_FAILED;
} else if (error_name == bluetooth_device::kErrorFailed) {
error_code = ERROR_FAILED;
} else if (error_name == bluetooth_device::kErrorAuthenticationFailed) {
error_code = ERROR_AUTH_FAILED;
} else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) {
error_code = ERROR_AUTH_CANCELED;
} else if (error_name == bluetooth_device::kErrorAuthenticationRejected) {
error_code = ERROR_AUTH_REJECTED;
} else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) {
error_code = ERROR_AUTH_TIMEOUT;
}
RecordPairingResult(error_code);
error_callback.Run(error_code);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::OnPairError(
const ConnectErrorCallback& error_callback,
const std::string& error_name,
const std::string& error_message) {
if (--num_connecting_calls_ == 0)
adapter_->NotifyDeviceChanged(this);
DCHECK(num_connecting_calls_ >= 0);
LOG(WARNING) << object_path_.value() << ": Failed to pair device: "
<< error_name << ": " << error_message;
VLOG(1) << object_path_.value() << ": " << num_connecting_calls_
<< " still in progress";
pairing_context_.reset();
ConnectErrorCode error_code = ERROR_UNKNOWN;
if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) {
error_code = ERROR_FAILED;
} else if (error_name == bluetooth_device::kErrorFailed) {
error_code = ERROR_FAILED;
} else if (error_name == bluetooth_device::kErrorAuthenticationFailed) {
error_code = ERROR_AUTH_FAILED;
} else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) {
error_code = ERROR_AUTH_CANCELED;
} else if (error_name == bluetooth_device::kErrorAuthenticationRejected) {
error_code = ERROR_AUTH_REJECTED;
} else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) {
error_code = ERROR_AUTH_TIMEOUT;
}
RecordPairingResult(error_code);
error_callback.Run(error_code);
}
| 171,228 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
{
int i,n=0,len,nid, first, use_bn;
BIGNUM *bl;
unsigned long l;
const unsigned char *p;
char tbuf[DECIMAL_SIZE(i)+DECIMAL_SIZE(l)+2];
if ((a == NULL) || (a->data == NULL)) {
buf[0]='\0';
return(0);
}
if (!no_name && (nid=OBJ_obj2nid(a)) != NID_undef)
{
s=OBJ_nid2ln(nid);
if (s == NULL)
s=OBJ_nid2sn(nid);
if (s)
{
if (buf)
BUF_strlcpy(buf,s,buf_len);
n=strlen(s);
return n;
}
}
len=a->length;
p=a->data;
first = 1;
bl = NULL;
while (len > 0)
{
l=0;
use_bn = 0;
for (;;)
{
unsigned char c = *p++;
len--;
if ((len == 0) && (c & 0x80))
goto err;
if (use_bn)
{
if (!BN_add_word(bl, c & 0x7f))
goto err;
}
else
l |= c & 0x7f;
if (!(c & 0x80))
break;
if (!use_bn && (l > (ULONG_MAX >> 7L)))
{
if (!bl && !(bl = BN_new()))
goto err;
if (!BN_set_word(bl, l))
goto err;
use_bn = 1;
}
if (use_bn)
{
if (!BN_lshift(bl, bl, 7))
goto err;
}
else
l<<=7L;
}
if (first)
{
first = 0;
if (l >= 80)
{
i = 2;
if (use_bn)
{
if (!BN_sub_word(bl, 80))
goto err;
}
else
l -= 80;
}
else
{
i=(int)(l/40);
i=(int)(l/40);
l-=(long)(i*40);
}
if (buf && (buf_len > 0))
{
*buf++ = i + '0';
buf_len--;
}
n++;
if (use_bn)
{
char *bndec;
bndec = BN_bn2dec(bl);
if (!bndec)
goto err;
i = strlen(bndec);
if (buf)
i = strlen(bndec);
if (buf)
{
if (buf_len > 0)
{
*buf++ = '.';
buf_len--;
}
BUF_strlcpy(buf,bndec,buf_len);
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n++;
n += i;
OPENSSL_free(bndec);
}
else
{
BIO_snprintf(tbuf,sizeof tbuf,".%lu",l);
i=strlen(tbuf);
if (buf && (buf_len > 0))
{
BUF_strlcpy(buf,tbuf,buf_len);
if (i > buf_len)
{
buf += buf_len;
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n+=i;
l=0;
}
}
if (bl)
BN_free(bl);
return n;
err:
if (bl)
BN_free(bl);
return -1;
}
Commit Message:
CWE ID: CWE-200 | int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
{
int i,n=0,len,nid, first, use_bn;
BIGNUM *bl;
unsigned long l;
const unsigned char *p;
char tbuf[DECIMAL_SIZE(i)+DECIMAL_SIZE(l)+2];
/* Ensure that, at every state, |buf| is NUL-terminated. */
if (buf && buf_len > 0)
buf[0] = '\0';
if ((a == NULL) || (a->data == NULL))
return(0);
if (!no_name && (nid=OBJ_obj2nid(a)) != NID_undef)
{
s=OBJ_nid2ln(nid);
if (s == NULL)
s=OBJ_nid2sn(nid);
if (s)
{
if (buf)
BUF_strlcpy(buf,s,buf_len);
n=strlen(s);
return n;
}
}
len=a->length;
p=a->data;
first = 1;
bl = NULL;
while (len > 0)
{
l=0;
use_bn = 0;
for (;;)
{
unsigned char c = *p++;
len--;
if ((len == 0) && (c & 0x80))
goto err;
if (use_bn)
{
if (!BN_add_word(bl, c & 0x7f))
goto err;
}
else
l |= c & 0x7f;
if (!(c & 0x80))
break;
if (!use_bn && (l > (ULONG_MAX >> 7L)))
{
if (!bl && !(bl = BN_new()))
goto err;
if (!BN_set_word(bl, l))
goto err;
use_bn = 1;
}
if (use_bn)
{
if (!BN_lshift(bl, bl, 7))
goto err;
}
else
l<<=7L;
}
if (first)
{
first = 0;
if (l >= 80)
{
i = 2;
if (use_bn)
{
if (!BN_sub_word(bl, 80))
goto err;
}
else
l -= 80;
}
else
{
i=(int)(l/40);
i=(int)(l/40);
l-=(long)(i*40);
}
if (buf && (buf_len > 1))
{
*buf++ = i + '0';
*buf = '\0';
buf_len--;
}
n++;
if (use_bn)
{
char *bndec;
bndec = BN_bn2dec(bl);
if (!bndec)
goto err;
i = strlen(bndec);
if (buf)
i = strlen(bndec);
if (buf)
{
if (buf_len > 1)
{
*buf++ = '.';
*buf = '\0';
buf_len--;
}
BUF_strlcpy(buf,bndec,buf_len);
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n++;
n += i;
OPENSSL_free(bndec);
}
else
{
BIO_snprintf(tbuf,sizeof tbuf,".%lu",l);
i=strlen(tbuf);
if (buf && (buf_len > 0))
{
BUF_strlcpy(buf,tbuf,buf_len);
if (i > buf_len)
{
buf += buf_len;
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n+=i;
l=0;
}
}
if (bl)
BN_free(bl);
return n;
err:
if (bl)
BN_free(bl);
return -1;
}
| 165,176 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: txid_snapshot_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
TxidSnapshot *snap;
txid last = 0;
int nxip;
int i;
int avail;
int expect;
txid xmin,
xmax;
/*
* load nxip and check for nonsense.
*
* (nxip > avail) check is against int overflows in 'expect'.
*/
nxip = pq_getmsgint(buf, 4);
avail = buf->len - buf->cursor;
expect = 8 + 8 + nxip * 8;
if (nxip < 0 || nxip > avail || expect > avail)
goto bad_format;
xmin = pq_getmsgint64(buf);
xmax = pq_getmsgint64(buf);
if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID)
goto bad_format;
snap = palloc(TXID_SNAPSHOT_SIZE(nxip));
snap->xmin = xmin;
snap->xmax = xmax;
snap->nxip = nxip;
SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip));
for (i = 0; i < nxip; i++)
{
txid cur = pq_getmsgint64(buf);
if (cur <= last || cur < xmin || cur >= xmax)
goto bad_format;
snap->xip[i] = cur;
last = cur;
}
PG_RETURN_POINTER(snap);
bad_format:
elog(ERROR, "invalid snapshot data");
return (Datum) NULL;
}
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 | txid_snapshot_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
TxidSnapshot *snap;
txid last = 0;
int nxip;
int i;
txid xmin,
xmax;
/* load and validate nxip */
nxip = pq_getmsgint(buf, 4);
if (nxip < 0 || nxip > TXID_SNAPSHOT_MAX_NXIP)
goto bad_format;
xmin = pq_getmsgint64(buf);
xmax = pq_getmsgint64(buf);
if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID)
goto bad_format;
snap = palloc(TXID_SNAPSHOT_SIZE(nxip));
snap->xmin = xmin;
snap->xmax = xmax;
snap->nxip = nxip;
SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip));
for (i = 0; i < nxip; i++)
{
txid cur = pq_getmsgint64(buf);
if (cur <= last || cur < xmin || cur >= xmax)
goto bad_format;
snap->xip[i] = cur;
last = cur;
}
PG_RETURN_POINTER(snap);
bad_format:
elog(ERROR, "invalid snapshot data");
return (Datum) NULL;
}
| 166,416 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GfxIndexedColorSpace::getRGBLine(Guchar *in, unsigned int *out, int length) {
Guchar *line;
int i, j, n;
n = base->getNComps();
line = (Guchar *) gmalloc (length * n);
for (i = 0; i < length; i++)
for (j = 0; j < n; j++)
line[i * n + j] = lookup[in[i] * n + j];
base->getRGBLine(line, out, length);
gfree (line);
}
Commit Message:
CWE ID: CWE-189 | void GfxIndexedColorSpace::getRGBLine(Guchar *in, unsigned int *out, int length) {
Guchar *line;
int i, j, n;
n = base->getNComps();
line = (Guchar *) gmallocn (length, n);
for (i = 0; i < length; i++)
for (j = 0; j < n; j++)
line[i * n + j] = lookup[in[i] * n + j];
base->getRGBLine(line, out, length);
gfree (line);
}
| 164,610 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
AliasInfo *alias;
unsigned i, num_key_aliases;
struct xkb_key_alias *key_aliases;
/*
* Do some sanity checking on the aliases. We can't do it before
* because keys and their aliases may be added out-of-order.
*/
num_key_aliases = 0;
darray_foreach(alias, info->aliases) {
/* Check that ->real is a key. */
if (!XkbKeyByName(keymap, alias->real, false)) {
log_vrb(info->ctx, 5,
"Attempt to alias %s to non-existent key %s; Ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
/* Check that ->alias is not a key. */
if (XkbKeyByName(keymap, alias->alias, false)) {
log_vrb(info->ctx, 5,
"Attempt to create alias with the name of a real key; "
"Alias \"%s = %s\" ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
num_key_aliases++;
}
/* Copy key aliases. */
key_aliases = NULL;
if (num_key_aliases > 0) {
key_aliases = calloc(num_key_aliases, sizeof(*key_aliases));
if (!key_aliases)
return false;
}
i = 0;
darray_foreach(alias, info->aliases) {
if (alias->real != XKB_ATOM_NONE) {
key_aliases[i].alias = alias->alias;
key_aliases[i].real = alias->real;
i++;
}
}
keymap->num_key_aliases = num_key_aliases;
keymap->key_aliases = key_aliases;
return true;
}
Commit Message: keycodes: don't try to copy zero key aliases
Move the aliases copy to within the (num_key_aliases > 0) block.
Passing info->aliases into this fuction with invalid aliases will
cause log messages but num_key_aliases stays on 0. The key_aliases array
is never allocated and remains NULL. We then loop through the aliases, causing
a null-pointer dereference.
Signed-off-by: Peter Hutterer <[email protected]>
CWE ID: CWE-476 | CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
AliasInfo *alias;
unsigned i, num_key_aliases;
struct xkb_key_alias *key_aliases;
/*
* Do some sanity checking on the aliases. We can't do it before
* because keys and their aliases may be added out-of-order.
*/
num_key_aliases = 0;
darray_foreach(alias, info->aliases) {
/* Check that ->real is a key. */
if (!XkbKeyByName(keymap, alias->real, false)) {
log_vrb(info->ctx, 5,
"Attempt to alias %s to non-existent key %s; Ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
/* Check that ->alias is not a key. */
if (XkbKeyByName(keymap, alias->alias, false)) {
log_vrb(info->ctx, 5,
"Attempt to create alias with the name of a real key; "
"Alias \"%s = %s\" ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
num_key_aliases++;
}
/* Copy key aliases. */
key_aliases = NULL;
if (num_key_aliases > 0) {
key_aliases = calloc(num_key_aliases, sizeof(*key_aliases));
if (!key_aliases)
return false;
i = 0;
darray_foreach(alias, info->aliases) {
if (alias->real != XKB_ATOM_NONE) {
key_aliases[i].alias = alias->alias;
key_aliases[i].real = alias->real;
i++;
}
}
}
keymap->num_key_aliases = num_key_aliases;
keymap->key_aliases = key_aliases;
return true;
}
| 169,092 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagesetstyle)
{
zval *IM, *styles;
gdImagePtr im;
int * stylearr;
int index;
HashPosition pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
/* copy the style values in the stylearr */
stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0);
zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos);
for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) {
zval ** item;
if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) {
break;
}
convert_to_long_ex(item);
stylearr[index++] = Z_LVAL_PP(item);
}
gdImageSetStyle(im, stylearr, index);
efree(stylearr);
RETURN_TRUE;
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189 | PHP_FUNCTION(imagesetstyle)
{
zval *IM, *styles;
gdImagePtr im;
int * stylearr;
int index;
HashPosition pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
/* copy the style values in the stylearr */
stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0);
zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos);
for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) {
zval ** item;
if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) {
break;
}
if (Z_TYPE_PP(item) != IS_LONG) {
zval lval;
lval = **item;
zval_copy_ctor(&lval);
convert_to_long(&lval);
stylearr[index++] = Z_LVAL(lval);
} else {
stylearr[index++] = Z_LVAL_PP(item);
}
}
gdImageSetStyle(im, stylearr, index);
efree(stylearr);
RETURN_TRUE;
}
| 166,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::ContentEncryption::~ContentEncryption() {
delete [] key_id;
delete [] signature;
delete [] sig_key_id;
}
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 | ContentEncoding::ContentEncryption::~ContentEncryption() {
delete[] key_id;
delete[] signature;
delete[] sig_key_id;
}
| 174,461 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
Commit Message:
CWE ID: | int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
if (sanitize_paths) {
sanitize_path(buf, buf, "", 0, SP_DEFAULT);
len = strlen(buf);
}
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
| 164,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int fill_thread_core_info(struct elf_thread_core_info *t,
const struct user_regset_view *view,
long signr, size_t *total)
{
unsigned int i;
/*
* NT_PRSTATUS is the one special case, because the regset data
* goes into the pr_reg field inside the note contents, rather
* than being the whole note contents. We fill the reset in here.
* We assume that regset 0 is NT_PRSTATUS.
*/
fill_prstatus(&t->prstatus, t->task, signr);
(void) view->regsets[0].get(t->task, &view->regsets[0],
0, sizeof(t->prstatus.pr_reg),
&t->prstatus.pr_reg, NULL);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
sizeof(t->prstatus), &t->prstatus);
*total += notesize(&t->notes[0]);
do_thread_regset_writeback(t->task, &view->regsets[0]);
/*
* Each other regset might generate a note too. For each regset
* that has no core_note_type or is inactive, we leave t->notes[i]
* all zero and we'll know to skip writing it later.
*/
for (i = 1; i < view->n; ++i) {
const struct user_regset *regset = &view->regsets[i];
do_thread_regset_writeback(t->task, regset);
if (regset->core_note_type &&
(!regset->active || regset->active(t->task, regset))) {
int ret;
size_t size = regset->n * regset->size;
void *data = kmalloc(size, GFP_KERNEL);
if (unlikely(!data))
return 0;
ret = regset->get(t->task, regset,
0, size, data, NULL);
if (unlikely(ret))
kfree(data);
else {
if (regset->core_note_type != NT_PRFPREG)
fill_note(&t->notes[i], "LINUX",
regset->core_note_type,
size, data);
else {
t->prstatus.pr_fpvalid = 1;
fill_note(&t->notes[i], "CORE",
NT_PRFPREG, size, data);
}
*total += notesize(&t->notes[i]);
}
}
}
return 1;
}
Commit Message: regset: Prevent null pointer reference on readonly regsets
The regset common infrastructure assumed that regsets would always
have .get and .set methods, but not necessarily .active methods.
Unfortunately people have since written regsets without .set methods.
Rather than putting in stub functions everywhere, handle regsets with
null .get or .set methods explicitly.
Signed-off-by: H. Peter Anvin <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Acked-by: Roland McGrath <[email protected]>
Cc: <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static int fill_thread_core_info(struct elf_thread_core_info *t,
const struct user_regset_view *view,
long signr, size_t *total)
{
unsigned int i;
/*
* NT_PRSTATUS is the one special case, because the regset data
* goes into the pr_reg field inside the note contents, rather
* than being the whole note contents. We fill the reset in here.
* We assume that regset 0 is NT_PRSTATUS.
*/
fill_prstatus(&t->prstatus, t->task, signr);
(void) view->regsets[0].get(t->task, &view->regsets[0],
0, sizeof(t->prstatus.pr_reg),
&t->prstatus.pr_reg, NULL);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
sizeof(t->prstatus), &t->prstatus);
*total += notesize(&t->notes[0]);
do_thread_regset_writeback(t->task, &view->regsets[0]);
/*
* Each other regset might generate a note too. For each regset
* that has no core_note_type or is inactive, we leave t->notes[i]
* all zero and we'll know to skip writing it later.
*/
for (i = 1; i < view->n; ++i) {
const struct user_regset *regset = &view->regsets[i];
do_thread_regset_writeback(t->task, regset);
if (regset->core_note_type && regset->get &&
(!regset->active || regset->active(t->task, regset))) {
int ret;
size_t size = regset->n * regset->size;
void *data = kmalloc(size, GFP_KERNEL);
if (unlikely(!data))
return 0;
ret = regset->get(t->task, regset,
0, size, data, NULL);
if (unlikely(ret))
kfree(data);
else {
if (regset->core_note_type != NT_PRFPREG)
fill_note(&t->notes[i], "LINUX",
regset->core_note_type,
size, data);
else {
t->prstatus.pr_fpvalid = 1;
fill_note(&t->notes[i], "CORE",
NT_PRFPREG, size, data);
}
*total += notesize(&t->notes[i]);
}
}
}
return 1;
}
| 165,644 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseEntityRef(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr ent = NULL;
GROW;
if (RAW != '&')
return(NULL);
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseEntityRef: no name\n");
return(NULL);
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return(NULL);
}
NEXT;
/*
* Predefined entites override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL)
return(ent);
}
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
(ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
(ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
if ((ctxt->inSubset == 0) &&
(ctxt->sax != NULL) &&
(ctxt->sax->reference != NULL)) {
ctxt->sax->reference(ctxt->userData, name);
}
}
ctxt->valid = 0;
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) && (ent->content != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n", name);
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
return(ent);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseEntityRef(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr ent = NULL;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (RAW != '&')
return(NULL);
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseEntityRef: no name\n");
return(NULL);
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return(NULL);
}
NEXT;
/*
* Predefined entites override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL)
return(ent);
}
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
(ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
(ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
if ((ctxt->inSubset == 0) &&
(ctxt->sax != NULL) &&
(ctxt->sax->reference != NULL)) {
ctxt->sax->reference(ctxt->userData, name);
}
}
ctxt->valid = 0;
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) && (ent->content != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n", name);
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
return(ent);
}
| 171,289 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int parse_index(git_index *index, const char *buffer, size_t buffer_size)
{
int error = 0;
unsigned int i;
struct index_header header = { 0 };
git_oid checksum_calculated, checksum_expected;
const char *last = NULL;
const char *empty = "";
#define seek_forward(_increase) { \
if (_increase >= buffer_size) { \
error = index_error_invalid("ran out of data while parsing"); \
goto done; } \
buffer += _increase; \
buffer_size -= _increase;\
}
if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
return index_error_invalid("insufficient buffer space");
/* Precalculate the SHA1 of the files's contents -- we'll match it to
* the provided SHA1 in the footer */
git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);
/* Parse header */
if ((error = read_header(&header, buffer)) < 0)
return error;
index->version = header.version;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = empty;
seek_forward(INDEX_HEADER_SIZE);
assert(!index->entries.length);
if (index->ignore_case)
git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count);
else
git_idxmap_resize(index->entries_map, header.entry_count);
/* Parse all the entries */
for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
git_index_entry *entry = NULL;
size_t entry_size = read_entry(&entry, index, buffer, buffer_size, last);
/* 0 bytes read means an object corruption */
if (entry_size == 0) {
error = index_error_invalid("invalid entry");
goto done;
}
if ((error = git_vector_insert(&index->entries, entry)) < 0) {
index_entry_free(entry);
goto done;
}
INSERT_IN_MAP(index, entry, &error);
if (error < 0) {
index_entry_free(entry);
goto done;
}
error = 0;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = entry->path;
seek_forward(entry_size);
}
if (i != header.entry_count) {
error = index_error_invalid("header entries changed while parsing");
goto done;
}
/* There's still space for some extensions! */
while (buffer_size > INDEX_FOOTER_SIZE) {
size_t extension_size;
extension_size = read_extension(index, buffer, buffer_size);
/* see if we have read any bytes from the extension */
if (extension_size == 0) {
error = index_error_invalid("extension is truncated");
goto done;
}
seek_forward(extension_size);
}
if (buffer_size != INDEX_FOOTER_SIZE) {
error = index_error_invalid(
"buffer size does not match index footer size");
goto done;
}
/* 160-bit SHA-1 over the content of the index file before this checksum. */
git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);
if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) {
error = index_error_invalid(
"calculated checksum does not match expected");
goto done;
}
git_oid_cpy(&index->checksum, &checksum_calculated);
#undef seek_forward
/* Entries are stored case-sensitively on disk, so re-sort now if
* in-memory index is supposed to be case-insensitive
*/
git_vector_set_sorted(&index->entries, !index->ignore_case);
git_vector_sort(&index->entries);
done:
return error;
}
Commit Message: index: convert `read_entry` to return entry size via an out-param
The function `read_entry` does not conform to our usual coding style of
returning stuff via the out parameter and to use the return value for
reporting errors. Due to most of our code conforming to that pattern, it
has become quite natural for us to actually return `-1` in case there is
any error, which has also slipped in with commit 5625d86b9 (index:
support index v4, 2016-05-17). As the function returns an `size_t` only,
though, the return value is wrapped around, causing the caller of
`read_tree` to continue with an invalid index entry. Ultimately, this
can lead to a double-free.
Improve code and fix the bug by converting the function to return the
index entry size via an out parameter and only using the return value to
indicate errors.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-415 | static int parse_index(git_index *index, const char *buffer, size_t buffer_size)
{
int error = 0;
unsigned int i;
struct index_header header = { 0 };
git_oid checksum_calculated, checksum_expected;
const char *last = NULL;
const char *empty = "";
#define seek_forward(_increase) { \
if (_increase >= buffer_size) { \
error = index_error_invalid("ran out of data while parsing"); \
goto done; } \
buffer += _increase; \
buffer_size -= _increase;\
}
if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
return index_error_invalid("insufficient buffer space");
/* Precalculate the SHA1 of the files's contents -- we'll match it to
* the provided SHA1 in the footer */
git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);
/* Parse header */
if ((error = read_header(&header, buffer)) < 0)
return error;
index->version = header.version;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = empty;
seek_forward(INDEX_HEADER_SIZE);
assert(!index->entries.length);
if (index->ignore_case)
git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count);
else
git_idxmap_resize(index->entries_map, header.entry_count);
/* Parse all the entries */
for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
git_index_entry *entry = NULL;
size_t entry_size;
if ((error = read_entry(&entry, &entry_size, index, buffer, buffer_size, last)) < 0) {
error = index_error_invalid("invalid entry");
goto done;
}
if ((error = git_vector_insert(&index->entries, entry)) < 0) {
index_entry_free(entry);
goto done;
}
INSERT_IN_MAP(index, entry, &error);
if (error < 0) {
index_entry_free(entry);
goto done;
}
error = 0;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = entry->path;
seek_forward(entry_size);
}
if (i != header.entry_count) {
error = index_error_invalid("header entries changed while parsing");
goto done;
}
/* There's still space for some extensions! */
while (buffer_size > INDEX_FOOTER_SIZE) {
size_t extension_size;
extension_size = read_extension(index, buffer, buffer_size);
/* see if we have read any bytes from the extension */
if (extension_size == 0) {
error = index_error_invalid("extension is truncated");
goto done;
}
seek_forward(extension_size);
}
if (buffer_size != INDEX_FOOTER_SIZE) {
error = index_error_invalid(
"buffer size does not match index footer size");
goto done;
}
/* 160-bit SHA-1 over the content of the index file before this checksum. */
git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);
if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) {
error = index_error_invalid(
"calculated checksum does not match expected");
goto done;
}
git_oid_cpy(&index->checksum, &checksum_calculated);
#undef seek_forward
/* Entries are stored case-sensitively on disk, so re-sort now if
* in-memory index is supposed to be case-insensitive
*/
git_vector_set_sorted(&index->entries, !index->ignore_case);
git_vector_sort(&index->entries);
done:
return error;
}
| 169,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
unsigned int count)
{
struct snd_kcontrol *kctl;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid < card->last_numid + 1 + count &&
kctl->id.numid + kctl->count > card->last_numid + 1) {
card->last_numid = kctl->id.numid + kctl->count - 1;
return true;
}
}
return false;
}
Commit Message: ALSA: control: Handle numid overflow
Each control gets automatically assigned its numids when the control is created.
The allocation is done by incrementing the numid by the amount of allocated
numids per allocation. This means that excessive creation and destruction of
controls (e.g. via SNDRV_CTL_IOCTL_ELEM_ADD/REMOVE) can cause the id to
eventually overflow. Currently when this happens for the control that caused the
overflow kctl->id.numid + kctl->count will also over flow causing it to be
smaller than kctl->id.numid. Most of the code assumes that this is something
that can not happen, so we need to make sure that it won't happen
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189 | static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
unsigned int count)
{
struct snd_kcontrol *kctl;
/* Make sure that the ids assigned to the control do not wrap around */
if (card->last_numid >= UINT_MAX - count)
card->last_numid = 0;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid < card->last_numid + 1 + count &&
kctl->id.numid + kctl->count > card->last_numid + 1) {
card->last_numid = kctl->id.numid + kctl->count - 1;
return true;
}
}
return false;
}
| 166,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
const unsigned char *end )
{
int ret = 0;
size_t n;
if( ssl->conf->f_psk == NULL &&
( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Receive client pre-shared key identity name
*/
if( *p + 2 > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
n = ( (*p)[0] << 8 ) | (*p)[1];
*p += 2;
if( n < 1 || n > 65535 || *p + n > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ssl->conf->f_psk != NULL )
{
if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
else
{
/* Identity is not a big secret since clients send it in the clear,
* but treat it carefully anyway, just in case */
if( n != ssl->conf->psk_identity_len ||
mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
{
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
}
if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
{
MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
}
*p += n;
return( 0 );
}
Commit Message: Prevent bounds check bypass through overflow in PSK identity parsing
The check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is
unsafe because `*p + n` might overflow, thus bypassing the check. As
`n` is a user-specified value up to 65K, this is relevant if the
library happens to be located in the last 65K of virtual memory.
This commit replaces the check by a safe version.
CWE ID: CWE-190 | static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
const unsigned char *end )
{
int ret = 0;
size_t n;
if( ssl->conf->f_psk == NULL &&
( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Receive client pre-shared key identity name
*/
if( end - *p < 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
n = ( (*p)[0] << 8 ) | (*p)[1];
*p += 2;
if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ssl->conf->f_psk != NULL )
{
if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
else
{
/* Identity is not a big secret since clients send it in the clear,
* but treat it carefully anyway, just in case */
if( n != ssl->conf->psk_identity_len ||
mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
{
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
}
if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
{
MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
}
*p += n;
return( 0 );
}
| 169,418 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fht8x8_c(in, out, stride, tx_type);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
void reference_8x8_dct_2d(const int16_t input[kNumCoeffs],
double output[kNumCoeffs]) {
// First transform columns
for (int i = 0; i < 8; ++i) {
double temp_in[8], temp_out[8];
for (int j = 0; j < 8; ++j)
temp_in[j] = input[j*8 + i];
reference_8x8_dct_1d(temp_in, temp_out, 1);
for (int j = 0; j < 8; ++j)
output[j * 8 + i] = temp_out[j];
}
// Then transform rows
for (int i = 0; i < 8; ++i) {
double temp_in[8], temp_out[8];
for (int j = 0; j < 8; ++j)
temp_in[j] = output[j + i*8];
reference_8x8_dct_1d(temp_in, temp_out, 1);
// Scale by some magic number
for (int j = 0; j < 8; ++j)
output[j + i * 8] = temp_out[j] * 2;
}
}
void fdct8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) {
vpx_fdct8x8_c(in, out, stride);
}
void fht8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) {
vp9_fht8x8_c(in, out, stride, tx_type);
}
| 174,565 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadUYVYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
u,
v,
y1,
y2;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if ((image->columns % 2) != 0)
image->columns++;
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Accumulate UYVY, then unpack into two pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns >> 1); x++)
{
u=(unsigned char) ReadBlobByte(image);
y1=(unsigned char) ReadBlobByte(image);
v=(unsigned char) ReadBlobByte(image);
y2=(unsigned char) ReadBlobByte(image);
SetPixelRed(q,ScaleCharToQuantum(y1));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
SetPixelRed(q,ScaleCharToQuantum(y2));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetImageColorspace(image,YCbCrColorspace);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadUYVYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
u,
v,
y1,
y2;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if ((image->columns % 2) != 0)
image->columns++;
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Accumulate UYVY, then unpack into two pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns >> 1); x++)
{
u=(unsigned char) ReadBlobByte(image);
y1=(unsigned char) ReadBlobByte(image);
v=(unsigned char) ReadBlobByte(image);
y2=(unsigned char) ReadBlobByte(image);
SetPixelRed(q,ScaleCharToQuantum(y1));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
SetPixelRed(q,ScaleCharToQuantum(y2));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetImageColorspace(image,YCbCrColorspace);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *addr = msg->msg_name;
u32 dst_pid;
u32 dst_group;
struct sk_buff *skb;
int err;
struct scm_cookie scm;
if (msg->msg_flags&MSG_OOB)
return -EOPNOTSUPP;
if (NULL == siocb->scm)
siocb->scm = &scm;
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
if (msg->msg_namelen) {
err = -EINVAL;
if (addr->nl_family != AF_NETLINK)
goto out;
dst_pid = addr->nl_pid;
dst_group = ffs(addr->nl_groups);
err = -EPERM;
if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
goto out;
} else {
dst_pid = nlk->dst_pid;
dst_group = nlk->dst_group;
}
if (!nlk->pid) {
err = netlink_autobind(sock);
if (err)
goto out;
}
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = alloc_skb(len, GFP_KERNEL);
if (skb == NULL)
goto out;
NETLINK_CB(skb).pid = nlk->pid;
NETLINK_CB(skb).dst_group = dst_group;
memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
goto out;
}
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (dst_group) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
out:
scm_destroy(siocb->scm);
return err;
}
Commit Message: af_netlink: force credentials passing [CVE-2012-3520]
Pablo Neira Ayuso discovered that avahi and
potentially NetworkManager accept spoofed Netlink messages because of a
kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data
to the receiver if the sender did not provide such data, instead of not
including any such data at all or including the correct data from the
peer (as it is the case with AF_UNIX).
This bug was introduced in commit 16e572626961
(af_unix: dont send SCM_CREDENTIALS by default)
This patch forces passing credentials for netlink, as
before the regression.
Another fix would be to not add SCM_CREDENTIALS in
netlink messages if not provided by the sender, but it
might break some programs.
With help from Florian Weimer & Petr Matousek
This issue is designated as CVE-2012-3520
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Florian Weimer <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-287 | static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *addr = msg->msg_name;
u32 dst_pid;
u32 dst_group;
struct sk_buff *skb;
int err;
struct scm_cookie scm;
if (msg->msg_flags&MSG_OOB)
return -EOPNOTSUPP;
if (NULL == siocb->scm)
siocb->scm = &scm;
err = scm_send(sock, msg, siocb->scm, true);
if (err < 0)
return err;
if (msg->msg_namelen) {
err = -EINVAL;
if (addr->nl_family != AF_NETLINK)
goto out;
dst_pid = addr->nl_pid;
dst_group = ffs(addr->nl_groups);
err = -EPERM;
if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
goto out;
} else {
dst_pid = nlk->dst_pid;
dst_group = nlk->dst_group;
}
if (!nlk->pid) {
err = netlink_autobind(sock);
if (err)
goto out;
}
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = alloc_skb(len, GFP_KERNEL);
if (skb == NULL)
goto out;
NETLINK_CB(skb).pid = nlk->pid;
NETLINK_CB(skb).dst_group = dst_group;
memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
goto out;
}
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (dst_group) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
out:
scm_destroy(siocb->scm);
return err;
}
| 165,578 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc32",
"%s", "cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
| 166,883 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.