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: SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (length > INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
| 167,066 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_end_io_nolock(ext4_io_end_t *io)
{
struct inode *inode = io->inode;
loff_t offset = io->offset;
ssize_t size = io->size;
int ret = 0;
ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p,"
"list->prev 0x%p\n",
io, inode->i_ino, io->list.next, io->list.prev);
if (list_empty(&io->list))
return ret;
if (io->flag != EXT4_IO_UNWRITTEN)
return ret;
if (offset + size <= i_size_read(inode))
ret = ext4_convert_unwritten_extents(inode, offset, size);
if (ret < 0) {
printk(KERN_EMERG "%s: failed to convert unwritten"
"extents to written extents, error is %d"
" io is still on inode %lu aio dio list\n",
__func__, ret, inode->i_ino);
return ret;
}
/* clear the DIO AIO unwritten flag */
io->flag = 0;
return ret;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static int ext4_end_io_nolock(ext4_io_end_t *io)
{
struct inode *inode = io->inode;
loff_t offset = io->offset;
ssize_t size = io->size;
int ret = 0;
ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p,"
"list->prev 0x%p\n",
io, inode->i_ino, io->list.next, io->list.prev);
if (list_empty(&io->list))
return ret;
if (io->flag != EXT4_IO_UNWRITTEN)
return ret;
ret = ext4_convert_unwritten_extents(inode, offset, size);
if (ret < 0) {
printk(KERN_EMERG "%s: failed to convert unwritten"
"extents to written extents, error is %d"
" io is still on inode %lu aio dio list\n",
__func__, ret, inode->i_ino);
return ret;
}
/* clear the DIO AIO unwritten flag */
io->flag = 0;
return ret;
}
| 167,541 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
}
Commit Message:
CWE ID: CWE-704 | znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
if (r_type(pnval) != t_integer)
return gs_note_error(gs_error_typecheck);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
}
| 164,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Segment::DoLoadClusterUnknownSize(
long long& pos,
long& len)
{
assert(m_pos < 0);
assert(m_pUnknownSize);
#if 0
assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this
const long long element_start = m_pUnknownSize->m_element_start;
pos = -m_pos;
assert(pos > element_start);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long element_size = -1;
for (;;) //determine cluster size
{
if ((total >= 0) && (pos >= total))
{
element_size = total - element_start;
assert(element_size > 0);
break;
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
element_size = segment_stop - element_start;
assert(element_size > 0);
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster ID or Cues ID
{
element_size = pos - element_start;
assert(element_size > 0);
break;
}
#ifdef _DEBUG
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
#endif
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
assert(element_size >= 0);
m_pos = element_start + element_size;
m_pUnknownSize = 0;
return 2; //continue parsing
#else
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) //error or underflow
return status;
if (status == 0) //parsed a block
return 2; //continue parsing
assert(status > 0); //nothing left to parse of this cluster
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
assert(size >= 0);
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; //continue parsing
#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 | long Segment::DoLoadClusterUnknownSize(
long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) {
assert(m_pos < 0);
assert(m_pUnknownSize);
#if 0
assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this
const long long element_start = m_pUnknownSize->m_element_start;
pos = -m_pos;
assert(pos > element_start);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long element_size = -1;
for (;;) { //determine cluster size
if ((total >= 0) && (pos >= total))
{
element_size = total - element_start;
assert(element_size > 0);
break;
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
element_size = segment_stop - element_start;
assert(element_size > 0);
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID
element_size = pos - element_start;
assert(element_size > 0);
break;
}
#ifdef _DEBUG
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
#endif
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
assert(element_size >= 0);
m_pos = element_start + element_size;
m_pUnknownSize = 0;
return 2; //continue parsing
#else
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) // error or underflow
return status;
if (status == 0) // parsed a block
return 2; // continue parsing
assert(status > 0); // nothing left to parse of this cluster
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
assert(size >= 0);
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; // continue parsing
#endif
}
| 174,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_object(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* an object is a possibly empty sequence of object fields, separated by
* commas and surrounded by curly braces.
*/
json_struct_action ostart = sem->object_start;
json_struct_action oend = sem->object_end;
JsonTokenType tok;
if (ostart != NULL)
(*ostart) (sem->semstate);
* itself. Note that we increment this after we call the semantic routine
* for the object start and restore it before we call the routine for the
* object end.
*/
lex->lex_level++;
/* we know this will succeeed, just clearing the token */
lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
tok = lex_peek(lex);
switch (tok)
{
case JSON_TOKEN_STRING:
parse_object_field(lex, sem);
while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
parse_object_field(lex, sem);
break;
case JSON_TOKEN_OBJECT_END:
break;
default:
/* case of an invalid initial token inside the object */
report_parse_error(JSON_PARSE_OBJECT_START, lex);
}
lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
lex->lex_level--;
if (oend != NULL)
(*oend) (sem->semstate);
}
Commit Message:
CWE ID: CWE-119 | parse_object(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* an object is a possibly empty sequence of object fields, separated by
* commas and surrounded by curly braces.
*/
json_struct_action ostart = sem->object_start;
json_struct_action oend = sem->object_end;
JsonTokenType tok;
check_stack_depth();
if (ostart != NULL)
(*ostart) (sem->semstate);
* itself. Note that we increment this after we call the semantic routine
* for the object start and restore it before we call the routine for the
* object end.
*/
lex->lex_level++;
/* we know this will succeeed, just clearing the token */
lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
tok = lex_peek(lex);
switch (tok)
{
case JSON_TOKEN_STRING:
parse_object_field(lex, sem);
while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
parse_object_field(lex, sem);
break;
case JSON_TOKEN_OBJECT_END:
break;
default:
/* case of an invalid initial token inside the object */
report_parse_error(JSON_PARSE_OBJECT_START, lex);
}
lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
lex->lex_level--;
if (oend != NULL)
(*oend) (sem->semstate);
}
| 164,680 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage(
sk_sp<SkImage> image) {
CHECK(image);
DCHECK(!image->isLazyGenerated());
paint_image_ =
CreatePaintImageBuilder()
.set_image(std::move(image), cc::PaintImage::GetNextContentId())
.TakePaintImage();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage(
sk_sp<SkImage> image) {
CHECK(image);
DCHECK(!image->isLazyGenerated());
paint_image_ =
CreatePaintImageBuilder()
.set_image(std::move(image), cc::PaintImage::GetNextContentId())
.TakePaintImage();
}
| 172,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SVGImage::setContainerSize(const IntSize& size)
{
if (!m_page || !usesContainerSize())
return;
LocalFrame* frame = m_page->mainFrame();
SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
if (!rootElement)
return;
RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
if (!renderer)
return;
FrameView* view = frameView();
view->resize(this->containerSize());
renderer->setContainerSize(size);
}
Commit Message: Fix crash when resizing a view destroys the render tree
This is a simple fix for not holding a renderer across FrameView
resizes. Calling view->resize() can destroy renderers so this patch
updates SVGImage::setContainerSize to query the renderer after the
resize is complete. A similar issue does not exist for the dom tree
which is not destroyed.
BUG=344492
Review URL: https://codereview.chromium.org/178043006
git-svn-id: svn://svn.chromium.org/blink/trunk@168113 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void SVGImage::setContainerSize(const IntSize& size)
{
if (!m_page || !usesContainerSize())
return;
LocalFrame* frame = m_page->mainFrame();
SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
if (!rootElement)
return;
FrameView* view = frameView();
view->resize(this->containerSize());
RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
if (!renderer)
return;
renderer->setContainerSize(size);
}
| 171,706 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session )
{
TPM_RC rval;
TPM2B_ENCRYPTED_SECRET key;
char label[] = "ATH";
UINT16 bytes;
int i;
key.t.size = 0;
if( session->nonceOlder.t.size == 0 )
{
/* this is an internal routine to TSS and should be removed */
session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 );
for( i = 0; i < session->nonceOlder.t.size; i++ )
session->nonceOlder.t.buffer[i] = 0;
}
session->nonceNewer.t.size = session->nonceOlder.t.size;
rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0,
&( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType,
&( session->symmetric ), session->authHash, &( session->sessionHandle ),
&( session->nonceNewer ), 0 );
if( rval == TPM_RC_SUCCESS )
{
if( session->tpmKey == TPM_RH_NULL )
session->salt.t.size = 0;
if( session->bind == TPM_RH_NULL )
session->authValueBind.t.size = 0;
if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL )
{
session->sessionKey.b.size = 0;
}
else
{
bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
bytes = GetDigestSize( session->authHash );
if( key.t.size == 0 )
{
session->sessionKey.t.size = 0;
}
else
{
rval = tpm_kdfa(sapi_context, session->authHash, &(key.b), label, &( session->nonceNewer.b ),
&( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) );
}
if( rval != TPM_RC_SUCCESS )
{
return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED );
}
}
session->nonceTpmDecrypt.b.size = 0;
session->nonceTpmEncrypt.b.size = 0;
session->nvNameChanged = 0;
}
return rval;
}
Commit Message: kdfa: use openssl for hmac not tpm
While not reachable in the current code base tools, a potential
security bug lurked in tpm_kdfa().
If using that routine for an hmac authorization, the hmac was
calculated using the tpm. A user of an object wishing to
authenticate via hmac, would expect that the password is never
sent to the tpm. However, since the hmac calculation relies on
password, and is performed by the tpm, the password ends up
being sent in plain text to the tpm.
The fix is to use openssl to generate the hmac on the host.
Fixes: CVE-2017-7524
Signed-off-by: William Roberts <[email protected]>
CWE ID: CWE-522 | static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session )
{
TPM_RC rval;
TPM2B_ENCRYPTED_SECRET key;
char label[] = "ATH";
UINT16 bytes;
int i;
key.t.size = 0;
if( session->nonceOlder.t.size == 0 )
{
/* this is an internal routine to TSS and should be removed */
session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 );
for( i = 0; i < session->nonceOlder.t.size; i++ )
session->nonceOlder.t.buffer[i] = 0;
}
session->nonceNewer.t.size = session->nonceOlder.t.size;
rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0,
&( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType,
&( session->symmetric ), session->authHash, &( session->sessionHandle ),
&( session->nonceNewer ), 0 );
if( rval == TPM_RC_SUCCESS )
{
if( session->tpmKey == TPM_RH_NULL )
session->salt.t.size = 0;
if( session->bind == TPM_RH_NULL )
session->authValueBind.t.size = 0;
if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL )
{
session->sessionKey.b.size = 0;
}
else
{
bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) );
if (!result)
{
return TSS2_SYS_RC_BAD_VALUE;
}
bytes = GetDigestSize( session->authHash );
if( key.t.size == 0 )
{
session->sessionKey.t.size = 0;
}
else
{
rval = tpm_kdfa(session->authHash, &(key.b), label, &( session->nonceNewer.b ),
&( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) );
}
if( rval != TPM_RC_SUCCESS )
{
return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED );
}
}
session->nonceTpmDecrypt.b.size = 0;
session->nonceTpmEncrypt.b.size = 0;
session->nvNameChanged = 0;
}
return rval;
}
| 168,266 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionInstalledBubbleGtk::ShowInternal() {
BrowserWindowGtk* browser_window =
BrowserWindowGtk::GetBrowserWindowForNativeWindow(
browser_->window()->GetNativeHandle());
GtkWidget* reference_widget = NULL;
if (type_ == BROWSER_ACTION) {
BrowserActionsToolbarGtk* toolbar =
browser_window->GetToolbar()->GetBrowserActionsToolbar();
if (toolbar->animating() && animation_wait_retries_-- > 0) {
MessageLoopForUI::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ExtensionInstalledBubbleGtk::ShowInternal, this),
base::TimeDelta::FromMilliseconds(kAnimationWaitMS));
return;
}
reference_widget = toolbar->GetBrowserActionWidget(extension_);
gtk_container_check_resize(GTK_CONTAINER(
browser_window->GetToolbar()->widget()));
if (reference_widget && !gtk_widget_get_visible(reference_widget)) {
reference_widget = gtk_widget_get_visible(toolbar->chevron()) ?
toolbar->chevron() : NULL;
}
} else if (type_ == PAGE_ACTION) {
LocationBarViewGtk* location_bar_view =
browser_window->GetToolbar()->GetLocationBarView();
location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(),
true); // preview_enabled
reference_widget = location_bar_view->GetPageActionWidget(
extension_->page_action());
gtk_container_check_resize(GTK_CONTAINER(
browser_window->GetToolbar()->widget()));
DCHECK(reference_widget);
} else if (type_ == OMNIBOX_KEYWORD) {
LocationBarViewGtk* location_bar_view =
browser_window->GetToolbar()->GetLocationBarView();
reference_widget = location_bar_view->location_entry_widget();
DCHECK(reference_widget);
}
if (reference_widget == NULL)
reference_widget = browser_window->GetToolbar()->GetAppMenuButton();
GtkThemeService* theme_provider = GtkThemeService::GetFrom(
browser_->profile());
GtkWidget* bubble_content = gtk_hbox_new(FALSE, kHorizontalColumnSpacing);
gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);
if (!icon_.isNull()) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon_);
gfx::Size size(icon_.width(), icon_.height());
if (size.width() > kIconSize || size.height() > kIconSize) {
if (size.width() > size.height()) {
size.set_height(size.height() * kIconSize / size.width());
size.set_width(kIconSize);
} else {
size.set_width(size.width() * kIconSize / size.height());
size.set_height(kIconSize);
}
GdkPixbuf* old = pixbuf;
pixbuf = gdk_pixbuf_scale_simple(pixbuf, size.width(), size.height(),
GDK_INTERP_BILINEAR);
g_object_unref(old);
}
GtkWidget* icon_column = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), icon_column, FALSE, FALSE,
kIconPadding);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(icon_column), image, FALSE, FALSE, 0);
}
GtkWidget* text_column = gtk_vbox_new(FALSE, kTextColumnVerticalSpacing);
gtk_box_pack_start(GTK_BOX(bubble_content), text_column, FALSE, FALSE, 0);
GtkWidget* heading_label = gtk_label_new(NULL);
string16 extension_name = UTF8ToUTF16(extension_->name());
base::i18n::AdjustStringForLocaleDirection(&extension_name);
std::string heading_text = l10n_util::GetStringFUTF8(
IDS_EXTENSION_INSTALLED_HEADING, extension_name,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
char* markup = g_markup_printf_escaped("<span size=\"larger\">%s</span>",
heading_text.c_str());
gtk_label_set_markup(GTK_LABEL(heading_label), markup);
g_free(markup);
gtk_util::SetLabelWidth(heading_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), heading_label, FALSE, FALSE, 0);
if (type_ == PAGE_ACTION) {
GtkWidget* info_label = gtk_label_new(l10n_util::GetStringUTF8(
IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO).c_str());
gtk_util::SetLabelWidth(info_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), info_label, FALSE, FALSE, 0);
}
if (type_ == OMNIBOX_KEYWORD) {
GtkWidget* info_label = gtk_label_new(l10n_util::GetStringFUTF8(
IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO,
UTF8ToUTF16(extension_->omnibox_keyword())).c_str());
gtk_util::SetLabelWidth(info_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), info_label, FALSE, FALSE, 0);
}
GtkWidget* manage_label = gtk_label_new(
l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALLED_MANAGE_INFO).c_str());
gtk_util::SetLabelWidth(manage_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), manage_label, FALSE, FALSE, 0);
GtkWidget* close_column = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), close_column, FALSE, FALSE, 0);
close_button_.reset(CustomDrawButton::CloseButton(theme_provider));
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(close_column), close_button_->widget(),
FALSE, FALSE, 0);
BubbleGtk::ArrowLocationGtk arrow_location =
!base::i18n::IsRTL() ?
BubbleGtk::ARROW_LOCATION_TOP_RIGHT :
BubbleGtk::ARROW_LOCATION_TOP_LEFT;
gfx::Rect bounds = gtk_util::WidgetBounds(reference_widget);
if (type_ == OMNIBOX_KEYWORD) {
arrow_location =
!base::i18n::IsRTL() ?
BubbleGtk::ARROW_LOCATION_TOP_LEFT :
BubbleGtk::ARROW_LOCATION_TOP_RIGHT;
if (base::i18n::IsRTL())
bounds.Offset(bounds.width(), 0);
bounds.set_width(0);
}
bubble_ = BubbleGtk::Show(reference_widget,
&bounds,
bubble_content,
arrow_location,
true, // match_system_theme
true, // grab_input
theme_provider,
this);
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void ExtensionInstalledBubbleGtk::ShowInternal() {
BrowserWindowGtk* browser_window =
BrowserWindowGtk::GetBrowserWindowForNativeWindow(
browser_->window()->GetNativeHandle());
GtkWidget* reference_widget = NULL;
if (type_ == BROWSER_ACTION) {
BrowserActionsToolbarGtk* toolbar =
browser_window->GetToolbar()->GetBrowserActionsToolbar();
if (toolbar->animating() && animation_wait_retries_-- > 0) {
MessageLoopForUI::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ExtensionInstalledBubbleGtk::ShowInternal, this),
base::TimeDelta::FromMilliseconds(kAnimationWaitMS));
return;
}
reference_widget = toolbar->GetBrowserActionWidget(extension_);
gtk_container_check_resize(GTK_CONTAINER(
browser_window->GetToolbar()->widget()));
if (reference_widget && !gtk_widget_get_visible(reference_widget)) {
reference_widget = gtk_widget_get_visible(toolbar->chevron()) ?
toolbar->chevron() : NULL;
}
} else if (type_ == PAGE_ACTION) {
LocationBarViewGtk* location_bar_view =
browser_window->GetToolbar()->GetLocationBarView();
location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(),
true); // preview_enabled
reference_widget = location_bar_view->GetPageActionWidget(
extension_->page_action());
gtk_container_check_resize(GTK_CONTAINER(
browser_window->GetToolbar()->widget()));
DCHECK(reference_widget);
} else if (type_ == OMNIBOX_KEYWORD) {
LocationBarViewGtk* location_bar_view =
browser_window->GetToolbar()->GetLocationBarView();
reference_widget = location_bar_view->location_entry_widget();
DCHECK(reference_widget);
}
if (reference_widget == NULL)
reference_widget = browser_window->GetToolbar()->GetAppMenuButton();
GtkThemeService* theme_provider = GtkThemeService::GetFrom(
browser_->profile());
GtkWidget* bubble_content = gtk_hbox_new(FALSE, kHorizontalColumnSpacing);
gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);
if (!icon_.isNull()) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon_);
gfx::Size size(icon_.width(), icon_.height());
if (size.width() > kIconSize || size.height() > kIconSize) {
if (size.width() > size.height()) {
size.set_height(size.height() * kIconSize / size.width());
size.set_width(kIconSize);
} else {
size.set_width(size.width() * kIconSize / size.height());
size.set_height(kIconSize);
}
GdkPixbuf* old = pixbuf;
pixbuf = gdk_pixbuf_scale_simple(pixbuf, size.width(), size.height(),
GDK_INTERP_BILINEAR);
g_object_unref(old);
}
GtkWidget* icon_column = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), icon_column, FALSE, FALSE,
kIconPadding);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(icon_column), image, FALSE, FALSE, 0);
}
GtkWidget* text_column = gtk_vbox_new(FALSE, kTextColumnVerticalSpacing);
gtk_box_pack_start(GTK_BOX(bubble_content), text_column, FALSE, FALSE, 0);
GtkWidget* heading_label = gtk_label_new(NULL);
string16 extension_name = UTF8ToUTF16(extension_->name());
base::i18n::AdjustStringForLocaleDirection(&extension_name);
std::string heading_text = l10n_util::GetStringFUTF8(
IDS_EXTENSION_INSTALLED_HEADING, extension_name);
char* markup = g_markup_printf_escaped("<span size=\"larger\">%s</span>",
heading_text.c_str());
gtk_label_set_markup(GTK_LABEL(heading_label), markup);
g_free(markup);
gtk_util::SetLabelWidth(heading_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), heading_label, FALSE, FALSE, 0);
if (type_ == PAGE_ACTION) {
GtkWidget* info_label = gtk_label_new(l10n_util::GetStringUTF8(
IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO).c_str());
gtk_util::SetLabelWidth(info_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), info_label, FALSE, FALSE, 0);
}
if (type_ == OMNIBOX_KEYWORD) {
GtkWidget* info_label = gtk_label_new(l10n_util::GetStringFUTF8(
IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO,
UTF8ToUTF16(extension_->omnibox_keyword())).c_str());
gtk_util::SetLabelWidth(info_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), info_label, FALSE, FALSE, 0);
}
GtkWidget* manage_label = gtk_label_new(
l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALLED_MANAGE_INFO).c_str());
gtk_util::SetLabelWidth(manage_label, kTextColumnWidth);
gtk_box_pack_start(GTK_BOX(text_column), manage_label, FALSE, FALSE, 0);
GtkWidget* close_column = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), close_column, FALSE, FALSE, 0);
close_button_.reset(CustomDrawButton::CloseButton(theme_provider));
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(close_column), close_button_->widget(),
FALSE, FALSE, 0);
BubbleGtk::ArrowLocationGtk arrow_location =
!base::i18n::IsRTL() ?
BubbleGtk::ARROW_LOCATION_TOP_RIGHT :
BubbleGtk::ARROW_LOCATION_TOP_LEFT;
gfx::Rect bounds = gtk_util::WidgetBounds(reference_widget);
if (type_ == OMNIBOX_KEYWORD) {
arrow_location =
!base::i18n::IsRTL() ?
BubbleGtk::ARROW_LOCATION_TOP_LEFT :
BubbleGtk::ARROW_LOCATION_TOP_RIGHT;
if (base::i18n::IsRTL())
bounds.Offset(bounds.width(), 0);
bounds.set_width(0);
}
bubble_ = BubbleGtk::Show(reference_widget,
&bounds,
bubble_content,
arrow_location,
true, // match_system_theme
true, // grab_input
theme_provider,
this);
}
| 170,982 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup),
mPortIndex(portIndex) {
}
| 173,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tcp_v6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct in6_addr *saddr = NULL, *final_p, final;
struct flowi6 fl6;
struct dst_entry *dst;
int addr_type;
int err;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
IP6_ECN_flow_init(fl6.flowlabel);
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
fl6_sock_release(flowlabel);
}
}
/*
* connect() to INADDR_ANY means loopback (BSD'ism).
*/
if (ipv6_addr_any(&usin->sin6_addr))
usin->sin6_addr.s6_addr[15] = 0x1;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -ENETUNREACH;
if (addr_type&IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
/* If interface is set while binding, indices
* must coincide.
*/
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id)
return -EINVAL;
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
return -EINVAL;
}
if (tp->rx_opt.ts_recent_stamp &&
!ipv6_addr_equal(&sk->sk_v6_daddr, &usin->sin6_addr)) {
tp->rx_opt.ts_recent = 0;
tp->rx_opt.ts_recent_stamp = 0;
tp->write_seq = 0;
}
sk->sk_v6_daddr = usin->sin6_addr;
np->flow_label = fl6.flowlabel;
/*
* TCP over IPv4
*/
if (addr_type == IPV6_ADDR_MAPPED) {
u32 exthdrlen = icsk->icsk_ext_hdr_len;
struct sockaddr_in sin;
SOCK_DEBUG(sk, "connect: ipv4 mapped\n");
if (__ipv6_only_sock(sk))
return -ENETUNREACH;
sin.sin_family = AF_INET;
sin.sin_port = usin->sin6_port;
sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];
icsk->icsk_af_ops = &ipv6_mapped;
sk->sk_backlog_rcv = tcp_v4_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv6_mapped_specific;
#endif
err = tcp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));
if (err) {
icsk->icsk_ext_hdr_len = exthdrlen;
icsk->icsk_af_ops = &ipv6_specific;
sk->sk_backlog_rcv = tcp_v6_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv6_specific;
#endif
goto failure;
}
np->saddr = sk->sk_v6_rcv_saddr;
return err;
}
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))
saddr = &sk->sk_v6_rcv_saddr;
fl6.flowi6_proto = IPPROTO_TCP;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = saddr ? *saddr : np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = usin->sin6_port;
fl6.fl6_sport = inet->inet_sport;
final_p = fl6_update_dst(&fl6, np->opt, &final);
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto failure;
}
if (!saddr) {
saddr = &fl6.saddr;
sk->sk_v6_rcv_saddr = *saddr;
}
/* set the source address */
np->saddr = *saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
sk->sk_gso_type = SKB_GSO_TCPV6;
__ip6_dst_store(sk, dst, NULL, NULL);
if (tcp_death_row.sysctl_tw_recycle &&
!tp->rx_opt.ts_recent_stamp &&
ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr))
tcp_fetch_timewait_stamp(sk, dst);
icsk->icsk_ext_hdr_len = 0;
if (np->opt)
icsk->icsk_ext_hdr_len = (np->opt->opt_flen +
np->opt->opt_nflen);
tp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr);
inet->inet_dport = usin->sin6_port;
tcp_set_state(sk, TCP_SYN_SENT);
err = inet6_hash_connect(&tcp_death_row, sk);
if (err)
goto late_failure;
sk_set_txhash(sk);
if (!tp->write_seq && likely(!tp->repair))
tp->write_seq = secure_tcpv6_sequence_number(np->saddr.s6_addr32,
sk->sk_v6_daddr.s6_addr32,
inet->inet_sport,
inet->inet_dport);
err = tcp_connect(sk);
if (err)
goto late_failure;
return 0;
late_failure:
tcp_set_state(sk, TCP_CLOSE);
__sk_dst_reset(sk);
failure:
inet->inet_dport = 0;
sk->sk_route_caps = 0;
return err;
}
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 tcp_v6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct in6_addr *saddr = NULL, *final_p, final;
struct ipv6_txoptions *opt;
struct flowi6 fl6;
struct dst_entry *dst;
int addr_type;
int err;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
IP6_ECN_flow_init(fl6.flowlabel);
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
fl6_sock_release(flowlabel);
}
}
/*
* connect() to INADDR_ANY means loopback (BSD'ism).
*/
if (ipv6_addr_any(&usin->sin6_addr))
usin->sin6_addr.s6_addr[15] = 0x1;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -ENETUNREACH;
if (addr_type&IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
/* If interface is set while binding, indices
* must coincide.
*/
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id)
return -EINVAL;
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
return -EINVAL;
}
if (tp->rx_opt.ts_recent_stamp &&
!ipv6_addr_equal(&sk->sk_v6_daddr, &usin->sin6_addr)) {
tp->rx_opt.ts_recent = 0;
tp->rx_opt.ts_recent_stamp = 0;
tp->write_seq = 0;
}
sk->sk_v6_daddr = usin->sin6_addr;
np->flow_label = fl6.flowlabel;
/*
* TCP over IPv4
*/
if (addr_type == IPV6_ADDR_MAPPED) {
u32 exthdrlen = icsk->icsk_ext_hdr_len;
struct sockaddr_in sin;
SOCK_DEBUG(sk, "connect: ipv4 mapped\n");
if (__ipv6_only_sock(sk))
return -ENETUNREACH;
sin.sin_family = AF_INET;
sin.sin_port = usin->sin6_port;
sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];
icsk->icsk_af_ops = &ipv6_mapped;
sk->sk_backlog_rcv = tcp_v4_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv6_mapped_specific;
#endif
err = tcp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));
if (err) {
icsk->icsk_ext_hdr_len = exthdrlen;
icsk->icsk_af_ops = &ipv6_specific;
sk->sk_backlog_rcv = tcp_v6_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv6_specific;
#endif
goto failure;
}
np->saddr = sk->sk_v6_rcv_saddr;
return err;
}
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))
saddr = &sk->sk_v6_rcv_saddr;
fl6.flowi6_proto = IPPROTO_TCP;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = saddr ? *saddr : np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = usin->sin6_port;
fl6.fl6_sport = inet->inet_sport;
opt = rcu_dereference_protected(np->opt, sock_owned_by_user(sk));
final_p = fl6_update_dst(&fl6, opt, &final);
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto failure;
}
if (!saddr) {
saddr = &fl6.saddr;
sk->sk_v6_rcv_saddr = *saddr;
}
/* set the source address */
np->saddr = *saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
sk->sk_gso_type = SKB_GSO_TCPV6;
__ip6_dst_store(sk, dst, NULL, NULL);
if (tcp_death_row.sysctl_tw_recycle &&
!tp->rx_opt.ts_recent_stamp &&
ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr))
tcp_fetch_timewait_stamp(sk, dst);
icsk->icsk_ext_hdr_len = 0;
if (opt)
icsk->icsk_ext_hdr_len = opt->opt_flen +
opt->opt_nflen;
tp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr);
inet->inet_dport = usin->sin6_port;
tcp_set_state(sk, TCP_SYN_SENT);
err = inet6_hash_connect(&tcp_death_row, sk);
if (err)
goto late_failure;
sk_set_txhash(sk);
if (!tp->write_seq && likely(!tp->repair))
tp->write_seq = secure_tcpv6_sequence_number(np->saddr.s6_addr32,
sk->sk_v6_daddr.s6_addr32,
inet->inet_sport,
inet->inet_dport);
err = tcp_connect(sk);
if (err)
goto late_failure;
return 0;
late_failure:
tcp_set_state(sk, TCP_CLOSE);
__sk_dst_reset(sk);
failure:
inet->inet_dport = 0;
sk->sk_route_caps = 0;
return err;
}
| 167,340 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MessageService::OpenChannelToNativeApp(
int source_process_id,
int source_routing_id,
int receiver_port_id,
const std::string& source_extension_id,
const std::string& native_app_name,
const std::string& channel_name,
const std::string& connect_message) {
content::RenderProcessHost* source =
content::RenderProcessHost::FromID(source_process_id);
if (!source)
return;
WebContents* source_contents = tab_util::GetWebContentsByID(
source_process_id, source_routing_id);
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue(
source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS));
base::JSONWriter::Write(tab_value.get(), &tab_json);
}
scoped_ptr<MessageChannel> channel(new MessageChannel());
channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL,
source_extension_id));
NativeMessageProcessHost::MessageType type =
channel_name == "chrome.runtime.sendNativeMessage" ?
NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST :
NativeMessageProcessHost::TYPE_CONNECT;
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&NativeMessageProcessHost::Create,
base::WeakPtr<NativeMessageProcessHost::Client>(
weak_factory_.GetWeakPtr()),
native_app_name, connect_message, receiver_port_id,
type,
base::Bind(&MessageService::FinalizeOpenChannelToNativeApp,
weak_factory_.GetWeakPtr(),
receiver_port_id,
channel_name,
base::Passed(&channel),
tab_json)));
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void MessageService::OpenChannelToNativeApp(
int source_process_id,
int source_routing_id,
int receiver_port_id,
const std::string& source_extension_id,
const std::string& native_app_name,
const std::string& channel_name,
const std::string& connect_message) {
content::RenderProcessHost* source =
content::RenderProcessHost::FromID(source_process_id);
if (!source)
return;
WebContents* source_contents = tab_util::GetWebContentsByID(
source_process_id, source_routing_id);
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue(
source_contents));
base::JSONWriter::Write(tab_value.get(), &tab_json);
}
scoped_ptr<MessageChannel> channel(new MessageChannel());
channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL,
source_extension_id));
NativeMessageProcessHost::MessageType type =
channel_name == "chrome.runtime.sendNativeMessage" ?
NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST :
NativeMessageProcessHost::TYPE_CONNECT;
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&NativeMessageProcessHost::Create,
base::WeakPtr<NativeMessageProcessHost::Client>(
weak_factory_.GetWeakPtr()),
native_app_name, connect_message, receiver_port_id,
type,
base::Bind(&MessageService::FinalizeOpenChannelToNativeApp,
weak_factory_.GetWeakPtr(),
receiver_port_id,
channel_name,
base::Passed(&channel),
tab_json)));
}
| 171,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NormalPageArena::shrinkObject(HeapObjectHeader* header, size_t newSize) {
ASSERT(header->checkHeader());
ASSERT(header->payloadSize() > newSize);
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(header->size() > allocationSize);
size_t shrinkSize = header->size() - allocationSize;
if (isObjectAllocatedAtAllocationPoint(header)) {
m_currentAllocationPoint -= shrinkSize;
setRemainingAllocationSize(m_remainingAllocationSize + shrinkSize);
SET_MEMORY_INACCESSIBLE(m_currentAllocationPoint, shrinkSize);
header->setSize(allocationSize);
return true;
}
ASSERT(shrinkSize >= sizeof(HeapObjectHeader));
ASSERT(header->gcInfoIndex() > 0);
Address shrinkAddress = header->payloadEnd() - shrinkSize;
HeapObjectHeader* freedHeader = new (NotNull, shrinkAddress)
HeapObjectHeader(shrinkSize, header->gcInfoIndex());
freedHeader->markPromptlyFreed();
ASSERT(pageFromObject(reinterpret_cast<Address>(header)) ==
findPageFromAddress(reinterpret_cast<Address>(header)));
m_promptlyFreedSize += shrinkSize;
header->setSize(allocationSize);
SET_MEMORY_INACCESSIBLE(shrinkAddress + sizeof(HeapObjectHeader),
shrinkSize - sizeof(HeapObjectHeader));
return false;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | bool NormalPageArena::shrinkObject(HeapObjectHeader* header, size_t newSize) {
header->checkHeader();
ASSERT(header->payloadSize() > newSize);
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(header->size() > allocationSize);
size_t shrinkSize = header->size() - allocationSize;
if (isObjectAllocatedAtAllocationPoint(header)) {
m_currentAllocationPoint -= shrinkSize;
setRemainingAllocationSize(m_remainingAllocationSize + shrinkSize);
SET_MEMORY_INACCESSIBLE(m_currentAllocationPoint, shrinkSize);
header->setSize(allocationSize);
return true;
}
ASSERT(shrinkSize >= sizeof(HeapObjectHeader));
ASSERT(header->gcInfoIndex() > 0);
Address shrinkAddress = header->payloadEnd() - shrinkSize;
HeapObjectHeader* freedHeader = new (NotNull, shrinkAddress)
HeapObjectHeader(shrinkSize, header->gcInfoIndex());
freedHeader->markPromptlyFreed();
ASSERT(pageFromObject(reinterpret_cast<Address>(header)) ==
findPageFromAddress(reinterpret_cast<Address>(header)));
m_promptlyFreedSize += shrinkSize;
header->setSize(allocationSize);
SET_MEMORY_INACCESSIBLE(shrinkAddress + sizeof(HeapObjectHeader),
shrinkSize - sizeof(HeapObjectHeader));
return false;
}
| 172,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vmci_transport_dgram_dequeue(struct kiocb *kiocb,
struct vsock_sock *vsk,
struct msghdr *msg, size_t len,
int flags)
{
int err;
int noblock;
struct vmci_datagram *dg;
size_t payload_len;
struct sk_buff *skb;
noblock = flags & MSG_DONTWAIT;
if (flags & MSG_OOB || flags & MSG_ERRQUEUE)
return -EOPNOTSUPP;
/* Retrieve the head sk_buff from the socket's receive queue. */
err = 0;
skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);
if (err)
return err;
if (!skb)
return -EAGAIN;
dg = (struct vmci_datagram *)skb->data;
if (!dg)
/* err is 0, meaning we read zero bytes. */
goto out;
payload_len = dg->payload_size;
/* Ensure the sk_buff matches the payload size claimed in the packet. */
if (payload_len != skb->len - sizeof(*dg)) {
err = -EINVAL;
goto out;
}
if (payload_len > len) {
payload_len = len;
msg->msg_flags |= MSG_TRUNC;
}
/* Place the datagram payload in the user's iovec. */
err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,
payload_len);
if (err)
goto out;
msg->msg_namelen = 0;
if (msg->msg_name) {
struct sockaddr_vm *vm_addr;
/* Provide the address of the sender. */
vm_addr = (struct sockaddr_vm *)msg->msg_name;
vsock_addr_init(vm_addr, dg->src.context, dg->src.resource);
msg->msg_namelen = sizeof(*vm_addr);
}
err = payload_len;
out:
skb_free_datagram(&vsk->sk, skb);
return err;
}
Commit Message: VSOCK: vmci - fix possible info leak in vmci_transport_dgram_dequeue()
In case we received no data on the call to skb_recv_datagram(), i.e.
skb->data is NULL, vmci_transport_dgram_dequeue() will return with 0
without updating msg_namelen leading to net/socket.c leaking the local,
uninitialized sockaddr_storage variable to userland -- 128 bytes of
kernel stack memory.
Fix this by moving the already existing msg_namelen assignment a few
lines above.
Cc: Andy King <[email protected]>
Cc: Dmitry Torokhov <[email protected]>
Cc: George Zhang <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,
struct vsock_sock *vsk,
struct msghdr *msg, size_t len,
int flags)
{
int err;
int noblock;
struct vmci_datagram *dg;
size_t payload_len;
struct sk_buff *skb;
noblock = flags & MSG_DONTWAIT;
if (flags & MSG_OOB || flags & MSG_ERRQUEUE)
return -EOPNOTSUPP;
msg->msg_namelen = 0;
/* Retrieve the head sk_buff from the socket's receive queue. */
err = 0;
skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);
if (err)
return err;
if (!skb)
return -EAGAIN;
dg = (struct vmci_datagram *)skb->data;
if (!dg)
/* err is 0, meaning we read zero bytes. */
goto out;
payload_len = dg->payload_size;
/* Ensure the sk_buff matches the payload size claimed in the packet. */
if (payload_len != skb->len - sizeof(*dg)) {
err = -EINVAL;
goto out;
}
if (payload_len > len) {
payload_len = len;
msg->msg_flags |= MSG_TRUNC;
}
/* Place the datagram payload in the user's iovec. */
err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,
payload_len);
if (err)
goto out;
if (msg->msg_name) {
struct sockaddr_vm *vm_addr;
/* Provide the address of the sender. */
vm_addr = (struct sockaddr_vm *)msg->msg_name;
vsock_addr_init(vm_addr, dg->src.context, dg->src.resource);
msg->msg_namelen = sizeof(*vm_addr);
}
err = payload_len;
out:
skb_free_datagram(&vsk->sk, skb);
return err;
}
| 166,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, header[228];
unsigned char *cb1 = NULL, *cb2 = NULL;
size_t cb1_len, cb2_len, alloc_len;
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 (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
pool->swork.job_id = job_id;
snprintf(pool->prev_hash, 65, "%s", prev_hash);
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
snprintf(pool->bbversion, 9, "%s", bbversion);
snprintf(pool->nbit, 9, "%s", nbit);
snprintf(pool->ntime, 9, "%s", ntime);
pool->swork.clean = clean;
alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = 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] = malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
if (opt_protocol)
applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
goto out_unlock;
}
}
}
pool->merkles = merkles;
if (clean)
pool->nonce2 = 0;
#if 0
header_len = strlen(pool->bbversion) +
strlen(pool->prev_hash);
/* merkle_hash */ 32 +
strlen(pool->ntime) +
strlen(pool->nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
#endif
snprintf(header, 225,
"%s%s%s%s%s%s%s",
pool->bbversion,
pool->prev_hash,
blank_merkle,
pool->ntime,
pool->nbit,
"00000000", /* nonce */
workpadding);
ret = hex2bin(pool->header_bin, header, 112);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
goto out_unlock;
}
cb1 = alloca(cb1_len);
ret = hex2bin(cb1, coinbase1, cb1_len);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
goto out_unlock;
}
cb2 = alloca(cb2_len);
ret = hex2bin(cb2, coinbase2, cb2_len);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
goto out_unlock;
}
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = 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);
if (opt_debug) {
char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
free(cb);
}
out_unlock:
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);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
Commit Message: Do some random sanity checking for stratum message parsing
CWE ID: CWE-119 | static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, header[228];
unsigned char *cb1 = NULL, *cb2 = NULL;
size_t cb1_len, cb2_len, alloc_len;
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 (!valid_hex(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
!valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
!valid_hex(ntime)) {
/* Annoying but we must not leak memory */
free(job_id);
free(coinbase1);
free(coinbase2);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
pool->swork.job_id = job_id;
snprintf(pool->prev_hash, 65, "%s", prev_hash);
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
snprintf(pool->bbversion, 9, "%s", bbversion);
snprintf(pool->nbit, 9, "%s", nbit);
snprintf(pool->ntime, 9, "%s", ntime);
pool->swork.clean = clean;
alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = 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] = malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
if (opt_protocol)
applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
goto out_unlock;
}
}
}
pool->merkles = merkles;
if (clean)
pool->nonce2 = 0;
#if 0
header_len = strlen(pool->bbversion) +
strlen(pool->prev_hash);
/* merkle_hash */ 32 +
strlen(pool->ntime) +
strlen(pool->nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
#endif
snprintf(header, 225,
"%s%s%s%s%s%s%s",
pool->bbversion,
pool->prev_hash,
blank_merkle,
pool->ntime,
pool->nbit,
"00000000", /* nonce */
workpadding);
ret = hex2bin(pool->header_bin, header, 112);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
goto out_unlock;
}
cb1 = alloca(cb1_len);
ret = hex2bin(cb1, coinbase1, cb1_len);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
goto out_unlock;
}
cb2 = alloca(cb2_len);
ret = hex2bin(cb2, coinbase2, cb2_len);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
goto out_unlock;
}
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = 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);
if (opt_debug) {
char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
free(cb);
}
out_unlock:
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);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
| 166,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type)
{
struct hexline *hx;
u8 reset;
int ret,pos=0;
hx = kmalloc(sizeof(*hx), GFP_KERNEL);
if (!hx)
return -ENOMEM;
/* stop the CPU */
reset = 1;
if ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1)
err("could not stop the USB controller CPU.");
while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) {
deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk);
ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len);
if (ret != hx->len) {
err("error while transferring firmware (transferred size: %d, block size: %d)",
ret, hx->len);
ret = -EINVAL;
break;
}
}
if (ret < 0) {
err("firmware download failed at %d with %d",pos,ret);
kfree(hx);
return ret;
}
if (ret == 0) {
/* restart the CPU */
reset = 0;
if (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) {
err("could not restart the USB controller CPU.");
ret = -EINVAL;
}
} else
ret = -EIO;
kfree(hx);
return ret;
}
Commit Message: [media] dvb-usb-firmware: don't do DMA on stack
The buffer allocation for the firmware data was changed in
commit 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load")
but the same applies for the reset value.
Fixes: 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load")
Cc: [email protected]
Signed-off-by: Stefan Brüns <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type)
{
struct hexline *hx;
u8 *buf;
int ret, pos = 0;
u16 cpu_cs_register = cypress[type].cpu_cs_register;
buf = kmalloc(sizeof(*hx), GFP_KERNEL);
if (!buf)
return -ENOMEM;
hx = (struct hexline *)buf;
/* stop the CPU */
buf[0] = 1;
if (usb_cypress_writemem(udev, cpu_cs_register, buf, 1) != 1)
err("could not stop the USB controller CPU.");
while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) {
deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk);
ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len);
if (ret != hx->len) {
err("error while transferring firmware (transferred size: %d, block size: %d)",
ret, hx->len);
ret = -EINVAL;
break;
}
}
if (ret < 0) {
err("firmware download failed at %d with %d",pos,ret);
kfree(buf);
return ret;
}
if (ret == 0) {
/* restart the CPU */
buf[0] = 0;
if (usb_cypress_writemem(udev, cpu_cs_register, buf, 1) != 1) {
err("could not restart the USB controller CPU.");
ret = -EINVAL;
}
} else
ret = -EIO;
kfree(buf);
return ret;
}
| 168,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gplotGenCommandFile(GPLOT *gplot)
{
char buf[L_BUF_SIZE];
char *cmdstr, *plottitle, *dataname;
l_int32 i, plotstyle, nplots;
FILE *fp;
PROCNAME("gplotGenCommandFile");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
/* Remove any previous command data */
sarrayClear(gplot->cmddata);
/* Generate command data instructions */
if (gplot->title) { /* set title */
snprintf(buf, L_BUF_SIZE, "set title '%s'", gplot->title);
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
if (gplot->xlabel) { /* set xlabel */
snprintf(buf, L_BUF_SIZE, "set xlabel '%s'", gplot->xlabel);
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
if (gplot->ylabel) { /* set ylabel */
snprintf(buf, L_BUF_SIZE, "set ylabel '%s'", gplot->ylabel);
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
/* Set terminal type and output */
if (gplot->outformat == GPLOT_PNG) {
snprintf(buf, L_BUF_SIZE, "set terminal png; set output '%s'",
gplot->outname);
} else if (gplot->outformat == GPLOT_PS) {
snprintf(buf, L_BUF_SIZE, "set terminal postscript; set output '%s'",
gplot->outname);
} else if (gplot->outformat == GPLOT_EPS) {
snprintf(buf, L_BUF_SIZE,
"set terminal postscript eps; set output '%s'",
gplot->outname);
} else if (gplot->outformat == GPLOT_LATEX) {
snprintf(buf, L_BUF_SIZE, "set terminal latex; set output '%s'",
gplot->outname);
}
sarrayAddString(gplot->cmddata, buf, L_COPY);
if (gplot->scaling == GPLOT_LOG_SCALE_X ||
gplot->scaling == GPLOT_LOG_SCALE_X_Y) {
snprintf(buf, L_BUF_SIZE, "set logscale x");
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
if (gplot->scaling == GPLOT_LOG_SCALE_Y ||
gplot->scaling == GPLOT_LOG_SCALE_X_Y) {
snprintf(buf, L_BUF_SIZE, "set logscale y");
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
nplots = sarrayGetCount(gplot->datanames);
for (i = 0; i < nplots; i++) {
plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY);
dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY);
numaGetIValue(gplot->plotstyles, i, &plotstyle);
if (nplots == 1) {
snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s",
dataname, plottitle, gplotstylenames[plotstyle]);
} else {
if (i == 0)
snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s, \\",
dataname, plottitle, gplotstylenames[plotstyle]);
else if (i < nplots - 1)
snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s, \\",
dataname, plottitle, gplotstylenames[plotstyle]);
else
snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s",
dataname, plottitle, gplotstylenames[plotstyle]);
}
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
/* Write command data to file */
cmdstr = sarrayToString(gplot->cmddata, 1);
if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) {
LEPT_FREE(cmdstr);
return ERROR_INT("cmd stream not opened", procName, 1);
}
fwrite(cmdstr, 1, strlen(cmdstr), fp);
fclose(fp);
LEPT_FREE(cmdstr);
return 0;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119 | gplotGenCommandFile(GPLOT *gplot)
{
char buf[L_BUFSIZE];
char *cmdstr, *plottitle, *dataname;
l_int32 i, plotstyle, nplots;
FILE *fp;
PROCNAME("gplotGenCommandFile");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
/* Remove any previous command data */
sarrayClear(gplot->cmddata);
/* Generate command data instructions */
if (gplot->title) { /* set title */
snprintf(buf, L_BUFSIZE, "set title '%s'", gplot->title);
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
if (gplot->xlabel) { /* set xlabel */
snprintf(buf, L_BUFSIZE, "set xlabel '%s'", gplot->xlabel);
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
if (gplot->ylabel) { /* set ylabel */
snprintf(buf, L_BUFSIZE, "set ylabel '%s'", gplot->ylabel);
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
/* Set terminal type and output */
if (gplot->outformat == GPLOT_PNG) {
snprintf(buf, L_BUFSIZE, "set terminal png; set output '%s'",
gplot->outname);
} else if (gplot->outformat == GPLOT_PS) {
snprintf(buf, L_BUFSIZE, "set terminal postscript; set output '%s'",
gplot->outname);
} else if (gplot->outformat == GPLOT_EPS) {
snprintf(buf, L_BUFSIZE,
"set terminal postscript eps; set output '%s'",
gplot->outname);
} else if (gplot->outformat == GPLOT_LATEX) {
snprintf(buf, L_BUFSIZE, "set terminal latex; set output '%s'",
gplot->outname);
}
sarrayAddString(gplot->cmddata, buf, L_COPY);
if (gplot->scaling == GPLOT_LOG_SCALE_X ||
gplot->scaling == GPLOT_LOG_SCALE_X_Y) {
snprintf(buf, L_BUFSIZE, "set logscale x");
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
if (gplot->scaling == GPLOT_LOG_SCALE_Y ||
gplot->scaling == GPLOT_LOG_SCALE_X_Y) {
snprintf(buf, L_BUFSIZE, "set logscale y");
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
nplots = sarrayGetCount(gplot->datanames);
for (i = 0; i < nplots; i++) {
plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY);
dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY);
numaGetIValue(gplot->plotstyles, i, &plotstyle);
if (nplots == 1) {
snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s",
dataname, plottitle, gplotstylenames[plotstyle]);
} else {
if (i == 0)
snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s, \\",
dataname, plottitle, gplotstylenames[plotstyle]);
else if (i < nplots - 1)
snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s, \\",
dataname, plottitle, gplotstylenames[plotstyle]);
else
snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s",
dataname, plottitle, gplotstylenames[plotstyle]);
}
sarrayAddString(gplot->cmddata, buf, L_COPY);
}
/* Write command data to file */
cmdstr = sarrayToString(gplot->cmddata, 1);
if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) {
LEPT_FREE(cmdstr);
return ERROR_INT("cmd stream not opened", procName, 1);
}
fwrite(cmdstr, 1, strlen(cmdstr), fp);
fclose(fp);
LEPT_FREE(cmdstr);
return 0;
}
| 169,325 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip,
impeg2d_video_decode_op_t *ps_op)
{
UWORD32 u4_bits_read;
dec_state_t *ps_dec;
ps_dec = (dec_state_t *)pv_dec;
ps_op->s_ivd_video_decode_op_t.u4_error_code = 0;
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream),ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer,
ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes);
{
{
IMPEG2D_ERROR_CODES_T e_error;
e_error = impeg2d_process_video_header(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0)
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE);
return;
}
}
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size;
ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0;
/* MOD */
ps_dec->u2_header_done = 1;
}
}
Commit Message: Fix in handling header decode errors
If header decode was unsuccessful, do not try decoding a frame
Also, initialize pic_wd, pic_ht for reinitialization when
decoder is created with smaller dimensions
Bug: 28886651
Bug: 35219737
Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50
(cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27)
(cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4)
CWE ID: CWE-119 | void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip,
impeg2d_video_decode_op_t *ps_op)
{
UWORD32 u4_bits_read;
dec_state_t *ps_dec;
ps_dec = (dec_state_t *)pv_dec;
ps_op->s_ivd_video_decode_op_t.u4_error_code = 0;
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream),ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer,
ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes);
{
{
IMPEG2D_ERROR_CODES_T e_error;
e_error = impeg2d_process_video_header(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0)
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0;
ps_dec->u2_header_done = 0;
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width;
}
impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE);
return;
}
}
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size;
ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0;
/* MOD */
ps_dec->u2_header_done = 1;
}
}
| 174,034 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaControlVolumeSliderElement::defaultEventHandler(Event* event) {
if (event->isMouseEvent() &&
toMouseEvent(event)->button() !=
static_cast<short>(WebPointerProperties::Button::Left))
return;
if (!isConnected() || !document().isActive())
return;
MediaControlInputElement::defaultEventHandler(event);
if (event->type() == EventTypeNames::mouseover ||
event->type() == EventTypeNames::mouseout ||
event->type() == EventTypeNames::mousemove)
return;
if (event->type() == EventTypeNames::mousedown)
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.VolumeChangeBegin"));
if (event->type() == EventTypeNames::mouseup)
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.VolumeChangeEnd"));
double volume = value().toDouble();
mediaElement().setVolume(volume);
mediaElement().setMuted(false);
}
Commit Message: Fixed volume slider element event handling
MediaControlVolumeSliderElement::defaultEventHandler has making
redundant calls to setVolume() & setMuted() on mouse activity. E.g. if
a mouse click changed the slider position, the above calls were made 4
times, once for each of these events: mousedown, input, mouseup,
DOMActive, click. This crack got exposed when PointerEvents are enabled
by default on M55, adding pointermove, pointerdown & pointerup to the
list.
This CL fixes the code to trigger the calls to setVolume() & setMuted()
only when the slider position is changed. Also added pointer events to
certain lists of mouse events in the code.
BUG=677900
Review-Url: https://codereview.chromium.org/2622273003
Cr-Commit-Position: refs/heads/master@{#446032}
CWE ID: CWE-119 | void MediaControlVolumeSliderElement::defaultEventHandler(Event* event) {
if (!isConnected() || !document().isActive())
return;
MediaControlInputElement::defaultEventHandler(event);
if (event->type() == EventTypeNames::mousedown)
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.VolumeChangeBegin"));
if (event->type() == EventTypeNames::mouseup)
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.VolumeChangeEnd"));
if (event->type() == EventTypeNames::input) {
double volume = value().toDouble();
mediaElement().setVolume(volume);
mediaElement().setMuted(false);
}
}
| 171,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: static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->abort) return FALSE;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
Commit Message:
CWE ID: CWE-20 | static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
| 165,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ~0;
args->count = ntohl(*p++);
args->count = min_t(u32, args->count, PAGE_SIZE);
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ~0;
args->count = ntohl(*p++);
if (!xdr_argsize_check(rqstp, p))
return 0;
args->count = min_t(u32, args->count, PAGE_SIZE);
args->buffer = page_address(*(rqstp->rq_next_page++));
return 1;
}
| 168,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
/* ext4_handle_valid() assumes a valid handle_t pointer */
if (handle && !ext4_handle_valid(handle))
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (sbi->s_journal && !handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
Commit Message: ext4: make orphan functions be no-op in no-journal mode
Instead of checking whether the handle is valid, we check if journal
is enabled. This avoids taking the s_orphan_lock mutex in all cases
when there is no journal in use, including the error paths where
ext4_orphan_del() is called with a handle set to NULL.
Signed-off-by: Anatol Pomozov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: CWE-20 | int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!EXT4_SB(inode->i_sb)->s_journal)
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
| 166,582 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)
CWE ID: CWE-787 | opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
/* If the declared file size is > 10 MB, check that the file is big */
/* enough to avoid excessive memory allocations */
if (image_height != 0 && image_width > 10000000 / image_height / numcomps) {
char ch;
OPJ_UINT64 expected_file_size =
(OPJ_UINT64)image_width * image_height * numcomps;
long curpos = ftell(f);
if (expected_file_size > (OPJ_UINT64)INT_MAX) {
expected_file_size = (OPJ_UINT64)INT_MAX;
}
fseek(f, (long)expected_file_size - 1, SEEK_SET);
if (fread(&ch, 1, 1, f) != 1) {
fclose(f);
return NULL;
}
fseek(f, curpos, SEEK_SET);
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
| 167,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ,
krb5_db_entry **server_ptr, const char **status)
{
krb5_error_code retval;
krb5_principal *plist = NULL, *pl2;
krb5_data tmp;
krb5_db_entry *server = NULL;
*server_ptr = NULL;
assert(is_cross_tgs_principal(princ));
if ((retval = krb5_walk_realm_tree(kdc_context,
krb5_princ_realm(kdc_context, princ),
krb5_princ_component(kdc_context, princ, 1),
&plist, KRB5_REALM_BRANCH_CHAR))) {
goto cleanup;
}
/* move to the end */
for (pl2 = plist; *pl2; pl2++);
/* the first entry in this array is for krbtgt/local@local, so we
ignore it */
while (--pl2 > plist) {
tmp = *krb5_princ_realm(kdc_context, *pl2);
krb5_princ_set_realm(kdc_context, *pl2,
krb5_princ_realm(kdc_context, tgs_server));
retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status);
krb5_princ_set_realm(kdc_context, *pl2, &tmp);
if (retval == KRB5_KDB_NOENTRY)
continue;
else if (retval)
goto cleanup;
log_tgs_alt_tgt(kdc_context, server->princ);
*server_ptr = server;
server = NULL;
goto cleanup;
}
cleanup:
if (retval != 0)
*status = "UNKNOWN_SERVER";
krb5_free_realm_tree(kdc_context, plist);
krb5_db_free_principal(kdc_context, server);
return retval;
}
Commit Message: KDC null deref due to referrals [CVE-2013-1417]
An authenticated remote client can cause a KDC to crash by making a
valid TGS-REQ to a KDC serving a realm with a single-component name.
The process_tgs_req() function dereferences a null pointer because an
unusual failure condition causes a helper function to return success.
While attempting to provide cross-realm referrals for host-based
service principals, the find_referral_tgs() function could return a
TGS principal for a zero-length realm name (indicating that the
hostname in the service principal has no known realm associated with
it).
Subsequently, the find_alternate_tgs() function would attempt to
construct a path to this empty-string realm, and return success along
with a null pointer in its output parameter. This happens because
krb5_walk_realm_tree() returns a list of length one when it attempts
to construct a transit path between a single-component realm and the
empty-string realm. This list causes a loop in find_alternate_tgs()
to iterate over zero elements, resulting in the unexpected output of a
null pointer, which process_tgs_req() proceeds to dereference because
there is no error condition.
Add an error condition to find_referral_tgs() when
krb5_get_host_realm() returns an empty realm name. Also add an error
condition to find_alternate_tgs() to handle the length-one output from
krb5_walk_realm_tree().
The vulnerable configuration is not likely to arise in practice.
(Realm names that have a single component are likely to be test
realms.) Releases prior to krb5-1.11 are not vulnerable.
Thanks to Sol Jerome for reporting this problem.
CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
(cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0)
ticket: 7668
version_fixed: 1.11.4
status: resolved
CWE ID: CWE-20 | find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ,
krb5_db_entry **server_ptr, const char **status)
{
krb5_error_code retval;
krb5_principal *plist = NULL, *pl2;
krb5_data tmp;
krb5_db_entry *server = NULL;
*server_ptr = NULL;
assert(is_cross_tgs_principal(princ));
if ((retval = krb5_walk_realm_tree(kdc_context,
krb5_princ_realm(kdc_context, princ),
krb5_princ_component(kdc_context, princ, 1),
&plist, KRB5_REALM_BRANCH_CHAR))) {
goto cleanup;
}
/* move to the end */
for (pl2 = plist; *pl2; pl2++);
/* the first entry in this array is for krbtgt/local@local, so we
ignore it */
while (--pl2 > plist) {
tmp = *krb5_princ_realm(kdc_context, *pl2);
krb5_princ_set_realm(kdc_context, *pl2,
krb5_princ_realm(kdc_context, tgs_server));
retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status);
krb5_princ_set_realm(kdc_context, *pl2, &tmp);
if (retval == KRB5_KDB_NOENTRY)
continue;
else if (retval)
goto cleanup;
log_tgs_alt_tgt(kdc_context, server->princ);
*server_ptr = server;
server = NULL;
goto cleanup;
}
cleanup:
if (retval == 0 && server_ptr == NULL)
retval = KRB5_KDB_NOENTRY;
if (retval != 0)
*status = "UNKNOWN_SERVER";
krb5_free_realm_tree(kdc_context, plist);
krb5_db_free_principal(kdc_context, server);
return retval;
}
| 166,130 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UpdatePropertyCallback(IBusPanelService* panel,
IBusProperty* ibus_prop,
gpointer user_data) {
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->UpdateProperty(ibus_prop);
}
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 | static void UpdatePropertyCallback(IBusPanelService* panel,
void UpdateProperty(IBusPanelService* panel, IBusProperty* ibus_prop) {
VLOG(1) << "UpdateProperty";
DCHECK(ibus_prop);
// You can call
// LOG(INFO) << "\n" << PrintProp(ibus_prop, 0);
// here to dump |ibus_prop|.
ImePropertyList prop_list; // our representation.
if (!FlattenProperty(ibus_prop, &prop_list)) {
// Don't update the UI on errors.
LOG(ERROR) << "Malformed properties are detected";
return;
}
// Notify the change.
if (!prop_list.empty()) {
FOR_EACH_OBSERVER(Observer, observers_,
OnUpdateImeProperty(prop_list));
}
}
| 170,551 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int SSL_library_init(void)
{
#ifndef OPENSSL_NO_DES
EVP_add_cipher(EVP_des_cbc());
EVP_add_cipher(EVP_des_ede3_cbc());
#endif
#ifndef OPENSSL_NO_IDEA
EVP_add_cipher(EVP_idea_cbc());
#endif
#ifndef OPENSSL_NO_RC4
EVP_add_cipher(EVP_rc4());
#if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__))
EVP_add_cipher(EVP_rc4_hmac_md5());
#endif
#endif
#ifndef OPENSSL_NO_RC2
EVP_add_cipher(EVP_rc2_cbc());
/* Not actually used for SSL/TLS but this makes PKCS#12 work
* if an application only calls SSL_library_init().
*/
EVP_add_cipher(EVP_rc2_40_cbc());
#endif
#ifndef OPENSSL_NO_AES
EVP_add_cipher(EVP_aes_128_cbc());
EVP_add_cipher(EVP_aes_192_cbc());
EVP_add_cipher(EVP_aes_256_cbc());
EVP_add_cipher(EVP_aes_128_gcm());
EVP_add_cipher(EVP_aes_256_gcm());
#if 0 /* Disabled because of timing side-channel leaks. */
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)
EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());
EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());
#endif
#endif
#endif
#ifndef OPENSSL_NO_CAMELLIA
#endif
#ifndef OPENSSL_NO_CAMELLIA
EVP_add_cipher(EVP_camellia_128_cbc());
EVP_add_cipher(EVP_camellia_256_cbc());
#endif
#ifndef OPENSSL_NO_SEED
EVP_add_cipher(EVP_seed_cbc());
#endif
#ifndef OPENSSL_NO_MD5
EVP_add_digest(EVP_md5());
EVP_add_digest_alias(SN_md5,"ssl2-md5");
EVP_add_digest_alias(SN_md5,"ssl3-md5");
#endif
#ifndef OPENSSL_NO_SHA
EVP_add_digest(EVP_sha1()); /* RSA with sha1 */
EVP_add_digest_alias(SN_sha1,"ssl3-sha1");
EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA);
#endif
#ifndef OPENSSL_NO_SHA256
EVP_add_digest(EVP_sha224());
EVP_add_digest(EVP_sha256());
#endif
#ifndef OPENSSL_NO_SHA512
EVP_add_digest(EVP_sha384());
EVP_add_digest(EVP_sha512());
#endif
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA)
EVP_add_digest(EVP_dss1()); /* DSA with sha1 */
EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2);
EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1");
EVP_add_digest_alias(SN_dsaWithSHA1,"dss1");
#endif
#ifndef OPENSSL_NO_ECDSA
EVP_add_digest(EVP_ecdsa());
#endif
/* If you want support for phased out ciphers, add the following */
#if 0
EVP_add_digest(EVP_sha());
EVP_add_digest(EVP_dss());
#endif
#ifndef OPENSSL_NO_COMP
/* This will initialise the built-in compression algorithms.
The value returned is a STACK_OF(SSL_COMP), but that can
be discarded safely */
(void)SSL_COMP_get_compression_methods();
#endif
/* initialize cipher/digest methods table */
ssl_load_ciphers();
return(1);
}
Commit Message:
CWE ID: CWE-310 | int SSL_library_init(void)
{
#ifndef OPENSSL_NO_DES
EVP_add_cipher(EVP_des_cbc());
EVP_add_cipher(EVP_des_ede3_cbc());
#endif
#ifndef OPENSSL_NO_IDEA
EVP_add_cipher(EVP_idea_cbc());
#endif
#ifndef OPENSSL_NO_RC4
EVP_add_cipher(EVP_rc4());
#if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__))
EVP_add_cipher(EVP_rc4_hmac_md5());
#endif
#endif
#ifndef OPENSSL_NO_RC2
EVP_add_cipher(EVP_rc2_cbc());
/* Not actually used for SSL/TLS but this makes PKCS#12 work
* if an application only calls SSL_library_init().
*/
EVP_add_cipher(EVP_rc2_40_cbc());
#endif
#ifndef OPENSSL_NO_AES
EVP_add_cipher(EVP_aes_128_cbc());
EVP_add_cipher(EVP_aes_192_cbc());
EVP_add_cipher(EVP_aes_256_cbc());
EVP_add_cipher(EVP_aes_128_gcm());
EVP_add_cipher(EVP_aes_256_gcm());
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)
EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());
EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());
#endif
#endif
#ifndef OPENSSL_NO_CAMELLIA
#endif
#ifndef OPENSSL_NO_CAMELLIA
EVP_add_cipher(EVP_camellia_128_cbc());
EVP_add_cipher(EVP_camellia_256_cbc());
#endif
#ifndef OPENSSL_NO_SEED
EVP_add_cipher(EVP_seed_cbc());
#endif
#ifndef OPENSSL_NO_MD5
EVP_add_digest(EVP_md5());
EVP_add_digest_alias(SN_md5,"ssl2-md5");
EVP_add_digest_alias(SN_md5,"ssl3-md5");
#endif
#ifndef OPENSSL_NO_SHA
EVP_add_digest(EVP_sha1()); /* RSA with sha1 */
EVP_add_digest_alias(SN_sha1,"ssl3-sha1");
EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA);
#endif
#ifndef OPENSSL_NO_SHA256
EVP_add_digest(EVP_sha224());
EVP_add_digest(EVP_sha256());
#endif
#ifndef OPENSSL_NO_SHA512
EVP_add_digest(EVP_sha384());
EVP_add_digest(EVP_sha512());
#endif
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA)
EVP_add_digest(EVP_dss1()); /* DSA with sha1 */
EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2);
EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1");
EVP_add_digest_alias(SN_dsaWithSHA1,"dss1");
#endif
#ifndef OPENSSL_NO_ECDSA
EVP_add_digest(EVP_ecdsa());
#endif
/* If you want support for phased out ciphers, add the following */
#if 0
EVP_add_digest(EVP_sha());
EVP_add_digest(EVP_dss());
#endif
#ifndef OPENSSL_NO_COMP
/* This will initialise the built-in compression algorithms.
The value returned is a STACK_OF(SSL_COMP), but that can
be discarded safely */
(void)SSL_COMP_get_compression_methods();
#endif
/* initialize cipher/digest methods table */
ssl_load_ciphers();
return(1);
}
| 164,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cg_mkdir(const char *path, mode_t mode)
{
struct fuse_context *fc = fuse_get_context();
char *fpath = NULL, *path1, *cgdir = NULL, *controller;
const char *cgroup;
int ret;
if (!fc)
return -EIO;
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EINVAL;
cgroup = find_cgroup_in_path(path);
if (!cgroup)
return -EINVAL;
get_cgdir_and_path(cgroup, &cgdir, &fpath);
if (!fpath)
path1 = "/";
else
path1 = cgdir;
if (!fc_may_access(fc, controller, path1, NULL, O_RDWR)) {
ret = -EACCES;
goto out;
}
if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) {
ret = -EACCES;
goto out;
}
ret = cgfs_create(controller, cgroup, fc->uid, fc->gid);
printf("cgfs_create returned %d for %s %s\n", ret, controller, cgroup);
out:
free(cgdir);
return ret;
}
Commit Message: Fix checking of parent directories
Taken from the justification in the launchpad bug:
To a task in freezer cgroup /a/b/c/d, it should appear that there are no
cgroups other than its descendents. Since this is a filesystem, we must have
the parent directories, but each parent cgroup should only contain the child
which the task can see.
So, when this task looks at /a/b, it should see only directory 'c' and no
files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already
exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x
exists or not. Opening /a/b/tasks should result in -ENOENT.
The caller_may_see_dir checks specifically whether a task may see a cgroup
directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing
opendir('/a/b/c/d').
caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at
/a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the
task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only)
directory which he can see in the path - 'c'.
Beyond this, regular DAC permissions should apply, with the
root-in-user-namespace privilege over its mapped uids being respected. The
fc_may_access check does this check for both directories and files.
This is CVE-2015-1342 (LP: #1508481)
Signed-off-by: Serge Hallyn <[email protected]>
CWE ID: CWE-264 | int cg_mkdir(const char *path, mode_t mode)
{
struct fuse_context *fc = fuse_get_context();
char *fpath = NULL, *path1, *cgdir = NULL, *controller, *next = NULL;
const char *cgroup;
int ret;
if (!fc)
return -EIO;
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EINVAL;
cgroup = find_cgroup_in_path(path);
if (!cgroup)
return -EINVAL;
get_cgdir_and_path(cgroup, &cgdir, &fpath);
if (!fpath)
path1 = "/";
else
path1 = cgdir;
if (!caller_is_in_ancestor(fc->pid, controller, path1, &next)) {
if (fpath && strcmp(next, fpath) == 0)
ret = -EEXIST;
else
ret = -ENOENT;
goto out;
}
if (!fc_may_access(fc, controller, path1, NULL, O_RDWR)) {
ret = -EACCES;
goto out;
}
if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) {
ret = -EACCES;
goto out;
}
ret = cgfs_create(controller, cgroup, fc->uid, fc->gid);
printf("cgfs_create returned %d for %s %s\n", ret, controller, cgroup);
out:
free(cgdir);
free(next);
return ret;
}
| 166,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 * gdImageGifPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
gdImageGifCtx (im, out);
rv = gdDPExtractData (out, size);
out->gd_free (out);
return rv;
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415 | void * gdImageGifPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
if (!_gdImageGifCtx(im, out)) {
rv = gdDPExtractData(out, size);
} else {
rv = NULL;
}
out->gd_free (out);
return rv;
}
| 169,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(ctcptype);
Q_UNUSED(target);
if(!_ignoreListManager->ctcpMatch(prefix, network()->networkName())) {
QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix);
if(!param.isEmpty())
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
}
Commit Message:
CWE ID: CWE-399 | void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) {
Q_UNUSED(ctcptype);
Q_UNUSED(target);
Q_UNUSED(reply);
QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix);
if(!param.isEmpty())
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
| 164,876 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InputMethodController::FinishComposingText(
ConfirmCompositionBehavior confirm_behavior) {
if (!HasComposition())
return false;
const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition());
const String& composing = ComposingText();
if (confirm_behavior == kKeepSelection) {
const bool is_handle_visible = GetFrame().Selection().IsHandleVisible();
const PlainTextRange& old_offsets = GetSelectionOffsets();
Editor::RevealSelectionScope reveal_selection_scope(&GetEditor());
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
DispatchCompositionEndEvent(GetFrame(), composing);
}
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& old_selection_range =
EphemeralRangeForOffsets(old_offsets);
if (old_selection_range.IsNull())
return false;
const SelectionInDOMTree& selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtent(old_selection_range)
.SetIsHandleVisible(is_handle_visible)
.Build();
GetFrame().Selection().SetSelection(
selection,
SetSelectionData::Builder().SetShouldCloseTyping(true).Build());
return true;
}
Element* root_editable_element =
GetFrame()
.Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.RootEditableElement();
if (!root_editable_element)
return false;
PlainTextRange composition_range =
PlainTextRange::Create(*root_editable_element, *composition_range_);
if (composition_range.IsNull())
return false;
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
}
if (!MoveCaret(composition_range.End()))
return false;
DispatchCompositionEndEvent(GetFrame(), composing);
return true;
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119 | bool InputMethodController::FinishComposingText(
ConfirmCompositionBehavior confirm_behavior) {
if (!HasComposition())
return false;
const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition());
const String& composing = ComposingText();
if (confirm_behavior == kKeepSelection) {
const bool is_handle_visible = GetFrame().Selection().IsHandleVisible();
const PlainTextRange& old_offsets = GetSelectionOffsets();
Editor::RevealSelectionScope reveal_selection_scope(&GetEditor());
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
DispatchCompositionEndEvent(GetFrame(), composing);
}
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& old_selection_range =
EphemeralRangeForOffsets(old_offsets);
if (old_selection_range.IsNull())
return false;
const SelectionInDOMTree& selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtent(old_selection_range)
.Build();
GetFrame().Selection().SetSelection(
selection, SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldShowHandle(is_handle_visible)
.Build());
return true;
}
Element* root_editable_element =
GetFrame()
.Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.RootEditableElement();
if (!root_editable_element)
return false;
PlainTextRange composition_range =
PlainTextRange::Create(*root_editable_element, *composition_range_);
if (composition_range.IsNull())
return false;
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
}
if (!MoveCaret(composition_range.End()))
return false;
DispatchCompositionEndEvent(GetFrame(), composing);
return true;
}
| 171,761 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext4_xattr_create_cache(char *name)
{
return mb_cache_create(name, HASH_BUCKET_BITS);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext4_xattr_create_cache(char *name)
struct mb2_cache *
ext4_xattr_create_cache(void)
{
return mb2_cache_create(HASH_BUCKET_BITS);
}
| 169,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
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));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *ReadSCRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char zxscr[6144];
char zxattr[768];
int octetnr;
int octetline;
int zoneline;
int zonenr;
int octet_val;
int attr_nr;
int pix;
int piy;
int binar[8];
int attrbin[8];
int *pbin;
int *abin;
int z;
int one_nr;
int ink;
int paper;
int bright;
unsigned char colour_palette[] = {
0, 0, 0,
0, 0,192,
192, 0, 0,
192, 0,192,
0,192, 0,
0,192,192,
192,192, 0,
192,192,192,
0, 0, 0,
0, 0,255,
255, 0, 0,
255, 0,255,
0,255, 0,
0,255,255,
255,255, 0,
255,255,255
};
Image
*image;
MagickBooleanType
status;
register PixelPacket
*q;
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->columns = 256;
image->rows = 192;
count=ReadBlob(image,6144,(unsigned char *) zxscr);
(void) count;
count=ReadBlob(image,768,(unsigned char *) zxattr);
for(zonenr=0;zonenr<3;zonenr++)
{
for(zoneline=0;zoneline<8;zoneline++)
{
for(octetline=0;octetline<8;octetline++)
{
for(octetnr=(zoneline*32);octetnr<((zoneline*32)+32);octetnr++)
{
octet_val = zxscr[octetnr+(256*octetline)+(zonenr*2048)];
attr_nr = zxattr[octetnr+(256*zonenr)];
pix = (((8*octetnr)-(256*zoneline)));
piy = ((octetline+(8*zoneline)+(zonenr*64)));
pbin = binar;
abin = attrbin;
one_nr=1;
for(z=0;z<8;z++)
{
if(octet_val&one_nr)
{
*pbin = 1;
} else {
*pbin = 0;
}
one_nr=one_nr*2;
pbin++;
}
one_nr = 1;
for(z=0;z<8;z++)
{
if(attr_nr&one_nr)
{
*abin = 1;
} else {
*abin = 0;
}
one_nr=one_nr*2;
abin++;
}
ink = (attrbin[0]+(2*attrbin[1])+(4*attrbin[2]));
paper = (attrbin[3]+(2*attrbin[4])+(4*attrbin[5]));
bright = attrbin[6];
if(bright) { ink=ink+8; paper=paper+8; }
for(z=7;z>-1;z--)
{
q=QueueAuthenticPixels(image,pix,piy,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
if(binar[z])
{
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*ink]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*ink)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*ink)]));
} else {
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*paper]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*paper)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*paper)]));
}
pix++;
}
}
}
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadSCRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char zxscr[6144];
char zxattr[768];
int octetnr;
int octetline;
int zoneline;
int zonenr;
int octet_val;
int attr_nr;
int pix;
int piy;
int binar[8];
int attrbin[8];
int *pbin;
int *abin;
int z;
int one_nr;
int ink;
int paper;
int bright;
unsigned char colour_palette[] = {
0, 0, 0,
0, 0,192,
192, 0, 0,
192, 0,192,
0,192, 0,
0,192,192,
192,192, 0,
192,192,192,
0, 0, 0,
0, 0,255,
255, 0, 0,
255, 0,255,
0,255, 0,
0,255,255,
255,255, 0,
255,255,255
};
Image
*image;
MagickBooleanType
status;
register PixelPacket
*q;
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->columns = 256;
image->rows = 192;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
count=ReadBlob(image,6144,(unsigned char *) zxscr);
(void) count;
count=ReadBlob(image,768,(unsigned char *) zxattr);
for(zonenr=0;zonenr<3;zonenr++)
{
for(zoneline=0;zoneline<8;zoneline++)
{
for(octetline=0;octetline<8;octetline++)
{
for(octetnr=(zoneline*32);octetnr<((zoneline*32)+32);octetnr++)
{
octet_val = zxscr[octetnr+(256*octetline)+(zonenr*2048)];
attr_nr = zxattr[octetnr+(256*zonenr)];
pix = (((8*octetnr)-(256*zoneline)));
piy = ((octetline+(8*zoneline)+(zonenr*64)));
pbin = binar;
abin = attrbin;
one_nr=1;
for(z=0;z<8;z++)
{
if(octet_val&one_nr)
{
*pbin = 1;
} else {
*pbin = 0;
}
one_nr=one_nr*2;
pbin++;
}
one_nr = 1;
for(z=0;z<8;z++)
{
if(attr_nr&one_nr)
{
*abin = 1;
} else {
*abin = 0;
}
one_nr=one_nr*2;
abin++;
}
ink = (attrbin[0]+(2*attrbin[1])+(4*attrbin[2]));
paper = (attrbin[3]+(2*attrbin[4])+(4*attrbin[5]));
bright = attrbin[6];
if(bright) { ink=ink+8; paper=paper+8; }
for(z=7;z>-1;z--)
{
q=QueueAuthenticPixels(image,pix,piy,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
if(binar[z])
{
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*ink]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*ink)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*ink)]));
} else {
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*paper]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*paper)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*paper)]));
}
pix++;
}
}
}
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex
Reported by Google Autofuzz team
CWE ID: CWE-787 | int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
| 168,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::GetEntryCount() const
{
return m_entries_count;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Cluster::GetEntryCount() const
| 174,318 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_da3_fixhashpath(
struct xfs_da_state *state,
struct xfs_da_state_path *path)
{
struct xfs_da_state_blk *blk;
struct xfs_da_intnode *node;
struct xfs_da_node_entry *btree;
xfs_dahash_t lasthash=0;
int level;
int count;
struct xfs_inode *dp = state->args->dp;
trace_xfs_da_fixhashpath(state->args);
level = path->active-1;
blk = &path->blk[ level ];
switch (blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DIR2_LEAFN_MAGIC:
lasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DA_NODE_MAGIC:
lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
}
for (blk--, level--; level >= 0; blk--, level--) {
struct xfs_da3_icnode_hdr nodehdr;
node = blk->bp->b_addr;
dp->d_ops->node_hdr_from_disk(&nodehdr, node);
btree = dp->d_ops->node_tree_p(node);
if (be32_to_cpu(btree->hashval) == lasthash)
break;
blk->hashval = lasthash;
btree[blk->index].hashval = cpu_to_be32(lasthash);
xfs_trans_log_buf(state->args->trans, blk->bp,
XFS_DA_LOGRANGE(node, &btree[blk->index],
sizeof(*btree)));
lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);
}
}
Commit Message: xfs: fix directory hash ordering bug
Commit f5ea1100 ("xfs: add CRCs to dir2/da node blocks") introduced
in 3.10 incorrectly converted the btree hash index array pointer in
xfs_da3_fixhashpath(). It resulted in the the current hash always
being compared against the first entry in the btree rather than the
current block index into the btree block's hash entry array. As a
result, it was comparing the wrong hashes, and so could misorder the
entries in the btree.
For most cases, this doesn't cause any problems as it requires hash
collisions to expose the ordering problem. However, when there are
hash collisions within a directory there is a very good probability
that the entries will be ordered incorrectly and that actually
matters when duplicate hashes are placed into or removed from the
btree block hash entry array.
This bug results in an on-disk directory corruption and that results
in directory verifier functions throwing corruption warnings into
the logs. While no data or directory entries are lost, access to
them may be compromised, and attempts to remove entries from a
directory that has suffered from this corruption may result in a
filesystem shutdown. xfs_repair will fix the directory hash
ordering without data loss occuring.
[dchinner: wrote useful a commit message]
cc: <[email protected]>
Reported-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Mark Tinguely <[email protected]>
Reviewed-by: Ben Myers <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-399 | xfs_da3_fixhashpath(
struct xfs_da_state *state,
struct xfs_da_state_path *path)
{
struct xfs_da_state_blk *blk;
struct xfs_da_intnode *node;
struct xfs_da_node_entry *btree;
xfs_dahash_t lasthash=0;
int level;
int count;
struct xfs_inode *dp = state->args->dp;
trace_xfs_da_fixhashpath(state->args);
level = path->active-1;
blk = &path->blk[ level ];
switch (blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DIR2_LEAFN_MAGIC:
lasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DA_NODE_MAGIC:
lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);
if (count == 0)
return;
break;
}
for (blk--, level--; level >= 0; blk--, level--) {
struct xfs_da3_icnode_hdr nodehdr;
node = blk->bp->b_addr;
dp->d_ops->node_hdr_from_disk(&nodehdr, node);
btree = dp->d_ops->node_tree_p(node);
if (be32_to_cpu(btree[blk->index].hashval) == lasthash)
break;
blk->hashval = lasthash;
btree[blk->index].hashval = cpu_to_be32(lasthash);
xfs_trans_log_buf(state->args->trans, blk->bp,
XFS_DA_LOGRANGE(node, &btree[blk->index],
sizeof(*btree)));
lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);
}
}
| 166,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cliprdr_process(STREAM s)
{
uint16 type, status;
uint32 length, format;
uint8 *data;
in_uint16_le(s, type);
in_uint16_le(s, status);
in_uint32_le(s, length);
data = s->p;
logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status,
length);
if (status == CLIPRDR_ERROR)
{
switch (type)
{
case CLIPRDR_FORMAT_ACK:
/* FIXME: We seem to get this when we send an announce while the server is
still processing a paste. Try sending another announce. */
cliprdr_send_native_format_announce(last_formats,
last_formats_length);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_request_failed();
break;
default:
logger(Clipboard, Warning,
"cliprdr_process(), unhandled error (type=%d)", type);
}
return;
}
switch (type)
{
case CLIPRDR_CONNECT:
ui_clip_sync();
break;
case CLIPRDR_FORMAT_ANNOUNCE:
ui_clip_format_announce(data, length);
cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0);
return;
case CLIPRDR_FORMAT_ACK:
break;
case CLIPRDR_DATA_REQUEST:
in_uint32_le(s, format);
ui_clip_request_data(format);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_handle_data(data, length);
break;
case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */
break;
default:
logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d",
type);
}
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | cliprdr_process(STREAM s)
{
uint16 type, status;
uint32 length, format;
uint8 *data;
struct stream packet = *s;
in_uint16_le(s, type);
in_uint16_le(s, status);
in_uint32_le(s, length);
data = s->p;
logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status,
length);
if (!s_check_rem(s, length))
{
rdp_protocol_error("cliprdr_process(), consume of packet from stream would overrun", &packet);
}
if (status == CLIPRDR_ERROR)
{
switch (type)
{
case CLIPRDR_FORMAT_ACK:
/* FIXME: We seem to get this when we send an announce while the server is
still processing a paste. Try sending another announce. */
cliprdr_send_native_format_announce(last_formats,
last_formats_length);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_request_failed();
break;
default:
logger(Clipboard, Warning,
"cliprdr_process(), unhandled error (type=%d)", type);
}
return;
}
switch (type)
{
case CLIPRDR_CONNECT:
ui_clip_sync();
break;
case CLIPRDR_FORMAT_ANNOUNCE:
ui_clip_format_announce(data, length);
cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0);
return;
case CLIPRDR_FORMAT_ACK:
break;
case CLIPRDR_DATA_REQUEST:
in_uint32_le(s, format);
ui_clip_request_data(format);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_handle_data(data, length);
break;
case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */
break;
default:
logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d",
type);
}
}
| 169,796 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t BnGraphicBufferConsumer::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case ACQUIRE_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
BufferItem item;
int64_t presentWhen = data.readInt64();
status_t result = acquireBuffer(&item, presentWhen);
status_t err = reply->write(item);
if (err) return err;
reply->writeInt32(result);
return NO_ERROR;
} break;
case DETACH_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
int slot = data.readInt32();
int result = detachBuffer(slot);
reply->writeInt32(result);
return NO_ERROR;
} break;
case ATTACH_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
sp<GraphicBuffer> buffer = new GraphicBuffer();
data.read(*buffer.get());
int slot;
int result = attachBuffer(&slot, buffer);
reply->writeInt32(slot);
reply->writeInt32(result);
return NO_ERROR;
} break;
case RELEASE_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
int buf = data.readInt32();
uint64_t frameNumber = data.readInt64();
sp<Fence> releaseFence = new Fence();
status_t err = data.read(*releaseFence);
if (err) return err;
status_t result = releaseBuffer(buf, frameNumber,
EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence);
reply->writeInt32(result);
return NO_ERROR;
} break;
case CONSUMER_CONNECT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() );
bool controlledByApp = data.readInt32();
status_t result = consumerConnect(consumer, controlledByApp);
reply->writeInt32(result);
return NO_ERROR;
} break;
case CONSUMER_DISCONNECT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
status_t result = consumerDisconnect();
reply->writeInt32(result);
return NO_ERROR;
} break;
case GET_RELEASED_BUFFERS: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint64_t slotMask;
status_t result = getReleasedBuffers(&slotMask);
reply->writeInt64(slotMask);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_DEFAULT_BUFFER_SIZE: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t w = data.readInt32();
uint32_t h = data.readInt32();
status_t result = setDefaultBufferSize(w, h);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_DEFAULT_MAX_BUFFER_COUNT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t bufferCount = data.readInt32();
status_t result = setDefaultMaxBufferCount(bufferCount);
reply->writeInt32(result);
return NO_ERROR;
} break;
case DISABLE_ASYNC_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
status_t result = disableAsyncBuffer();
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_MAX_ACQUIRED_BUFFER_COUNT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t maxAcquiredBuffers = data.readInt32();
status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_CONSUMER_NAME: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
setConsumerName( data.readString8() );
return NO_ERROR;
} break;
case SET_DEFAULT_BUFFER_FORMAT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t defaultFormat = data.readInt32();
status_t result = setDefaultBufferFormat(defaultFormat);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_CONSUMER_USAGE_BITS: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t usage = data.readInt32();
status_t result = setConsumerUsageBits(usage);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_TRANSFORM_HINT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t hint = data.readInt32();
status_t result = setTransformHint(hint);
reply->writeInt32(result);
return NO_ERROR;
} break;
case DUMP: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
String8 result = data.readString8();
String8 prefix = data.readString8();
static_cast<IGraphicBufferConsumer*>(this)->dump(result, prefix);
reply->writeString8(result);
return NO_ERROR;
}
}
return BBinder::onTransact(code, data, reply, flags);
}
Commit Message: IGraphicBufferConsumer: fix ATTACH_BUFFER info leak
Bug: 26338113
Change-Id: I019c4df2c6adbc944122df96968ddd11a02ebe33
CWE ID: CWE-254 | status_t BnGraphicBufferConsumer::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case ACQUIRE_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
BufferItem item;
int64_t presentWhen = data.readInt64();
status_t result = acquireBuffer(&item, presentWhen);
status_t err = reply->write(item);
if (err) return err;
reply->writeInt32(result);
return NO_ERROR;
} break;
case DETACH_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
int slot = data.readInt32();
int result = detachBuffer(slot);
reply->writeInt32(result);
return NO_ERROR;
} break;
case ATTACH_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
sp<GraphicBuffer> buffer = new GraphicBuffer();
data.read(*buffer.get());
int slot = -1;
int result = attachBuffer(&slot, buffer);
reply->writeInt32(slot);
reply->writeInt32(result);
return NO_ERROR;
} break;
case RELEASE_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
int buf = data.readInt32();
uint64_t frameNumber = data.readInt64();
sp<Fence> releaseFence = new Fence();
status_t err = data.read(*releaseFence);
if (err) return err;
status_t result = releaseBuffer(buf, frameNumber,
EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence);
reply->writeInt32(result);
return NO_ERROR;
} break;
case CONSUMER_CONNECT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() );
bool controlledByApp = data.readInt32();
status_t result = consumerConnect(consumer, controlledByApp);
reply->writeInt32(result);
return NO_ERROR;
} break;
case CONSUMER_DISCONNECT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
status_t result = consumerDisconnect();
reply->writeInt32(result);
return NO_ERROR;
} break;
case GET_RELEASED_BUFFERS: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint64_t slotMask;
status_t result = getReleasedBuffers(&slotMask);
reply->writeInt64(slotMask);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_DEFAULT_BUFFER_SIZE: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t w = data.readInt32();
uint32_t h = data.readInt32();
status_t result = setDefaultBufferSize(w, h);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_DEFAULT_MAX_BUFFER_COUNT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t bufferCount = data.readInt32();
status_t result = setDefaultMaxBufferCount(bufferCount);
reply->writeInt32(result);
return NO_ERROR;
} break;
case DISABLE_ASYNC_BUFFER: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
status_t result = disableAsyncBuffer();
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_MAX_ACQUIRED_BUFFER_COUNT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t maxAcquiredBuffers = data.readInt32();
status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_CONSUMER_NAME: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
setConsumerName( data.readString8() );
return NO_ERROR;
} break;
case SET_DEFAULT_BUFFER_FORMAT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t defaultFormat = data.readInt32();
status_t result = setDefaultBufferFormat(defaultFormat);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_CONSUMER_USAGE_BITS: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t usage = data.readInt32();
status_t result = setConsumerUsageBits(usage);
reply->writeInt32(result);
return NO_ERROR;
} break;
case SET_TRANSFORM_HINT: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
uint32_t hint = data.readInt32();
status_t result = setTransformHint(hint);
reply->writeInt32(result);
return NO_ERROR;
} break;
case DUMP: {
CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
String8 result = data.readString8();
String8 prefix = data.readString8();
static_cast<IGraphicBufferConsumer*>(this)->dump(result, prefix);
reply->writeString8(result);
return NO_ERROR;
}
}
return BBinder::onTransact(code, data, reply, flags);
}
| 173,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == nameAttr) {
removeFromRadioButtonGroup();
m_name = value;
addToRadioButtonGroup();
HTMLTextFormControlElement::parseAttribute(name, value);
} else if (name == autocompleteAttr) {
if (equalIgnoringCase(value, "off"))
m_autocomplete = Off;
else {
if (value.isEmpty())
m_autocomplete = Uninitialized;
else
m_autocomplete = On;
}
} else if (name == typeAttr)
updateType();
else if (name == valueAttr) {
if (!hasDirtyValue()) {
updatePlaceholderVisibility(false);
setNeedsStyleRecalc();
}
setFormControlValueMatchesRenderer(false);
setNeedsValidityCheck();
m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress;
m_inputType->valueAttributeChanged();
} else if (name == checkedAttr) {
if (!m_parsingInProgress && m_reflectsCheckedAttribute) {
setChecked(!value.isNull());
m_reflectsCheckedAttribute = true;
}
} else if (name == maxlengthAttr)
parseMaxLengthAttribute(value);
else if (name == sizeAttr) {
int oldSize = m_size;
int valueAsInteger = value.toInt();
m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize;
if (m_size != oldSize && renderer())
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
} else if (name == altAttr)
m_inputType->altAttributeChanged();
else if (name == srcAttr)
m_inputType->srcAttributeChanged();
else if (name == usemapAttr || name == accesskeyAttr) {
} else if (name == onsearchAttr) {
setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value));
} else if (name == resultsAttr) {
int oldResults = m_maxResults;
m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
lazyReattachIfAttached();
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::ResultsAttribute);
} else if (name == incrementalAttr) {
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::IncrementalAttribute);
} else if (name == minAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MinAttribute);
} else if (name == maxAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MaxAttribute);
} else if (name == multipleAttr) {
m_inputType->multipleAttributeChanged();
setNeedsValidityCheck();
} else if (name == stepAttr) {
m_inputType->stepAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::StepAttribute);
} else if (name == patternAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PatternAttribute);
} else if (name == precisionAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PrecisionAttribute);
} else if (name == disabledAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->disabledAttributeChanged();
} else if (name == readonlyAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->readonlyAttributeChanged();
} else if (name == listAttr) {
m_hasNonEmptyList = !value.isEmpty();
if (m_hasNonEmptyList) {
resetListAttributeTargetObserver();
listAttributeTargetChanged();
}
UseCounter::count(document(), UseCounter::ListAttribute);
}
#if ENABLE(INPUT_SPEECH)
else if (name == webkitspeechAttr) {
if (renderer()) {
detach();
m_inputType->destroyShadowSubtree();
m_inputType->createShadowSubtree();
if (!attached())
attach();
} else {
m_inputType->destroyShadowSubtree();
m_inputType->createShadowSubtree();
}
setFormControlValueMatchesRenderer(false);
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
} else if (name == onwebkitspeechchangeAttr)
setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value));
#endif
else if (name == webkitdirectoryAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
}
else
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->attributeChanged();
}
Commit Message: Setting input.x-webkit-speech should not cause focus change
In r150866, we introduced element()->focus() in destroyShadowSubtree()
to retain focus on <input> when its type attribute gets changed.
But when x-webkit-speech attribute is changed, the element is detached
before calling destroyShadowSubtree() and element()->focus() failed
This patch moves detach() after destroyShadowSubtree() to fix the
problem.
BUG=243818
TEST=fast/forms/input-type-change-focusout.html
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/16084005
git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == nameAttr) {
removeFromRadioButtonGroup();
m_name = value;
addToRadioButtonGroup();
HTMLTextFormControlElement::parseAttribute(name, value);
} else if (name == autocompleteAttr) {
if (equalIgnoringCase(value, "off"))
m_autocomplete = Off;
else {
if (value.isEmpty())
m_autocomplete = Uninitialized;
else
m_autocomplete = On;
}
} else if (name == typeAttr)
updateType();
else if (name == valueAttr) {
if (!hasDirtyValue()) {
updatePlaceholderVisibility(false);
setNeedsStyleRecalc();
}
setFormControlValueMatchesRenderer(false);
setNeedsValidityCheck();
m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress;
m_inputType->valueAttributeChanged();
} else if (name == checkedAttr) {
if (!m_parsingInProgress && m_reflectsCheckedAttribute) {
setChecked(!value.isNull());
m_reflectsCheckedAttribute = true;
}
} else if (name == maxlengthAttr)
parseMaxLengthAttribute(value);
else if (name == sizeAttr) {
int oldSize = m_size;
int valueAsInteger = value.toInt();
m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize;
if (m_size != oldSize && renderer())
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
} else if (name == altAttr)
m_inputType->altAttributeChanged();
else if (name == srcAttr)
m_inputType->srcAttributeChanged();
else if (name == usemapAttr || name == accesskeyAttr) {
} else if (name == onsearchAttr) {
setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value));
} else if (name == resultsAttr) {
int oldResults = m_maxResults;
m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
lazyReattachIfAttached();
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::ResultsAttribute);
} else if (name == incrementalAttr) {
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::IncrementalAttribute);
} else if (name == minAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MinAttribute);
} else if (name == maxAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MaxAttribute);
} else if (name == multipleAttr) {
m_inputType->multipleAttributeChanged();
setNeedsValidityCheck();
} else if (name == stepAttr) {
m_inputType->stepAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::StepAttribute);
} else if (name == patternAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PatternAttribute);
} else if (name == precisionAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PrecisionAttribute);
} else if (name == disabledAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->disabledAttributeChanged();
} else if (name == readonlyAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->readonlyAttributeChanged();
} else if (name == listAttr) {
m_hasNonEmptyList = !value.isEmpty();
if (m_hasNonEmptyList) {
resetListAttributeTargetObserver();
listAttributeTargetChanged();
}
UseCounter::count(document(), UseCounter::ListAttribute);
}
#if ENABLE(INPUT_SPEECH)
else if (name == webkitspeechAttr) {
if (renderer()) {
m_inputType->destroyShadowSubtree();
detach();
m_inputType->createShadowSubtree();
if (!attached())
attach();
} else {
m_inputType->destroyShadowSubtree();
m_inputType->createShadowSubtree();
}
setFormControlValueMatchesRenderer(false);
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
} else if (name == onwebkitspeechchangeAttr)
setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value));
#endif
else if (name == webkitdirectoryAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
}
else
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->attributeChanged();
}
| 171,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LogoService::GetLogo(LogoCallbacks callbacks) {
if (!template_url_service_) {
RunCallbacksWithDisabled(std::move(callbacks));
return;
}
const TemplateURL* template_url =
template_url_service_->GetDefaultSearchProvider();
if (!template_url) {
RunCallbacksWithDisabled(std::move(callbacks));
return;
}
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
GURL logo_url;
if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) {
logo_url = GURL(
command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL));
} else {
#if defined(OS_ANDROID)
logo_url = template_url->logo_url();
#endif
}
GURL base_url;
GURL doodle_url;
const bool is_google = template_url->url_ref().HasGoogleBaseURLs(
template_url_service_->search_terms_data());
if (is_google) {
base_url =
GURL(template_url_service_->search_terms_data().GoogleBaseURLValue());
doodle_url = search_provider_logos::GetGoogleDoodleURL(base_url);
} else if (base::FeatureList::IsEnabled(features::kThirdPartyDoodles)) {
if (command_line->HasSwitch(switches::kThirdPartyDoodleURL)) {
doodle_url = GURL(
command_line->GetSwitchValueASCII(switches::kThirdPartyDoodleURL));
} else {
std::string override_url = base::GetFieldTrialParamValueByFeature(
features::kThirdPartyDoodles,
features::kThirdPartyDoodlesOverrideUrlParam);
if (!override_url.empty()) {
doodle_url = GURL(override_url);
} else {
doodle_url = template_url->doodle_url();
}
}
base_url = doodle_url.GetOrigin();
}
if (!logo_url.is_valid() && !doodle_url.is_valid()) {
RunCallbacksWithDisabled(std::move(callbacks));
return;
}
const bool use_fixed_logo = !doodle_url.is_valid();
if (!logo_tracker_) {
std::unique_ptr<LogoCache> logo_cache = std::move(logo_cache_for_test_);
if (!logo_cache) {
logo_cache = std::make_unique<LogoCache>(cache_directory_);
}
std::unique_ptr<base::Clock> clock = std::move(clock_for_test_);
if (!clock) {
clock = std::make_unique<base::DefaultClock>();
}
logo_tracker_ = std::make_unique<LogoTracker>(
request_context_getter_,
std::make_unique<LogoDelegateImpl>(std::move(image_decoder_)),
std::move(logo_cache), std::move(clock));
}
if (use_fixed_logo) {
logo_tracker_->SetServerAPI(
logo_url, base::Bind(&search_provider_logos::ParseFixedLogoResponse),
base::Bind(&search_provider_logos::UseFixedLogoUrl));
} else if (is_google) {
logo_tracker_->SetServerAPI(
doodle_url,
search_provider_logos::GetGoogleParseLogoResponseCallback(base_url),
search_provider_logos::GetGoogleAppendQueryparamsCallback(
use_gray_background_));
} else {
logo_tracker_->SetServerAPI(
doodle_url,
base::Bind(&search_provider_logos::GoogleNewParseLogoResponse,
base_url),
base::Bind(&search_provider_logos::GoogleNewAppendQueryparamsToLogoURL,
use_gray_background_));
}
logo_tracker_->GetLogo(std::move(callbacks));
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119 | void LogoService::GetLogo(LogoCallbacks callbacks) {
| 171,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 main(int argc, char *argv[]) {
struct mg_context *ctx;
base::AtExitManager exit;
base::WaitableEvent shutdown_event(false, false);
CommandLine::Init(argc, argv);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
#if defined(OS_POSIX)
signal(SIGPIPE, SIG_IGN);
#endif
srand((unsigned int)time(NULL));
chrome::RegisterPathProvider();
TestTimeouts::Initialize();
InitChromeDriverLogging(*cmd_line);
std::string port = "9515";
std::string root;
std::string url_base;
if (cmd_line->HasSwitch("port"))
port = cmd_line->GetSwitchValueASCII("port");
if (cmd_line->HasSwitch("root"))
root = cmd_line->GetSwitchValueASCII("root");
if (cmd_line->HasSwitch("url-base"))
url_base = cmd_line->GetSwitchValueASCII("url-base");
webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance();
manager->set_port(port);
manager->set_url_base(url_base);
ctx = mg_start();
if (!SetMongooseOptions(ctx, port, root)) {
mg_stop(ctx);
#if defined(OS_WIN)
return WSAEADDRINUSE;
#else
return EADDRINUSE;
#endif
}
webdriver::Dispatcher dispatcher(ctx, url_base);
webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty());
std::cout << "Started ChromeDriver" << std::endl
<< "port=" << port << std::endl;
if (root.length()) {
VLOG(1) << "Serving files from the current working directory";
}
shutdown_event.Wait();
mg_stop(ctx);
return (EXIT_SUCCESS);
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | int main(int argc, char *argv[]) {
struct mg_context *ctx;
base::AtExitManager exit;
base::WaitableEvent shutdown_event(false, false);
CommandLine::Init(argc, argv);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
#if defined(OS_POSIX)
signal(SIGPIPE, SIG_IGN);
#endif
srand((unsigned int)time(NULL));
chrome::RegisterPathProvider();
TestTimeouts::Initialize();
std::string port = "9515";
std::string root;
std::string url_base;
bool verbose = false;
if (cmd_line->HasSwitch("port"))
port = cmd_line->GetSwitchValueASCII("port");
if (cmd_line->HasSwitch("root"))
root = cmd_line->GetSwitchValueASCII("root");
if (cmd_line->HasSwitch("url-base"))
url_base = cmd_line->GetSwitchValueASCII("url-base");
// Whether or not to do verbose logging.
if (cmd_line->HasSwitch("verbose"))
verbose = true;
webdriver::InitWebDriverLogging(
verbose ? logging::LOG_INFO : logging::LOG_WARNING);
webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance();
manager->set_port(port);
manager->set_url_base(url_base);
ctx = mg_start();
if (!SetMongooseOptions(ctx, port, root)) {
mg_stop(ctx);
#if defined(OS_WIN)
return WSAEADDRINUSE;
#else
return EADDRINUSE;
#endif
}
webdriver::Dispatcher dispatcher(ctx, url_base);
webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty());
std::cout << "Started ChromeDriver" << std::endl
<< "port=" << port << std::endl;
if (root.length()) {
VLOG(1) << "Serving files from the current working directory";
}
shutdown_event.Wait();
mg_stop(ctx);
return (EXIT_SUCCESS);
}
| 170,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_monitor_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_monitor_header {
uint8_t pkt_type;
uint8_t padding;
uint8_t iif[2];
uint8_t service_id[4];
};
const struct juniper_monitor_header *mh;
l2info.pictype = DLT_JUNIPER_MONITOR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
mh = (const struct juniper_monitor_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ",
EXTRACT_32BITS(&mh->service_id),
EXTRACT_16BITS(&mh->iif),
mh->pkt_type));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | juniper_monitor_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_monitor_header {
uint8_t pkt_type;
uint8_t padding;
uint8_t iif[2];
uint8_t service_id[4];
};
const struct juniper_monitor_header *mh;
l2info.pictype = DLT_JUNIPER_MONITOR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
mh = (const struct juniper_monitor_header *)p;
ND_TCHECK(*mh);
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ",
EXTRACT_32BITS(&mh->service_id),
EXTRACT_16BITS(&mh->iif),
mh->pkt_type));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_services]"));
return l2info.header_len;
}
| 167,918 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 signed short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) (buffer[0] << 8);
value|=buffer[1];
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
| 169,953 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,
raptor_option option)
{
int result = -1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
result = TURTLE_WRITER_AUTO_INDENT(turtle_writer);
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
result = turtle_writer->indent;
break;
/* writer options */
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
break;
}
return result;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200 | raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,
raptor_option option)
{
int result = -1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
result = TURTLE_WRITER_AUTO_INDENT(turtle_writer);
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
result = turtle_writer->indent;
break;
/* writer options */
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
break;
}
return result;
}
| 165,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::OnUnregisterAgentError(
const std::string& error_name,
const std::string& error_message) {
LOG(WARNING) << object_path_.value() << ": Failed to unregister agent: "
<< error_name << ": " << error_message;
}
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::OnUnregisterAgentError(
| 171,231 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 * calloc(size_t n, size_t lb)
{
if (lb && n > SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
Commit Message: Fix calloc-related code to prevent SIZE_MAX redefinition in sys headers
* malloc.c: Include limits.h for SIZE_MAX.
* malloc.c (SIZE_MAX, calloc): Define GC_SIZE_MAX instead of SIZE_MAX.
CWE ID: CWE-189 | void * calloc(size_t n, size_t lb)
{
if (lb && n > GC_SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
| 169,880 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int PrintPreviewUI::GetAvailableDraftPageCount() {
return print_preview_data_service()->GetAvailableDraftPageCount(
preview_ui_addr_str_);
}
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 | int PrintPreviewUI::GetAvailableDraftPageCount() {
return print_preview_data_service()->GetAvailableDraftPageCount(id_);
}
| 170,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
const EAS_SAMPLE *loopEnd;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
/*lint -e{713} truncation is OK */
phaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* check for loop end */
acc0 = (EAS_I32) (pSamples - loopEnd);
if (acc0 >= 0)
pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0;
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
CWE ID: CWE-119 | void WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
const EAS_SAMPLE *loopEnd;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
android_errorWriteLog(0x534e4554, "26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
/*lint -e{713} truncation is OK */
phaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* check for loop end */
acc0 = (EAS_I32) (pSamples - loopEnd);
if (acc0 >= 0)
pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0;
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
| 174,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125 | rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo, "%s", rpl_tstr));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
| 169,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc)
{
struct ib_cqe *cqe = wc->wr_cqe;
struct svc_rdma_op_ctxt *ctxt;
svc_rdma_send_wc_common_put(cq, wc, "write");
ctxt = container_of(cqe, struct svc_rdma_op_ctxt, cqe);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc)
| 168,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CuePoint::Load(IMkvReader* pReader)
{
if (m_timecode >= 0) //already loaded
return;
assert(m_track_positions == NULL);
assert(m_track_positions_count == 0);
long long pos_ = -m_timecode;
const long long element_start = pos_;
long long stop;
{
long len;
const long long id = ReadUInt(pReader, pos_, len);
assert(id == 0x3B); //CuePoint ID
if (id != 0x3B)
return;
pos_ += len; //consume ID
const long long size = ReadUInt(pReader, pos_, len);
assert(size >= 0);
pos_ += len; //consume Size field
stop = pos_ + size;
}
const long long element_size = stop - element_start;
long long pos = pos_;
while (pos < stop)
{
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x33) //CueTime ID
m_timecode = UnserializeUInt(pReader, pos, size);
else if (id == 0x37) //CueTrackPosition(s) ID
++m_track_positions_count;
pos += size; //consume payload
assert(pos <= stop);
}
assert(m_timecode >= 0);
assert(m_track_positions_count > 0);
m_track_positions = new TrackPosition[m_track_positions_count];
TrackPosition* p = m_track_positions;
pos = pos_;
while (pos < stop)
{
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x37) //CueTrackPosition(s) ID
{
TrackPosition& tp = *p++;
tp.Parse(pReader, pos, size);
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(size_t(p - m_track_positions) == m_track_positions_count);
m_element_start = element_start;
m_element_size = element_size;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void CuePoint::Load(IMkvReader* pReader)
assert(m_track_positions == NULL);
assert(m_track_positions_count == 0);
long long pos_ = -m_timecode;
const long long element_start = pos_;
long long stop;
{
long len;
const long long id = ReadUInt(pReader, pos_, len);
assert(id == 0x3B); // CuePoint ID
if (id != 0x3B)
return;
pos_ += len; // consume ID
const long long size = ReadUInt(pReader, pos_, len);
assert(size >= 0);
pos_ += len; // consume Size field
// pos_ now points to start of payload
stop = pos_ + size;
}
const long long element_size = stop - element_start;
long long pos = pos_;
// First count number of track positions
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x33) // CueTime ID
m_timecode = UnserializeUInt(pReader, pos, size);
else if (id == 0x37) // CueTrackPosition(s) ID
++m_track_positions_count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(m_timecode >= 0);
assert(m_track_positions_count > 0);
// os << "CuePoint::Load(cont'd): idpos=" << idpos
// << " timecode=" << m_timecode
// << endl;
m_track_positions = new TrackPosition[m_track_positions_count];
// Now parse track positions
TrackPosition* p = m_track_positions;
pos = pos_;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x37) { // CueTrackPosition(s) ID
TrackPosition& tp = *p++;
tp.Parse(pReader, pos, size);
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(size_t(p - m_track_positions) == m_track_positions_count);
m_element_start = element_start;
m_element_size = element_size;
}
| 174,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/') {
if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Path is absolute");
return (ARCHIVE_FAILED);
}
separator = *src++;
}
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert.
CWE ID: CWE-20 | cleanup_pathname(struct archive_write_disk *a)
cleanup_pathname_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags)
{
char *dest, *src;
char separator = '\0';
dest = src = path;
if (*src == '\0') {
if (error_number) *error_number = ARCHIVE_ERRNO_MISC;
if (error_string)
archive_string_sprintf(error_string,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/') {
if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
if (error_number) *error_number = ARCHIVE_ERRNO_MISC;
if (error_string)
archive_string_sprintf(error_string,
"Path is absolute");
return (ARCHIVE_FAILED);
}
separator = *src++;
}
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
if (error_number) *error_number = ARCHIVE_ERRNO_MISC;
if (error_string)
archive_string_sprintf(error_string,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == path) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
| 167,136 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20 | void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
#if defined(OS_MACOSX)
// On the Mac, the convention is to turn popups into new tabs when in
// fullscreen mode. Only worry about user-initiated fullscreen as showing a
// popup in HTML5 fullscreen would have kicked the page out of fullscreen.
if (disposition == WindowOpenDisposition::NEW_POPUP &&
exclusive_access_manager_->fullscreen_controller()
->IsFullscreenForBrowser()) {
disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
#endif
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
| 173,205 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_stream *php_stream_zip_open(char *filename, char *path, char *mode STREAMS_DC TSRMLS_DC)
{
struct zip_file *zf = NULL;
int err = 0;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
struct zip *stream_za;
if (strncmp(mode,"r", strlen("r")) != 0) {
return NULL;
}
if (filename) {
if (ZIP_OPENBASEDIR_CHECKPATH(filename)) {
return NULL;
}
/* duplicate to make the stream za independent (esp. for MSHUTDOWN) */
stream_za = zip_open(filename, ZIP_CREATE, &err);
if (!stream_za) {
return NULL;
}
zf = zip_fopen(stream_za, path, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = stream_za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
stream->orig_path = estrdup(path);
} else {
zip_close(stream_za);
}
}
if (!stream) {
return NULL;
} else {
return stream;
}
}
Commit Message:
CWE ID: CWE-119 | php_stream *php_stream_zip_open(char *filename, char *path, char *mode STREAMS_DC TSRMLS_DC)
{
struct zip_file *zf = NULL;
int err = 0;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
struct zip *stream_za;
if (strncmp(mode,"r", strlen("r")) != 0) {
return NULL;
}
if (filename) {
if (ZIP_OPENBASEDIR_CHECKPATH(filename)) {
return NULL;
}
/* duplicate to make the stream za independent (esp. for MSHUTDOWN) */
stream_za = zip_open(filename, ZIP_CREATE, &err);
if (!stream_za) {
return NULL;
}
zf = zip_fopen(stream_za, path, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = stream_za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
stream->orig_path = estrdup(path);
} else {
zip_close(stream_za);
}
}
if (!stream) {
return NULL;
} else {
return stream;
}
}
| 164,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: float SVGLayoutSupport::calculateScreenFontSizeScalingFactor(const LayoutObject* layoutObject)
{
ASSERT(layoutObject);
AffineTransform ctm = deprecatedCalculateTransformToLayer(layoutObject) * SubtreeContentTransformScope::currentContentTransformation();
ctm.scale(layoutObject->document().frameHost()->deviceScaleFactorDeprecated());
return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID: | float SVGLayoutSupport::calculateScreenFontSizeScalingFactor(const LayoutObject* layoutObject)
{
ASSERT(layoutObject);
AffineTransform ctm = deprecatedCalculateTransformToLayer(layoutObject) * SubtreeContentTransformScope::currentContentTransformation();
ctm.scale(layoutObject->document().frameHost()->deviceScaleFactorDeprecated());
return narrowPrecisionToFloat(sqrt((ctm.xScaleSquared() + ctm.yScaleSquared()) / 2));
}
| 171,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: l2tp_bearer_cap_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l2tp_bearer_cap_print(netdissect_options *ndo, const u_char *dat)
l2tp_bearer_cap_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
| 167,891 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
| 165,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: build_config(char *prefix, struct server *server)
{
char *path = NULL;
int path_size = strlen(prefix) + strlen(server->port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port);
FILE *f = fopen(path, "w+");
if (f == NULL) {
if (verbose) {
LOGE("unable to open config file");
}
ss_free(path);
return;
}
fprintf(f, "{\n");
fprintf(f, "\"server_port\":%d,\n", atoi(server->port));
fprintf(f, "\"password\":\"%s\"", server->password);
if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open);
if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode);
if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method);
if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin);
if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts);
fprintf(f, "\n}\n");
fclose(f);
ss_free(path);
}
Commit Message: Fix #1734
CWE ID: CWE-78 | build_config(char *prefix, struct server *server)
build_config(char *prefix, struct manager_ctx *manager, struct server *server)
{
char *path = NULL;
int path_size = strlen(prefix) + strlen(server->port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port);
FILE *f = fopen(path, "w+");
if (f == NULL) {
if (verbose) {
LOGE("unable to open config file");
}
ss_free(path);
return;
}
fprintf(f, "{\n");
fprintf(f, "\"server_port\":%d,\n", atoi(server->port));
fprintf(f, "\"password\":\"%s\"", server->password);
if (server->method)
fprintf(f, ",\n\"method\":\"%s\"", server->method);
else if (manager->method)
fprintf(f, ",\n\"method\":\"%s\"", manager->method);
if (server->fast_open[0])
fprintf(f, ",\n\"fast_open\": %s", server->fast_open);
if (server->mode)
fprintf(f, ",\n\"mode\":\"%s\"", server->mode);
if (server->plugin)
fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin);
if (server->plugin_opts)
fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts);
fprintf(f, "\n}\n");
fclose(f);
ss_free(path);
}
| 167,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int no_low_depth_gray)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (no_low_depth_gray)
*bit_depth = 8;
else
*bit_depth = 1;
*palette_number = 0;
return 1;
}
if (*colour_type == 3)
{
/* Add multiple palettes for colour type 3. */
if (++*palette_number < PALETTE_COUNT(*bit_depth))
return 1;
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
# ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
# endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int low_depth_gray, int tRNS)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (low_depth_gray)
*bit_depth = 1;
else
*bit_depth = 8;
*palette_number = 0;
return 1;
}
if (*colour_type < 4/*no alpha channel*/)
{
/* Add multiple palettes for colour type 3, one image with tRNS
* and one without for other non-alpha formats:
*/
unsigned int pn = ++*palette_number;
png_byte ct = *colour_type;
if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
(ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
return 1;
/* No: next bit depth */
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
#ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
#endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
| 173,672 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
}
| 170,219 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MaybeRestoreConnections() {
if (IBusConnectionsAreAlive()) {
return;
}
MaybeCreateIBus();
MaybeRestoreIBusConfig();
if (IBusConnectionsAreAlive()) {
ConnectPanelServiceSignals();
if (connection_change_handler_) {
LOG(INFO) << "Notifying Chrome that IBus is ready.";
connection_change_handler_(language_library_, true);
}
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void MaybeRestoreConnections() {
if (IBusConnectionsAreAlive()) {
return;
}
MaybeCreateIBus();
MaybeRestoreIBusConfig();
if (IBusConnectionsAreAlive()) {
ConnectPanelServiceSignals();
VLOG(1) << "Notifying Chrome that IBus is ready.";
FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(true));
}
}
| 170,542 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CheckClientDownloadRequest::ShouldUploadForMalwareScan(
DownloadCheckResultReason reason) {
if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads))
return false;
if (reason != DownloadCheckResultReason::REASON_DOWNLOAD_SAFE &&
reason != DownloadCheckResultReason::REASON_DOWNLOAD_UNCOMMON &&
reason != DownloadCheckResultReason::REASON_VERDICT_UNKNOWN)
return false;
content::BrowserContext* browser_context =
content::DownloadItemUtils::GetBrowserContext(item_);
if (!browser_context)
return false;
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile)
return false;
int send_files_for_malware_check = profile->GetPrefs()->GetInteger(
prefs::kSafeBrowsingSendFilesForMalwareCheck);
if (send_files_for_malware_check !=
SendFilesForMalwareCheckValues::SEND_DOWNLOADS &&
send_files_for_malware_check !=
SendFilesForMalwareCheckValues::SEND_UPLOADS_AND_DOWNLOADS)
return false;
return !policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty();
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <[email protected]>
Reviewed-by: Tien Mai <[email protected]>
Reviewed-by: Daniel Rubery <[email protected]>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20 | bool CheckClientDownloadRequest::ShouldUploadForMalwareScan(
DownloadCheckResultReason reason) {
if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads))
return false;
if (reason != DownloadCheckResultReason::REASON_DOWNLOAD_SAFE &&
reason != DownloadCheckResultReason::REASON_DOWNLOAD_UNCOMMON &&
reason != DownloadCheckResultReason::REASON_VERDICT_UNKNOWN)
return false;
content::BrowserContext* browser_context =
content::DownloadItemUtils::GetBrowserContext(item_);
if (!browser_context)
return false;
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile)
return false;
int send_files_for_malware_check = profile->GetPrefs()->GetInteger(
prefs::kSafeBrowsingSendFilesForMalwareCheck);
if (send_files_for_malware_check !=
SendFilesForMalwareCheckValues::SEND_DOWNLOADS &&
send_files_for_malware_check !=
SendFilesForMalwareCheckValues::SEND_UPLOADS_AND_DOWNLOADS)
return false;
// If there's no valid DM token, the upload will fail, so we can skip
// uploading now.
return BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken().is_valid();
}
| 172,357 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
fsize = st.st_size;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
Commit Message: - limit the number of program and section header number of sections to be
processed to avoid excessive processing time.
- if a bad note is found, return 0 to stop processing immediately.
CWE ID: CWE-399 | file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type, phnum, shnum;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
fsize = st.st_size;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
| 169,904 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 raw_cmd_copyin(int cmd, void __user *param,
struct floppy_raw_cmd **rcmd)
{
struct floppy_raw_cmd *ptr;
int ret;
int i;
*rcmd = NULL;
loop:
ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);
if (!ptr)
return -ENOMEM;
*rcmd = ptr;
ret = copy_from_user(ptr, param, sizeof(*ptr));
if (ret)
return -EFAULT;
ptr->next = NULL;
ptr->buffer_length = 0;
param += sizeof(struct floppy_raw_cmd);
if (ptr->cmd_count > 33)
/* the command may now also take up the space
* initially intended for the reply & the
* reply count. Needed for long 82078 commands
* such as RESTORE, which takes ... 17 command
* bytes. Murphy's law #137: When you reserve
* 16 bytes for a structure, you'll one day
* discover that you really need 17...
*/
return -EINVAL;
for (i = 0; i < 16; i++)
ptr->reply[i] = 0;
ptr->resultcode = 0;
ptr->kernel_data = NULL;
if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
if (ptr->length <= 0)
return -EINVAL;
ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);
fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);
if (!ptr->kernel_data)
return -ENOMEM;
ptr->buffer_length = ptr->length;
}
if (ptr->flags & FD_RAW_WRITE) {
ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);
if (ret)
return ret;
}
if (ptr->flags & FD_RAW_MORE) {
rcmd = &(ptr->next);
ptr->rate &= 0x43;
goto loop;
}
return 0;
}
Commit Message: floppy: ignore kernel-only members in FDRAWCMD ioctl input
Always clear out these floppy_raw_cmd struct members after copying the
entire structure from userspace so that the in-kernel version is always
valid and never left in an interdeterminate state.
Signed-off-by: Matthew Daley <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int raw_cmd_copyin(int cmd, void __user *param,
struct floppy_raw_cmd **rcmd)
{
struct floppy_raw_cmd *ptr;
int ret;
int i;
*rcmd = NULL;
loop:
ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);
if (!ptr)
return -ENOMEM;
*rcmd = ptr;
ret = copy_from_user(ptr, param, sizeof(*ptr));
ptr->next = NULL;
ptr->buffer_length = 0;
ptr->kernel_data = NULL;
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if (ptr->cmd_count > 33)
/* the command may now also take up the space
* initially intended for the reply & the
* reply count. Needed for long 82078 commands
* such as RESTORE, which takes ... 17 command
* bytes. Murphy's law #137: When you reserve
* 16 bytes for a structure, you'll one day
* discover that you really need 17...
*/
return -EINVAL;
for (i = 0; i < 16; i++)
ptr->reply[i] = 0;
ptr->resultcode = 0;
if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
if (ptr->length <= 0)
return -EINVAL;
ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);
fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);
if (!ptr->kernel_data)
return -ENOMEM;
ptr->buffer_length = ptr->length;
}
if (ptr->flags & FD_RAW_WRITE) {
ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);
if (ret)
return ret;
}
if (ptr->flags & FD_RAW_MORE) {
rcmd = &(ptr->next);
ptr->rate &= 0x43;
goto loop;
}
return 0;
}
| 166,435 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
}
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416 | static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
seqf->private = NULL;
}
}
| 166,926 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileReaderLoader::FileReaderLoader(ReadType read_type,
FileReaderLoaderClient* client)
: read_type_(read_type),
client_(client),
handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
binding_(this) {}
Commit Message: Fix use-after-free in FileReaderLoader.
Anything that calls out to client_ can cause FileReaderLoader to be
destroyed, so make sure to check for that situation.
Bug: 835639
Change-Id: I57533d41b7118c06da17abec28bbf301e1f50646
Reviewed-on: https://chromium-review.googlesource.com/1024450
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Daniel Murphy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#552807}
CWE ID: CWE-416 | FileReaderLoader::FileReaderLoader(ReadType read_type,
FileReaderLoaderClient* client)
: read_type_(read_type),
client_(client),
handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
| 173,217 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetScreenLockLibrary(
ScreenLockLibrary* library, bool own) {
library_->screen_lock_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::SetScreenLockLibrary(
| 170,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: ftc_snode_load( FTC_SNode snode,
FTC_Manager manager,
FT_UInt gindex,
FT_ULong *asize )
{
FT_Error error;
FTC_GNode gnode = FTC_GNODE( snode );
FTC_Family family = gnode->family;
FT_Memory memory = manager->memory;
FT_Face face;
FTC_SBit sbit;
FTC_SFamilyClass clazz;
if ( (FT_UInt)(gindex - gnode->gindex) >= snode->count )
{
FT_ERROR(( "ftc_snode_load: invalid glyph index" ));
return FT_THROW( Invalid_Argument );
}
sbit = snode->sbits + ( gindex - gnode->gindex );
clazz = (FTC_SFamilyClass)family->clazz;
sbit->buffer = 0;
error = clazz->family_load_glyph( family, gindex, manager, &face );
if ( error )
goto BadGlyph;
{
FT_Int temp;
FT_GlyphSlot slot = face->glyph;
FT_Bitmap* bitmap = &slot->bitmap;
FT_Pos xadvance, yadvance; /* FT_GlyphSlot->advance.{x|y} */
if ( slot->format != FT_GLYPH_FORMAT_BITMAP )
{
FT_TRACE0(( "ftc_snode_load:"
" glyph loaded didn't return a bitmap\n" ));
goto BadGlyph;
}
/* Check that our values fit into 8-bit containers! */
/* If this is not the case, our bitmap is too large */
/* and we will leave it as `missing' with sbit.buffer = 0 */
#define CHECK_CHAR( d ) ( temp = (FT_Char)d, temp == d )
#define CHECK_BYTE( d ) ( temp = (FT_Byte)d, temp == d )
/* horizontal advance in pixels */
xadvance = ( slot->advance.x + 32 ) >> 6;
yadvance = ( slot->advance.y + 32 ) >> 6;
if ( !CHECK_BYTE( bitmap->rows ) ||
!CHECK_BYTE( bitmap->width ) ||
!CHECK_CHAR( bitmap->pitch ) ||
!CHECK_CHAR( slot->bitmap_left ) ||
!CHECK_CHAR( slot->bitmap_top ) ||
!CHECK_CHAR( xadvance ) ||
!CHECK_CHAR( yadvance ) )
{
FT_TRACE2(( "ftc_snode_load:"
" glyph too large for small bitmap cache\n"));
goto BadGlyph;
}
sbit->width = (FT_Byte)bitmap->width;
sbit->height = (FT_Byte)bitmap->rows;
sbit->pitch = (FT_Char)bitmap->pitch;
sbit->left = (FT_Char)slot->bitmap_left;
sbit->top = (FT_Char)slot->bitmap_top;
sbit->xadvance = (FT_Char)xadvance;
sbit->yadvance = (FT_Char)yadvance;
sbit->format = (FT_Byte)bitmap->pixel_mode;
sbit->max_grays = (FT_Byte)(bitmap->num_grays - 1);
/* copy the bitmap into a new buffer -- ignore error */
error = ftc_sbit_copy_bitmap( sbit, bitmap, memory );
/* now, compute size */
if ( asize )
*asize = FT_ABS( sbit->pitch ) * sbit->height;
} /* glyph loading successful */
/* ignore the errors that might have occurred -- */
/* we mark unloaded glyphs with `sbit.buffer == 0' */
/* and `width == 255', `height == 0' */
/* */
if ( error && FT_ERR_NEQ( error, Out_Of_Memory ) )
{
BadGlyph:
sbit->width = 255;
sbit->height = 0;
sbit->buffer = NULL;
error = FT_Err_Ok;
if ( asize )
*asize = 0;
}
return error;
}
Commit Message:
CWE ID: CWE-119 | ftc_snode_load( FTC_SNode snode,
FTC_Manager manager,
FT_UInt gindex,
FT_ULong *asize )
{
FT_Error error;
FTC_GNode gnode = FTC_GNODE( snode );
FTC_Family family = gnode->family;
FT_Memory memory = manager->memory;
FT_Face face;
FTC_SBit sbit;
FTC_SFamilyClass clazz;
if ( (FT_UInt)(gindex - gnode->gindex) >= snode->count )
{
FT_ERROR(( "ftc_snode_load: invalid glyph index" ));
return FT_THROW( Invalid_Argument );
}
sbit = snode->sbits + ( gindex - gnode->gindex );
clazz = (FTC_SFamilyClass)family->clazz;
sbit->buffer = 0;
error = clazz->family_load_glyph( family, gindex, manager, &face );
if ( error )
goto BadGlyph;
{
FT_Int temp;
FT_GlyphSlot slot = face->glyph;
FT_Bitmap* bitmap = &slot->bitmap;
FT_Pos xadvance, yadvance; /* FT_GlyphSlot->advance.{x|y} */
if ( slot->format != FT_GLYPH_FORMAT_BITMAP )
{
FT_TRACE0(( "ftc_snode_load:"
" glyph loaded didn't return a bitmap\n" ));
goto BadGlyph;
}
/* Check whether our values fit into 8-bit containers! */
/* If this is not the case, our bitmap is too large */
/* and we will leave it as `missing' with sbit.buffer = 0 */
#define CHECK_CHAR( d ) ( temp = (FT_Char)d, (FT_Int) temp == (FT_Int) d )
#define CHECK_BYTE( d ) ( temp = (FT_Byte)d, (FT_UInt)temp == (FT_UInt)d )
/* horizontal advance in pixels */
xadvance = ( slot->advance.x + 32 ) >> 6;
yadvance = ( slot->advance.y + 32 ) >> 6;
if ( !CHECK_BYTE( bitmap->rows ) ||
!CHECK_BYTE( bitmap->width ) ||
!CHECK_CHAR( bitmap->pitch ) ||
!CHECK_CHAR( slot->bitmap_left ) ||
!CHECK_CHAR( slot->bitmap_top ) ||
!CHECK_CHAR( xadvance ) ||
!CHECK_CHAR( yadvance ) )
{
FT_TRACE2(( "ftc_snode_load:"
" glyph too large for small bitmap cache\n"));
goto BadGlyph;
}
sbit->width = (FT_Byte)bitmap->width;
sbit->height = (FT_Byte)bitmap->rows;
sbit->pitch = (FT_Char)bitmap->pitch;
sbit->left = (FT_Char)slot->bitmap_left;
sbit->top = (FT_Char)slot->bitmap_top;
sbit->xadvance = (FT_Char)xadvance;
sbit->yadvance = (FT_Char)yadvance;
sbit->format = (FT_Byte)bitmap->pixel_mode;
sbit->max_grays = (FT_Byte)(bitmap->num_grays - 1);
/* copy the bitmap into a new buffer -- ignore error */
error = ftc_sbit_copy_bitmap( sbit, bitmap, memory );
/* now, compute size */
if ( asize )
*asize = FT_ABS( sbit->pitch ) * sbit->height;
} /* glyph loading successful */
/* ignore the errors that might have occurred -- */
/* we mark unloaded glyphs with `sbit.buffer == 0' */
/* and `width == 255', `height == 0' */
/* */
if ( error && FT_ERR_NEQ( error, Out_Of_Memory ) )
{
BadGlyph:
sbit->width = 255;
sbit->height = 0;
sbit->buffer = NULL;
error = FT_Err_Ok;
if ( asize )
*asize = 0;
}
return error;
}
| 164,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
CheckNumberCompactPixels;
compact_pixels++;
}
}
return(i);
}
Commit Message: Moved check for https://github.com/ImageMagick/ImageMagick/issues/92.
CWE ID: CWE-125 | static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
| 168,806 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char *print_array( cJSON *item, int depth, int fmt )
{
char **entries;
char *out = 0, *ptr, *ret;
int len = 5;
cJSON *child = item->child;
int numentries = 0, i = 0, fail = 0;
/* How many entries in the array? */
while ( child ) {
++numentries;
child = child->next;
}
/* Allocate an array to hold the values for each. */
if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )
return 0;
memset( entries, 0, numentries * sizeof(char*) );
/* Retrieve all the results. */
child = item->child;
while ( child && ! fail ) {
ret = print_value( child, depth + 1, fmt );
entries[i++] = ret;
if ( ret )
len += strlen( ret ) + 2 + ( fmt ? 1 : 0 );
else
fail = 1;
child = child -> next;
}
/* If we didn't fail, try to malloc the output string. */
if ( ! fail ) {
out = (char*) cJSON_malloc( len );
if ( ! out )
fail = 1;
}
/* Handle failure. */
if ( fail ) {
for ( i = 0; i < numentries; ++i )
if ( entries[i] )
cJSON_free( entries[i] );
cJSON_free( entries );
return 0;
}
/* Compose the output array. */
*out = '[';
ptr = out + 1;
*ptr = 0;
for ( i = 0; i < numentries; ++i ) {
strcpy( ptr, entries[i] );
ptr += strlen( entries[i] );
if ( i != numentries - 1 ) {
*ptr++ = ',';
if ( fmt )
*ptr++ = ' ';
*ptr = 0;
}
cJSON_free( entries[i] );
}
cJSON_free( entries );
*ptr++ = ']';
*ptr++ = 0;
return out;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static char *print_array( cJSON *item, int depth, int fmt )
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries;
char *out=0,*ptr,*ret;int len=5;
cJSON *child=item->child;
int numentries=0,i=0,fail=0;
size_t tmplen=0;
/* How many entries in the array? */
while (child) numentries++,child=child->next;
/* Explicitly handle numentries==0 */
if (!numentries)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (out) strcpy(out,"[]");
return out;
}
if (p)
{
/* Compose the output array. */
i=p->offset;
ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++;
child=item->child;
while (child && !fail)
{
print_value(child,depth+1,fmt,p);
p->offset=update(p);
if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;}
child=child->next;
}
ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
memset(entries,0,numentries*sizeof(char*));
/* Retrieve all the results: */
child=item->child;
while (child && !fail)
{
ret=print_value(child,depth+1,fmt,0);
entries[i++]=ret;
if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
child=child->next;
}
/* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len);
/* If that fails, we fail. */
if (!out) fail=1;
/* Handle failure. */
if (fail)
{
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries);
return 0;
}
/* Compose the output array. */
*out='[';
ptr=out+1;*ptr=0;
for (i=0;i<numentries;i++)
{
tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen;
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]);
}
cJSON_free(entries);
*ptr++=']';*ptr++=0;
}
return out;
}
| 167,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebGL2RenderingContextBase::bindVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost())
return;
if (vertex_array &&
(vertex_array->IsDeleted() || !vertex_array->Validate(nullptr, this))) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindVertexArray",
"invalid vertexArray");
return;
}
if (vertex_array && !vertex_array->IsDefaultObject() &&
vertex_array->Object()) {
ContextGL()->BindVertexArrayOES(ObjectOrZero(vertex_array));
vertex_array->SetHasEverBeenBound();
SetBoundVertexArrayObject(vertex_array);
} else {
ContextGL()->BindVertexArrayOES(0);
SetBoundVertexArrayObject(nullptr);
}
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | void WebGL2RenderingContextBase::bindVertexArray(
WebGLVertexArrayObject* vertex_array) {
bool deleted;
if (!CheckObjectToBeBound("bindVertexArray", vertex_array, deleted))
return;
if (deleted) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindVertexArray",
"attempt to bind a deleted vertex array");
return;
}
if (vertex_array && !vertex_array->IsDefaultObject() &&
vertex_array->Object()) {
ContextGL()->BindVertexArrayOES(ObjectOrZero(vertex_array));
vertex_array->SetHasEverBeenBound();
SetBoundVertexArrayObject(vertex_array);
} else {
ContextGL()->BindVertexArrayOES(0);
SetBoundVertexArrayObject(nullptr);
}
}
| 173,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) {
int i = 0;
int j = comp->nbStep - 1;
while (j > i) {
register xmlChar *tmp;
register xsltOp op;
register xmlXPathCompExprPtr expr;
register int t;
tmp = comp->steps[i].value;
comp->steps[i].value = comp->steps[j].value;
comp->steps[j].value = tmp;
tmp = comp->steps[i].value2;
comp->steps[i].value2 = comp->steps[j].value2;
comp->steps[j].value2 = tmp;
tmp = comp->steps[i].value3;
comp->steps[i].value3 = comp->steps[j].value3;
comp->steps[j].value3 = tmp;
op = comp->steps[i].op;
comp->steps[i].op = comp->steps[j].op;
comp->steps[j].op = op;
expr = comp->steps[i].comp;
comp->steps[i].comp = comp->steps[j].comp;
comp->steps[j].comp = expr;
t = comp->steps[i].previousExtra;
comp->steps[i].previousExtra = comp->steps[j].previousExtra;
comp->steps[j].previousExtra = t;
t = comp->steps[i].indexExtra;
comp->steps[i].indexExtra = comp->steps[j].indexExtra;
comp->steps[j].indexExtra = t;
t = comp->steps[i].lenExtra;
comp->steps[i].lenExtra = comp->steps[j].lenExtra;
comp->steps[j].lenExtra = t;
j--;
i++;
}
xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0);
/*
* detect consecutive XSLT_OP_PREDICATE indicating a direct
* matching should be done.
*/
for (i = 0;i < comp->nbStep - 1;i++) {
if ((comp->steps[i].op == XSLT_OP_PREDICATE) &&
(comp->steps[i + 1].op == XSLT_OP_PREDICATE)) {
comp->direct = 1;
if (comp->pattern[0] != '/') {
xmlChar *query;
query = xmlStrdup((const xmlChar *)"//");
query = xmlStrcat(query, comp->pattern);
xmlFree((xmlChar *) comp->pattern);
comp->pattern = query;
}
break;
}
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) {
int i = 0;
int j = comp->nbStep - 1;
while (j > i) {
register xmlChar *tmp;
register xsltOp op;
register xmlXPathCompExprPtr expr;
register int t;
tmp = comp->steps[i].value;
comp->steps[i].value = comp->steps[j].value;
comp->steps[j].value = tmp;
tmp = comp->steps[i].value2;
comp->steps[i].value2 = comp->steps[j].value2;
comp->steps[j].value2 = tmp;
tmp = comp->steps[i].value3;
comp->steps[i].value3 = comp->steps[j].value3;
comp->steps[j].value3 = tmp;
op = comp->steps[i].op;
comp->steps[i].op = comp->steps[j].op;
comp->steps[j].op = op;
expr = comp->steps[i].comp;
comp->steps[i].comp = comp->steps[j].comp;
comp->steps[j].comp = expr;
t = comp->steps[i].previousExtra;
comp->steps[i].previousExtra = comp->steps[j].previousExtra;
comp->steps[j].previousExtra = t;
t = comp->steps[i].indexExtra;
comp->steps[i].indexExtra = comp->steps[j].indexExtra;
comp->steps[j].indexExtra = t;
t = comp->steps[i].lenExtra;
comp->steps[i].lenExtra = comp->steps[j].lenExtra;
comp->steps[j].lenExtra = t;
j--;
i++;
}
xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0);
/*
* Detect consecutive XSLT_OP_PREDICATE and predicates on ops which
* haven't been optimized yet indicating a direct matching should be done.
*/
for (i = 0;i < comp->nbStep - 1;i++) {
xsltOp op = comp->steps[i].op;
if ((op != XSLT_OP_ELEM) &&
(op != XSLT_OP_ALL) &&
(comp->steps[i + 1].op == XSLT_OP_PREDICATE)) {
comp->direct = 1;
if (comp->pattern[0] != '/') {
xmlChar *query;
query = xmlStrdup((const xmlChar *)"//");
query = xmlStrcat(query, comp->pattern);
xmlFree((xmlChar *) comp->pattern);
comp->pattern = query;
}
break;
}
}
}
| 173,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftOpus::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamAudioAndroidOpus:
{
OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
opusParams->nAudioBandWidth = 0;
opusParams->nSampleRate = kRate;
opusParams->nBitRate = 0;
if (!isConfigured()) {
opusParams->nChannels = 1;
} else {
opusParams->nChannels = mHeader->channels;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nSamplingRate = kRate;
if (!isConfigured()) {
pcmParams->nChannels = 1;
} else {
pcmParams->nChannels = mHeader->channels;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(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 SoftOpus::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamAudioAndroidOpus:
{
OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (!isValidOMXParam(opusParams)) {
return OMX_ErrorBadParameter;
}
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
opusParams->nAudioBandWidth = 0;
opusParams->nSampleRate = kRate;
opusParams->nBitRate = 0;
if (!isConfigured()) {
opusParams->nChannels = 1;
} else {
opusParams->nChannels = mHeader->channels;
}
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 != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nSamplingRate = kRate;
if (!isConfigured()) {
pcmParams->nChannels = 1;
} else {
pcmParams->nChannels = mHeader->channels;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *ReadSCREENSHOTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
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=(Image *) NULL;
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
{
BITMAPINFO
bmi;
DISPLAY_DEVICE
device;
HBITMAP
bitmap,
bitmapOld;
HDC
bitmapDC,
hDC;
Image
*screen;
int
i;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
x;
RGBTRIPLE
*p;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
i=0;
device.cb = sizeof(device);
image=(Image *) NULL;
while(EnumDisplayDevices(NULL,i,&device,0) && ++i)
{
if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)
continue;
hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);
if (hDC == (HDC) NULL)
ThrowReaderException(CoderError,"UnableToCreateDC");
screen=AcquireImage(image_info);
screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);
screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);
screen->storage_class=DirectClass;
status=SetImageExtent(screen,screen->columns,screen->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image == (Image *) NULL)
image=screen;
else
AppendImageToList(&image,screen);
bitmapDC=CreateCompatibleDC(hDC);
if (bitmapDC == (HDC) NULL)
{
DeleteDC(hDC);
ThrowReaderException(CoderError,"UnableToCreateDC");
}
(void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));
bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=(LONG) screen->columns;
bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;
bmi.bmiHeader.biPlanes=1;
bmi.bmiHeader.biBitCount=24;
bmi.bmiHeader.biCompression=BI_RGB;
bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);
if (bitmap == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);
if (bitmapOld == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,
SRCCOPY);
(void) SelectObject(bitmapDC,bitmapOld);
for (y=0; y < (ssize_t) screen->rows; y++)
{
q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) screen->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed));
SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen));
SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue));
SetPixelOpacity(q,OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(screen,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
}
}
#elif defined(MAGICKCORE_X11_DELEGATE)
{
const char
*option;
XImportInfo
ximage_info;
(void) exception;
XGetImportInfo(&ximage_info);
option=GetImageOption(image_info,"x:screen");
if (option != (const char *) NULL)
ximage_info.screen=IsMagickTrue(option);
option=GetImageOption(image_info,"x:silent");
if (option != (const char *) NULL)
ximage_info.silent=IsMagickTrue(option);
image=XImportImage(image_info,&ximage_info);
}
#endif
return(image);
}
Commit Message: Fixed potential memory leak.
CWE ID: CWE-772 | static Image *ReadSCREENSHOTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
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=(Image *) NULL;
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
{
BITMAPINFO
bmi;
DISPLAY_DEVICE
device;
HBITMAP
bitmap,
bitmapOld;
HDC
bitmapDC,
hDC;
Image
*screen;
int
i;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
x;
RGBTRIPLE
*p;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
i=0;
device.cb = sizeof(device);
image=(Image *) NULL;
while(EnumDisplayDevices(NULL,i,&device,0) && ++i)
{
if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)
continue;
hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);
if (hDC == (HDC) NULL)
ThrowReaderException(CoderError,"UnableToCreateDC");
screen=AcquireImage(image_info);
screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);
screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);
screen->storage_class=DirectClass;
if (image == (Image *) NULL)
image=screen;
else
AppendImageToList(&image,screen);
status=SetImageExtent(screen,screen->columns,screen->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
bitmapDC=CreateCompatibleDC(hDC);
if (bitmapDC == (HDC) NULL)
{
DeleteDC(hDC);
ThrowReaderException(CoderError,"UnableToCreateDC");
}
(void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));
bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=(LONG) screen->columns;
bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;
bmi.bmiHeader.biPlanes=1;
bmi.bmiHeader.biBitCount=24;
bmi.bmiHeader.biCompression=BI_RGB;
bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);
if (bitmap == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);
if (bitmapOld == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,
SRCCOPY);
(void) SelectObject(bitmapDC,bitmapOld);
for (y=0; y < (ssize_t) screen->rows; y++)
{
q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) screen->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed));
SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen));
SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue));
SetPixelOpacity(q,OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(screen,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
}
}
#elif defined(MAGICKCORE_X11_DELEGATE)
{
const char
*option;
XImportInfo
ximage_info;
(void) exception;
XGetImportInfo(&ximage_info);
option=GetImageOption(image_info,"x:screen");
if (option != (const char *) NULL)
ximage_info.screen=IsMagickTrue(option);
option=GetImageOption(image_info,"x:silent");
if (option != (const char *) NULL)
ximage_info.silent=IsMagickTrue(option);
image=XImportImage(image_info,&ximage_info);
}
#endif
return(image);
}
| 168,037 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 qeth_snmp_command(struct qeth_card *card, char __user *udata)
{
struct qeth_cmd_buffer *iob;
struct qeth_ipa_cmd *cmd;
struct qeth_snmp_ureq *ureq;
int req_len;
struct qeth_arp_query_info qinfo = {0, };
int rc = 0;
QETH_CARD_TEXT(card, 3, "snmpcmd");
if (card->info.guestlan)
return -EOPNOTSUPP;
if ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) &&
(!card->options.layer2)) {
return -EOPNOTSUPP;
}
/* skip 4 bytes (data_len struct member) to get req_len */
if (copy_from_user(&req_len, udata + sizeof(int), sizeof(int)))
return -EFAULT;
ureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr));
if (IS_ERR(ureq)) {
QETH_CARD_TEXT(card, 2, "snmpnome");
return PTR_ERR(ureq);
}
qinfo.udata_len = ureq->hdr.data_len;
qinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL);
if (!qinfo.udata) {
kfree(ureq);
return -ENOMEM;
}
qinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr);
iob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL,
QETH_SNMP_SETADP_CMDLENGTH + req_len);
cmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE);
memcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len);
rc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len,
qeth_snmp_command_cb, (void *)&qinfo);
if (rc)
QETH_DBF_MESSAGE(2, "SNMP command failed on %s: (0x%x)\n",
QETH_CARD_IFNAME(card), rc);
else {
if (copy_to_user(udata, qinfo.udata, qinfo.udata_len))
rc = -EFAULT;
}
kfree(ureq);
kfree(qinfo.udata);
return rc;
}
Commit Message: qeth: avoid buffer overflow in snmp ioctl
Check user-defined length in snmp ioctl request and allow request
only if it fits into a qeth command buffer.
Signed-off-by: Ursula Braun <[email protected]>
Signed-off-by: Frank Blaschka <[email protected]>
Reviewed-by: Heiko Carstens <[email protected]>
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Cc: <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int qeth_snmp_command(struct qeth_card *card, char __user *udata)
{
struct qeth_cmd_buffer *iob;
struct qeth_ipa_cmd *cmd;
struct qeth_snmp_ureq *ureq;
unsigned int req_len;
struct qeth_arp_query_info qinfo = {0, };
int rc = 0;
QETH_CARD_TEXT(card, 3, "snmpcmd");
if (card->info.guestlan)
return -EOPNOTSUPP;
if ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) &&
(!card->options.layer2)) {
return -EOPNOTSUPP;
}
/* skip 4 bytes (data_len struct member) to get req_len */
if (copy_from_user(&req_len, udata + sizeof(int), sizeof(int)))
return -EFAULT;
if (req_len > (QETH_BUFSIZE - IPA_PDU_HEADER_SIZE -
sizeof(struct qeth_ipacmd_hdr) -
sizeof(struct qeth_ipacmd_setadpparms_hdr)))
return -EINVAL;
ureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr));
if (IS_ERR(ureq)) {
QETH_CARD_TEXT(card, 2, "snmpnome");
return PTR_ERR(ureq);
}
qinfo.udata_len = ureq->hdr.data_len;
qinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL);
if (!qinfo.udata) {
kfree(ureq);
return -ENOMEM;
}
qinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr);
iob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL,
QETH_SNMP_SETADP_CMDLENGTH + req_len);
cmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE);
memcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len);
rc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len,
qeth_snmp_command_cb, (void *)&qinfo);
if (rc)
QETH_DBF_MESSAGE(2, "SNMP command failed on %s: (0x%x)\n",
QETH_CARD_IFNAME(card), rc);
else {
if (copy_to_user(udata, qinfo.udata, qinfo.udata_len))
rc = -EFAULT;
}
kfree(ureq);
kfree(qinfo.udata);
return rc;
}
| 165,940 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_split_unwritten_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path,
int flags)
{
struct ext4_extent *ex, newex, orig_ex;
struct ext4_extent *ex1 = NULL;
struct ext4_extent *ex2 = NULL;
struct ext4_extent *ex3 = NULL;
ext4_lblk_t ee_block, eof_block;
unsigned int allocated, ee_len, depth;
ext4_fsblk_t newblock;
int err = 0;
int may_zeroout;
ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
allocated = ee_len - (map->m_lblk - ee_block);
newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex);
ex2 = ex;
orig_ex.ee_block = ex->ee_block;
orig_ex.ee_len = cpu_to_le16(ee_len);
ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex));
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
may_zeroout = ee_block + ee_len <= eof_block;
/*
* If the uninitialized extent begins at the same logical
* block where the write begins, and the write completely
* covers the extent, then we don't need to split it.
*/
if ((map->m_lblk == ee_block) && (allocated <= map->m_len))
return allocated;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* ex1: ee_block to map->m_lblk - 1 : uninitialized */
if (map->m_lblk > ee_block) {
ex1 = ex;
ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
ext4_ext_mark_uninitialized(ex1);
ex2 = &newex;
}
/*
* for sanity, update the length of the ex2 extent before
* we insert ex3, if ex1 is NULL. This is to avoid temporary
* overlap of blocks.
*/
if (!ex1 && allocated > map->m_len)
ex2->ee_len = cpu_to_le16(map->m_len);
/* ex3: to ee_block + ee_len : uninitialised */
if (allocated > map->m_len) {
unsigned int newdepth;
ex3 = &newex;
ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len);
ext4_ext_store_pblock(ex3, newblock + map->m_len);
ex3->ee_len = cpu_to_le16(allocated - map->m_len);
ext4_ext_mark_uninitialized(ex3);
err = ext4_ext_insert_extent(handle, inode, path, ex3, flags);
if (err == -ENOSPC && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zeroed the full extent */
/* blocks available from map->m_lblk */
return allocated;
} else if (err)
goto fix_extent_len;
/*
* The depth, and hence eh & ex might change
* as part of the insert above.
*/
newdepth = ext_depth(inode);
/*
* update the extent length after successful insert of the
* split extent
*/
ee_len -= ext4_ext_get_actual_len(ex3);
orig_ex.ee_len = cpu_to_le16(ee_len);
may_zeroout = ee_block + ee_len <= eof_block;
depth = newdepth;
ext4_ext_drop_refs(path);
path = ext4_ext_find_extent(inode, map->m_lblk, path);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
ex = path[depth].p_ext;
if (ex2 != &newex)
ex2 = ex;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
allocated = map->m_len;
}
/*
* If there was a change of depth as part of the
* insertion of ex3 above, we need to update the length
* of the ex1 extent again here
*/
if (ex1 && ex1 != ex) {
ex1 = ex;
ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
ext4_ext_mark_uninitialized(ex1);
ex2 = &newex;
}
/*
* ex2: map->m_lblk to map->m_lblk + map->m_len-1 : to be written
* using direct I/O, uninitialised still.
*/
ex2->ee_block = cpu_to_le32(map->m_lblk);
ext4_ext_store_pblock(ex2, newblock);
ex2->ee_len = cpu_to_le16(allocated);
ext4_ext_mark_uninitialized(ex2);
if (ex2 != ex)
goto insert;
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + depth);
ext_debug("out here\n");
goto out;
insert:
err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
if (err == -ENOSPC && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zero out the first half */
return allocated;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err ? err : allocated;
fix_extent_len:
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_mark_uninitialized(ex);
ext4_ext_dirty(handle, inode, path + depth);
return err;
}
Commit Message: ext4: reimplement convert and split_unwritten
Reimplement ext4_ext_convert_to_initialized() and
ext4_split_unwritten_extents() using ext4_split_extent()
Signed-off-by: Yongqiang Yang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Tested-by: Allison Henderson <[email protected]>
CWE ID: | static int ext4_split_unwritten_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path,
int flags)
{
ext4_lblk_t eof_block;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len;
int split_flag = 0, depth;
ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
split_flag |= EXT4_EXT_MARK_UNINIT2;
flags |= EXT4_GET_BLOCKS_PRE_IO;
return ext4_split_extent(handle, inode, path, map, split_flag, flags);
}
| 166,218 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error;
address &= PAGE_MASK;
error = security_mmap_addr(address);
if (error)
return error;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
Commit Message: mm: enforce min addr even if capable() in expand_downwards()
security_mmap_addr() does a capability check with current_cred(), but
we can reach this code from contexts like a VFS write handler where
current_cred() must not be used.
This can be abused on systems without SMAP to make NULL pointer
dereferences exploitable again.
Fixes: 8869477a49c3 ("security: protect from stack expansion into low vm addresses")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476 | int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error = 0;
address &= PAGE_MASK;
if (address < mmap_min_addr)
return -EPERM;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
| 169,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int do_set_thread_area(struct task_struct *p, int idx,
struct user_desc __user *u_info,
int can_allocate)
{
struct user_desc info;
if (copy_from_user(&info, u_info, sizeof(info)))
return -EFAULT;
if (idx == -1)
idx = info.entry_number;
/*
* index -1 means the kernel should try to find and
* allocate an empty descriptor:
*/
if (idx == -1 && can_allocate) {
idx = get_free_idx();
if (idx < 0)
return idx;
if (put_user(idx, &u_info->entry_number))
return -EFAULT;
}
if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
return -EINVAL;
set_tls_desc(p, idx, &info, 1);
return 0;
}
Commit Message: x86/tls: Validate TLS entries to protect espfix
Installing a 16-bit RW data segment into the GDT defeats espfix.
AFAICT this will not affect glibc, Wine, or dosemu at all.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: H. Peter Anvin <[email protected]>
Cc: [email protected]
Cc: Konrad Rzeszutek Wilk <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: [email protected] <[email protected]>
Cc: Willy Tarreau <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | int do_set_thread_area(struct task_struct *p, int idx,
struct user_desc __user *u_info,
int can_allocate)
{
struct user_desc info;
if (copy_from_user(&info, u_info, sizeof(info)))
return -EFAULT;
if (!tls_desc_okay(&info))
return -EINVAL;
if (idx == -1)
idx = info.entry_number;
/*
* index -1 means the kernel should try to find and
* allocate an empty descriptor:
*/
if (idx == -1 && can_allocate) {
idx = get_free_idx();
if (idx < 0)
return idx;
if (put_user(idx, &u_info->entry_number))
return -EFAULT;
}
if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
return -EINVAL;
set_tls_desc(p, idx, &info, 1);
return 0;
}
| 166,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GpuChannel::~GpuChannel() {
#if defined(OS_WIN)
if (renderer_process_)
CloseHandle(renderer_process_);
#endif
}
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: | GpuChannel::~GpuChannel() {
}
| 170,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
if (copy_from_user(arg, user, get_arglen[GET_CMDID(cmd)]) != 0)
return -EFAULT;
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), IP_VS_CONN_TAB_SIZE);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = IP_VS_CONN_TAB_SIZE;
info.num_services = ip_vs_num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_get(AF_INET, entry->fwmark);
else
svc = __ip_vs_service_get(AF_INET, entry->protocol,
&addr, entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
ip_vs_service_put(svc);
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
__ip_vs_get_timeouts(&t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_DAEMON:
{
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (ip_vs_sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ip_vs_master_mcast_ifn, sizeof(d[0].mcast_ifn));
d[0].syncid = ip_vs_master_syncid;
}
if (ip_vs_sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ip_vs_backup_mcast_ifn, sizeof(d[1].mcast_ifn));
d[1].syncid = ip_vs_backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
Commit Message: ipvs: Add boundary check on ioctl arguments
The ipvs code has a nifty system for doing the size of ioctl command
copies; it defines an array with values into which it indexes the cmd
to find the right length.
Unfortunately, the ipvs code forgot to check if the cmd was in the
range that the array provides, allowing for an index outside of the
array, which then gives a "garbage" result into the length, which
then gets used for copying into a stack buffer.
Fix this by adding sanity checks on these as well as the copy size.
[ [email protected]: adjusted limit to IP_VS_SO_GET_MAX ]
Signed-off-by: Arjan van de Ven <[email protected]>
Acked-by: Julian Anastasov <[email protected]>
Signed-off-by: Simon Horman <[email protected]>
Signed-off-by: Patrick McHardy <[email protected]>
CWE ID: CWE-119 | do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
unsigned int copylen;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
return -EINVAL;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
copylen = get_arglen[GET_CMDID(cmd)];
if (copylen > 128)
return -EINVAL;
if (copy_from_user(arg, user, copylen) != 0)
return -EFAULT;
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), IP_VS_CONN_TAB_SIZE);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = IP_VS_CONN_TAB_SIZE;
info.num_services = ip_vs_num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_get(AF_INET, entry->fwmark);
else
svc = __ip_vs_service_get(AF_INET, entry->protocol,
&addr, entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
ip_vs_service_put(svc);
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
__ip_vs_get_timeouts(&t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_DAEMON:
{
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (ip_vs_sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ip_vs_master_mcast_ifn, sizeof(d[0].mcast_ifn));
d[0].syncid = ip_vs_master_syncid;
}
if (ip_vs_sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ip_vs_backup_mcast_ifn, sizeof(d[1].mcast_ifn));
d[1].syncid = ip_vs_backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
| 165,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data)
{
struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data;
u16 scid, flags, result;
struct sock *sk;
scid = __le16_to_cpu(rsp->scid);
flags = __le16_to_cpu(rsp->flags);
result = __le16_to_cpu(rsp->result);
BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x",
scid, flags, result);
sk = l2cap_get_chan_by_scid(&conn->chan_list, scid);
if (!sk)
return 0;
switch (result) {
case L2CAP_CONF_SUCCESS:
break;
case L2CAP_CONF_UNACCEPT:
if (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) {
char req[128];
/* It does not make sense to adjust L2CAP parameters
* that are currently defined in the spec. We simply
* resend config request that we sent earlier. It is
* stupid, but it helps qualification testing which
* expects at least some response from us. */
l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
l2cap_build_conf_req(sk, req), req);
goto done;
}
default:
sk->sk_state = BT_DISCONN;
sk->sk_err = ECONNRESET;
l2cap_sock_set_timer(sk, HZ * 5);
{
struct l2cap_disconn_req req;
req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);
req.scid = cpu_to_le16(l2cap_pi(sk)->scid);
l2cap_send_cmd(conn, l2cap_get_ident(conn),
L2CAP_DISCONN_REQ, sizeof(req), &req);
}
goto done;
}
if (flags & 0x01)
goto done;
l2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
}
done:
bh_unlock_sock(sk);
return 0;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data)
{
struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data;
u16 scid, flags, result;
struct sock *sk;
scid = __le16_to_cpu(rsp->scid);
flags = __le16_to_cpu(rsp->flags);
result = __le16_to_cpu(rsp->result);
BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x",
scid, flags, result);
sk = l2cap_get_chan_by_scid(&conn->chan_list, scid);
if (!sk)
return 0;
switch (result) {
case L2CAP_CONF_SUCCESS:
break;
case L2CAP_CONF_UNACCEPT:
if (l2cap_pi(sk)->num_conf_rsp <= L2CAP_CONF_MAX_CONF_RSP) {
int len = cmd->len - sizeof(*rsp);
char req[64];
/* throw out any old stored conf requests */
result = L2CAP_CONF_SUCCESS;
len = l2cap_parse_conf_rsp(sk, rsp->data,
len, req, &result);
if (len < 0) {
struct l2cap_disconn_req req;
req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);
req.scid = cpu_to_le16(l2cap_pi(sk)->scid);
l2cap_send_cmd(conn, l2cap_get_ident(conn),
L2CAP_DISCONN_REQ, sizeof(req), &req);
goto done;
}
l2cap_send_cmd(conn, l2cap_get_ident(conn),
L2CAP_CONF_REQ, len, req);
l2cap_pi(sk)->num_conf_req++;
if (result != L2CAP_CONF_SUCCESS)
goto done;
break;
}
default:
sk->sk_state = BT_DISCONN;
sk->sk_err = ECONNRESET;
l2cap_sock_set_timer(sk, HZ * 5);
{
struct l2cap_disconn_req req;
req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);
req.scid = cpu_to_le16(l2cap_pi(sk)->scid);
l2cap_send_cmd(conn, l2cap_get_ident(conn),
L2CAP_DISCONN_REQ, sizeof(req), &req);
}
goto done;
}
if (flags & 0x01)
goto done;
l2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
}
done:
bh_unlock_sock(sk);
return 0;
}
| 167,623 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = (r->glyph_data.bits.size - r->pos < n ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
Commit Message:
CWE ID: CWE-125 | static void gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = ((r->pos >= r->glyph_data.bits.size ||
r->glyph_data.bits.size - r->pos < n) ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
| 164,779 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppListController::EnableAppList() {
PrefService* local_state = g_browser_process->local_state();
bool has_been_enabled = local_state->GetBoolean(
apps::prefs::kAppLauncherHasBeenEnabled);
if (!has_been_enabled) {
local_state->SetBoolean(apps::prefs::kAppLauncherHasBeenEnabled, true);
ShellIntegration::ShortcutLocations shortcut_locations;
shortcut_locations.on_desktop = true;
shortcut_locations.in_quick_launch_bar = true;
shortcut_locations.in_applications_menu = true;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
shortcut_locations.applications_menu_subdir = dist->GetAppShortCutName();
base::FilePath user_data_dir(
g_browser_process->profile_manager()->user_data_dir());
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&CreateAppListShortcuts,
user_data_dir, GetAppModelId(), shortcut_locations));
}
}
Commit Message: Upgrade old app host to new app launcher on startup
This patch is a continuation of https://codereview.chromium.org/16805002/.
BUG=248825
Review URL: https://chromiumcodereview.appspot.com/17022015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AppListController::EnableAppList() {
PrefService* local_state = g_browser_process->local_state();
local_state->SetBoolean(apps::prefs::kAppLauncherHasBeenEnabled, true);
ShellIntegration::ShortcutLocations shortcut_locations;
shortcut_locations.on_desktop = true;
shortcut_locations.in_quick_launch_bar = true;
shortcut_locations.in_applications_menu = true;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
shortcut_locations.applications_menu_subdir = dist->GetAppShortCutName();
base::FilePath user_data_dir(
g_browser_process->profile_manager()->user_data_dir());
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&CreateAppListShortcuts,
user_data_dir, GetAppModelId(), shortcut_locations));
}
| 171,336 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebGraphicsContext3DCommandBufferImpl::GetGPUProcessID() {
return host_ ? host_->gpu_process_id() : 0;
}
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: | int WebGraphicsContext3DCommandBufferImpl::GetGPUProcessID() {
return host_ ? host_->gpu_host_id() : 0;
}
| 170,930 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void IOHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_host_ = process_host;
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void IOHandler::SetRenderer(RenderProcessHost* process_host,
void IOHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
RenderProcessHost* process_host = RenderProcessHost::FromID(process_host_id);
if (process_host) {
browser_context_ = process_host->GetBrowserContext();
storage_partition_ = process_host->GetStoragePartition();
} else {
browser_context_ = nullptr;
storage_partition_ = nullptr;
}
}
| 172,751 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_send_tls(gnutls_session * session, xmlNode * msg)
{
char *xml_text = NULL;
# if 0
const char *name = crm_element_name(msg);
if (safe_str_neq(name, "cib_command")) {
xmlNodeSetName(msg, "cib_result");
}
# endif
xml_text = dump_xml_unformatted(msg);
if (xml_text != NULL) {
char *unsent = xml_text;
int len = strlen(xml_text);
int rc = 0;
len++; /* null char */
crm_trace("Message size: %d", len);
while (TRUE) {
rc = gnutls_record_send(*session, unsent, len);
crm_debug("Sent %d bytes", rc);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_debug("Retry");
} else if (rc < 0) {
crm_debug("Connection terminated");
break;
} else if (rc < len) {
crm_debug("Only sent %d of %d bytes", rc, len);
len -= rc;
unsent += rc;
} else {
break;
}
}
}
free(xml_text);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_send_tls(gnutls_session * session, xmlNode * msg)
static int
crm_send_tls(gnutls_session * session, const char *buf, size_t len)
{
const char *unsent = buf;
int rc = 0;
int total_send;
if (buf == NULL) {
return -1;
}
total_send = len;
crm_trace("Message size: %d", len);
while (TRUE) {
rc = gnutls_record_send(*session, unsent, len);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_debug("Retry");
} else if (rc < 0) {
crm_err("Connection terminated rc = %d", rc);
break;
} else if (rc < len) {
crm_debug("Only sent %d of %d bytes", rc, len);
len -= rc;
unsent += rc;
} else {
crm_debug("Sent %d bytes", rc);
break;
}
}
return rc < 0 ? rc : total_send;
}
| 166,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
const Extension* extension) {
bool has_permission = extension && extension->HasAPIPermissionForTab(
GetTabId(contents), APIPermission::kTab);
return CreateTabValue(contents, tab_strip, tab_index,
has_permission ? INCLUDE_PRIVACY_SENSITIVE_FIELDS :
OMIT_PRIVACY_SENSITIVE_FIELDS);
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
const Extension* extension) {
DictionaryValue *result = CreateTabValue(contents, tab_strip, tab_index);
ScrubTabValueForExtension(contents, extension, result);
return result;
}
| 171,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int find_low_bit(unsigned int x)
{
int i;
for(i=0;i<=31;i++) {
if(x&(1<<i)) return i;
}
return 0;
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682 | static int find_low_bit(unsigned int x)
{
int i;
for(i=0;i<=31;i++) {
if(x&(1U<<(unsigned int)i)) return i;
}
return 0;
}
| 168,195 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length)
{
asn1_push_tag(data, ASN1_OCTET_STRING);
asn1_write(data, p, length);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399 | bool asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length)
{
if (!asn1_push_tag(data, ASN1_OCTET_STRING)) return false;
if (!asn1_write(data, p, length)) return false;
return asn1_pop_tag(data);
}
| 164,591 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::SetCryptohomeLibrary(
CryptohomeLibrary* library, bool own) {
library_->crypto_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::SetCryptohomeLibrary(
| 170,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: SPL_METHOD(SplFileInfo, getRealPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char buff[MAXPATHLEN];
char *filename;
zend_error_handling error_handling;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
}
if (intern->orig_path) {
filename = intern->orig_path;
} else {
filename = intern->file_name;
}
if (filename && VCWD_REALPATH(filename, buff)) {
#ifdef ZTS
if (VCWD_ACCESS(buff, F_OK)) {
RETVAL_FALSE;
} else
#endif
RETVAL_STRING(buff, 1);
} else {
RETVAL_FALSE;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileInfo, getRealPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char buff[MAXPATHLEN];
char *filename;
zend_error_handling error_handling;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
}
if (intern->orig_path) {
filename = intern->orig_path;
} else {
filename = intern->file_name;
}
if (filename && VCWD_REALPATH(filename, buff)) {
#ifdef ZTS
if (VCWD_ACCESS(buff, F_OK)) {
RETVAL_FALSE;
} else
#endif
RETVAL_STRING(buff, 1);
} else {
RETVAL_FALSE;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,039 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
while (begin && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
} else if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
} else if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
Commit Message: Fix #12239 - crash in the x86.nz assembler ##asm (#12252)
CWE ID: CWE-125 | static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
if (*begin > strlen (str)) {
return TT_EOF;
}
while (begin && str[*begin] && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
}
if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && str[*end] && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
}
if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
| 168,970 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, seek)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long line_pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) {
return;
}
if (line_pos < 0) {
zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos);
RETURN_FALSE;
}
spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC);
while(intern->u.file.current_line_num < line_pos) {
if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) {
break;
}
}
} /* }}} */
/* {{{ Function/Class/Method definitions */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, seek)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long line_pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) {
return;
}
if (line_pos < 0) {
zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos);
RETURN_FALSE;
}
spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC);
while(intern->u.file.current_line_num < line_pos) {
if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) {
break;
}
}
} /* }}} */
/* {{{ Function/Class/Method definitions */
| 167,068 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_seek (SF_PRIVATE *psf, sf_count_t position, int whence)
{
switch (whence)
{ case SEEK_SET :
if (position > SIGNED_SIZEOF (psf->header))
{ /* Too much header to cache so just seek instead. */
psf_fseek (psf, position, whence) ;
return ;
} ;
if (position > psf->headend)
psf->headend += psf_fread (psf->header + psf->headend, 1, position - psf->headend, psf) ;
psf->headindex = position ;
break ;
case SEEK_CUR :
if (psf->headindex + position < 0)
break ;
if (psf->headindex >= SIGNED_SIZEOF (psf->header))
{ psf_fseek (psf, position, whence) ;
return ;
} ;
if (psf->headindex + position <= psf->headend)
{ psf->headindex += position ;
break ;
} ;
if (psf->headindex + position > SIGNED_SIZEOF (psf->header))
{ /* Need to jump this without caching it. */
psf->headindex = psf->headend ;
psf_fseek (psf, position, SEEK_CUR) ;
break ;
} ;
psf->headend += psf_fread (psf->header + psf->headend, 1, position - (psf->headend - psf->headindex), psf) ;
psf->headindex = psf->headend ;
break ;
case SEEK_END :
default :
psf_log_printf (psf, "Bad whence param in header_seek().\n") ;
break ;
} ;
return ;
} /* header_seek */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_seek (SF_PRIVATE *psf, sf_count_t position, int whence)
{
switch (whence)
{ case SEEK_SET :
if (psf->header.indx + position >= psf->header.len)
psf_bump_header_allocation (psf, position) ;
if (position > psf->header.len)
{ /* Too much header to cache so just seek instead. */
psf_fseek (psf, position, whence) ;
return ;
} ;
if (position > psf->header.end)
psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, position - psf->header.end, psf) ;
psf->header.indx = position ;
break ;
case SEEK_CUR :
if (psf->header.indx + position >= psf->header.len)
psf_bump_header_allocation (psf, position) ;
if (psf->header.indx + position < 0)
break ;
if (psf->header.indx >= psf->header.len)
{ psf_fseek (psf, position, whence) ;
return ;
} ;
if (psf->header.indx + position <= psf->header.end)
{ psf->header.indx += position ;
break ;
} ;
if (psf->header.indx + position > psf->header.len)
{ /* Need to jump this without caching it. */
psf->header.indx = psf->header.end ;
psf_fseek (psf, position, SEEK_CUR) ;
break ;
} ;
psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, position - (psf->header.end - psf->header.indx), psf) ;
psf->header.indx = psf->header.end ;
break ;
case SEEK_END :
default :
psf_log_printf (psf, "Bad whence param in header_seek().\n") ;
break ;
} ;
return ;
} /* header_seek */
| 170,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: receive_carbon(void **state)
{
prof_input("/carbons on");
prof_connect();
assert_true(stbbr_received(
"<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>"
));
stbbr_send(
"<presence to='stabber@localhost' from='buddy1@localhost/mobile'>"
"<priority>10</priority>"
"<status>On my mobile</status>"
"</presence>"
);
assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\""));
prof_input("/msg Buddy1");
assert_true(prof_output_exact("unencrypted"));
stbbr_send(
"<message type='chat' to='stabber@localhost/profanity' from='buddy1@localhost'>"
"<received xmlns='urn:xmpp:carbons:2'>"
"<forwarded xmlns='urn:xmpp:forward:0'>"
"<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>"
"<body>test carbon from recipient</body>"
"</message>"
"</forwarded>"
"</received>"
"</message>"
);
assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient"));
}
Commit Message: Add carbons from check
CWE ID: CWE-346 | receive_carbon(void **state)
{
prof_input("/carbons on");
prof_connect();
assert_true(stbbr_received(
"<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>"
));
stbbr_send(
"<presence to='stabber@localhost' from='buddy1@localhost/mobile'>"
"<priority>10</priority>"
"<status>On my mobile</status>"
"</presence>"
);
assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\""));
prof_input("/msg Buddy1");
assert_true(prof_output_exact("unencrypted"));
stbbr_send(
"<message type='chat' to='stabber@localhost/profanity' from='stabber@localhost'>"
"<received xmlns='urn:xmpp:carbons:2'>"
"<forwarded xmlns='urn:xmpp:forward:0'>"
"<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>"
"<body>test carbon from recipient</body>"
"</message>"
"</forwarded>"
"</received>"
"</message>"
);
assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient"));
}
| 168,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190 | static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
| 168,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unix_client_connect(hsm_com_client_hdl_t *hdl)
{
int fd, len;
struct sockaddr_un unix_addr;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
{
return HSM_COM_ERROR;
}
memset(&unix_addr,0,sizeof(unix_addr));
unix_addr.sun_family = AF_UNIX;
if(strlen(hdl->c_path) >= sizeof(unix_addr.sun_path))
{
close(fd);
return HSM_COM_PATH_ERR;
}
snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s", hdl->c_path);
len = SUN_LEN(&unix_addr);
unlink(unix_addr.sun_path);
if(bind(fd, (struct sockaddr *)&unix_addr, len) < 0)
{
unlink(hdl->c_path);
close(fd);
return HSM_COM_BIND_ERR;
}
if(chmod(unix_addr.sun_path, S_IRWXU) < 0)
{
unlink(hdl->c_path);
close(fd);
return HSM_COM_CHMOD_ERR;
}
memset(&unix_addr,0,sizeof(unix_addr));
unix_addr.sun_family = AF_UNIX;
strncpy(unix_addr.sun_path, hdl->s_path, sizeof(unix_addr.sun_path));
unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0;
len = SUN_LEN(&unix_addr);
if (connect(fd, (struct sockaddr *) &unix_addr, len) < 0)
{
unlink(hdl->c_path);
close(fd);
return HSM_COM_CONX_ERR;
}
hdl->client_fd = fd;
hdl->client_state = HSM_COM_C_STATE_CT;
if(unix_sck_send_conn(hdl, 2) != HSM_COM_OK)
{
hdl->client_state = HSM_COM_C_STATE_IN;
return HSM_COM_SEND_ERR;
}
return HSM_COM_OK;
}
Commit Message: Fix scripts and code that use well-known tmp files.
CWE ID: CWE-362 | unix_client_connect(hsm_com_client_hdl_t *hdl)
{
int fd, len;
struct sockaddr_un unix_addr;
hsm_com_errno_t res = HSM_COM_OK;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
{
return HSM_COM_ERROR;
}
memset(&unix_addr,0,sizeof(unix_addr));
unix_addr.sun_family = AF_UNIX;
if(strlen(hdl->c_path) >= sizeof(unix_addr.sun_path))
{
res = HSM_COM_PATH_ERR;
goto cleanup;
}
snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s", hdl->c_path);
len = SUN_LEN(&unix_addr);
unlink(unix_addr.sun_path);
if(bind(fd, (struct sockaddr *)&unix_addr, len) < 0)
{
res = HSM_COM_BIND_ERR;
goto cleanup;
}
if(chmod(unix_addr.sun_path, S_IRWXU) < 0)
{
res = HSM_COM_CHMOD_ERR;
goto cleanup;
}
memset(&unix_addr,0,sizeof(unix_addr));
unix_addr.sun_family = AF_UNIX;
strncpy(unix_addr.sun_path, hdl->s_path, sizeof(unix_addr.sun_path));
unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0;
len = SUN_LEN(&unix_addr);
if (connect(fd, (struct sockaddr *) &unix_addr, len) < 0)
{
res = HSM_COM_CONX_ERR;
goto cleanup;
}
hdl->client_fd = fd;
hdl->client_state = HSM_COM_C_STATE_CT;
if(unix_sck_send_conn(hdl, 2) != HSM_COM_OK)
{
hdl->client_state = HSM_COM_C_STATE_IN;
res = HSM_COM_SEND_ERR;
}
return res;
cleanup:
close(fd);
return res;
}
| 170,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: static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ip))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(e))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
| 167,368 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) {
TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram");
SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime");
api()->glLinkProgramFn(GetProgramServiceID(program, resources_));
ExitCommandProcessingEarly();
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) {
TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram");
SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime");
GLuint program_service_id = GetProgramServiceID(program, resources_);
api()->glLinkProgramFn(program_service_id);
ExitCommandProcessingEarly();
linking_program_service_id_ = program_service_id;
return error::kNoError;
}
| 172,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos,
long long size) {
assert(pReader);
assert(pos >= 0);
if ((size <= 0) || (size > 8))
return E_FILE_FORMAT_INVALID;
long long result = 0;
for (long long i = 0; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return result;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos,
long long UnserializeUInt(IMkvReader* pReader, long long pos, long long size) {
if (!pReader || pos < 0 || (size <= 0) || (size > 8))
return E_FILE_FORMAT_INVALID;
long long result = 0;
for (long long i = 0; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return result;
}
| 173,868 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.