instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
gfx::SizeF contents_size_dip,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_updateScrollState(env,
obj.obj(),
max_scroll_offset.x(),
max_scroll_offset.y(),
contents_size_dip.width(),
contents_size_dip.height(),
page_scale_factor,
min_page_scale_factor,
max_page_scale_factor);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
void AwContents::UpdateScrollState(const gfx::Vector2d& max_scroll_offset,
const gfx::SizeF& contents_size_dip,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_updateScrollState(env,
obj.obj(),
max_scroll_offset.x(),
max_scroll_offset.y(),
contents_size_dip.width(),
contents_size_dip.height(),
page_scale_factor,
min_page_scale_factor,
max_page_scale_factor);
}
| 171,618
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ExtensionTtsPlatformImpl::set_error(const std::string& error) {
error_ = error;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ExtensionTtsPlatformImpl::set_error(const std::string& error) {
| 170,395
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link;
RING_FOREACH(link, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
Commit Message:
CWE ID: CWE-399
|
void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link, *next;
RING_FOREACH_SAFE(link, next, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
| 164,663
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SchedulerObject::remove(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!abortJob(id.cluster,
id.proc,
reason.c_str(),
true // Always perform within a transaction
)) {
text = "Failed to remove job";
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-20
|
SchedulerObject::remove(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!abortJob(id.cluster,
id.proc,
reason.c_str(),
true // Always perform within a transaction
)) {
text = "Failed to remove job";
return false;
}
return true;
}
| 164,834
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int er_supported(ERContext *s)
{
if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice ||
!s->cur_pic.f ||
s->cur_pic.field_picture ||
s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO
)
return 0;
return 1;
}
Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile
The profile field is changed by code inside and outside the decoder,
its not a reliable indicator of the internal codec state.
Maintaining it consistency with studio_profile is messy.
Its easier to just avoid it and use only studio_profile
Fixes: assertion failure
Fixes: ffmpeg_crash_9.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-617
|
static int er_supported(ERContext *s)
{
if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice ||
!s->cur_pic.f ||
s->cur_pic.field_picture
)
return 0;
return 1;
}
| 169,154
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int flush_completed_IO(struct inode *inode)
{
ext4_io_end_t *io;
int ret = 0;
int ret2 = 0;
if (list_empty(&EXT4_I(inode)->i_completed_io_list))
return ret;
dump_completed_IO(inode);
while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){
io = list_entry(EXT4_I(inode)->i_completed_io_list.next,
ext4_io_end_t, list);
/*
* Calling ext4_end_io_nolock() to convert completed
* IO to written.
*
* When ext4_sync_file() is called, run_queue() may already
* about to flush the work corresponding to this io structure.
* It will be upset if it founds the io structure related
* to the work-to-be schedule is freed.
*
* Thus we need to keep the io structure still valid here after
* convertion finished. The io structure has a flag to
* avoid double converting from both fsync and background work
* queue work.
*/
ret = ext4_end_io_nolock(io);
if (ret < 0)
ret2 = ret;
else
list_del_init(&io->list);
}
return (ret2 < 0) ? ret2 : 0;
}
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 <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
int flush_completed_IO(struct inode *inode)
{
ext4_io_end_t *io;
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned long flags;
int ret = 0;
int ret2 = 0;
if (list_empty(&ei->i_completed_io_list))
return ret;
dump_completed_IO(inode);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
while (!list_empty(&ei->i_completed_io_list)){
io = list_entry(ei->i_completed_io_list.next,
ext4_io_end_t, list);
/*
* Calling ext4_end_io_nolock() to convert completed
* IO to written.
*
* When ext4_sync_file() is called, run_queue() may already
* about to flush the work corresponding to this io structure.
* It will be upset if it founds the io structure related
* to the work-to-be schedule is freed.
*
* Thus we need to keep the io structure still valid here after
* convertion finished. The io structure has a flag to
* avoid double converting from both fsync and background work
* queue work.
*/
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
ret = ext4_end_io_nolock(io);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
if (ret < 0)
ret2 = ret;
else
list_del_init(&io->list);
}
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
return (ret2 < 0) ? ret2 : 0;
}
| 167,550
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
Commit Message:
CWE ID: CWE-189
|
tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
| 164,739
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_terminate (MyObject *obj, GError **error)
{
g_main_loop_quit (loop);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_terminate (MyObject *obj, GError **error)
| 165,123
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SPL_METHOD(DirectoryIterator, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(DirectoryIterator, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
| 167,033
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
return ch;
}
Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk
This helps protect against bugs where any part of a buf_t's memory
is passed to a function that expects a NUL-terminated input.
It also closes TROVE-2016-10-001 (aka bug 20384).
CWE ID: CWE-119
|
chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
CHUNK_SET_SENTINEL(ch, alloc);
return ch;
}
| 168,758
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: allocate(struct file *file, int allocate_idat)
{
struct control *control = png_voidcast(struct control*, file->alloc_ptr);
if (allocate_idat)
{
assert(file->idat == NULL);
IDAT_init(&control->idat, file);
}
else /* chunk */
{
assert(file->chunk == NULL);
chunk_init(&control->chunk, file);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
allocate(struct file *file, int allocate_idat)
{
struct control *control = voidcast(struct control*, file->alloc_ptr);
if (allocate_idat)
{
assert(file->idat == NULL);
IDAT_init(&control->idat, file);
}
else /* chunk */
{
assert(file->chunk == NULL);
chunk_init(&control->chunk, file);
}
}
| 173,729
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20
|
void SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
bool SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,182
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void __init proc_root_init(void)
{
struct vfsmount *mnt;
int err;
proc_init_inodecache();
err = register_filesystem(&proc_fs_type);
if (err)
return;
mnt = kern_mount_data(&proc_fs_type, &init_pid_ns);
if (IS_ERR(mnt)) {
unregister_filesystem(&proc_fs_type);
return;
}
init_pid_ns.proc_mnt = mnt;
proc_symlink("mounts", NULL, "self/mounts");
proc_net_init();
#ifdef CONFIG_SYSVIPC
proc_mkdir("sysvipc", NULL);
#endif
proc_mkdir("fs", NULL);
proc_mkdir("driver", NULL);
proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */
#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)
/* just give it a mountpoint */
proc_mkdir("openprom", NULL);
#endif
proc_tty_init();
#ifdef CONFIG_PROC_DEVICETREE
proc_device_tree_init();
#endif
proc_mkdir("bus", NULL);
proc_sys_init();
}
Commit Message: procfs: fix a vfsmount longterm reference leak
kern_mount() doesn't pair with plain mntput()...
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-119
|
void __init proc_root_init(void)
{
int err;
proc_init_inodecache();
err = register_filesystem(&proc_fs_type);
if (err)
return;
err = pid_ns_prepare_proc(&init_pid_ns);
if (err) {
unregister_filesystem(&proc_fs_type);
return;
}
proc_symlink("mounts", NULL, "self/mounts");
proc_net_init();
#ifdef CONFIG_SYSVIPC
proc_mkdir("sysvipc", NULL);
#endif
proc_mkdir("fs", NULL);
proc_mkdir("driver", NULL);
proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */
#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)
/* just give it a mountpoint */
proc_mkdir("openprom", NULL);
#endif
proc_tty_init();
#ifdef CONFIG_PROC_DEVICETREE
proc_device_tree_init();
#endif
proc_mkdir("bus", NULL);
proc_sys_init();
}
| 165,615
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->location());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
R=jochen@chromium.org
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->location());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
| 171,685
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx,
Flow *f,
uint8_t *buf, uint32_t buflen,
uint8_t ipproto, uint8_t direction)
{
SCEnter();
SCLogDebug("buflen %u for %s direction", buflen,
(direction & STREAM_TOSERVER) ? "toserver" : "toclient");
AppProto alproto = ALPROTO_UNKNOWN;
if (!FLOW_IS_PM_DONE(f, direction)) {
AppProto pm_results[ALPROTO_MAX];
uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f,
buf, buflen,
direction,
ipproto,
pm_results);
if (pm_matches > 0) {
alproto = pm_results[0];
goto end;
}
}
if (!FLOW_IS_PP_DONE(f, direction)) {
alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen,
ipproto, direction);
if (alproto != ALPROTO_UNKNOWN)
goto end;
}
/* Look if flow can be found in expectation list */
if (!FLOW_IS_PE_DONE(f, direction)) {
alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction);
}
end:
SCReturnUInt(alproto);
}
Commit Message: proto/detect: workaround dns misdetected as dcerpc
The DCERPC UDP detection would misfire on DNS with transaction
ID 0x0400. This would happen as the protocol detection engine
gives preference to pattern based detection over probing parsers for
performance reasons.
This hack/workaround fixes this specific case by still running the
probing parser if DCERPC has been detected on UDP. The probing
parser result will take precedence.
Bug #2736.
CWE ID: CWE-20
|
AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx,
Flow *f,
uint8_t *buf, uint32_t buflen,
uint8_t ipproto, uint8_t direction)
{
SCEnter();
SCLogDebug("buflen %u for %s direction", buflen,
(direction & STREAM_TOSERVER) ? "toserver" : "toclient");
AppProto alproto = ALPROTO_UNKNOWN;
AppProto pm_alproto = ALPROTO_UNKNOWN;
if (!FLOW_IS_PM_DONE(f, direction)) {
AppProto pm_results[ALPROTO_MAX];
uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f,
buf, buflen,
direction,
ipproto,
pm_results);
if (pm_matches > 0) {
alproto = pm_results[0];
/* HACK: if detected protocol is dcerpc/udp, we run PP as well
* to avoid misdetecting DNS as DCERPC. */
if (!(ipproto == IPPROTO_UDP && alproto == ALPROTO_DCERPC))
goto end;
pm_alproto = alproto;
/* fall through */
}
}
if (!FLOW_IS_PP_DONE(f, direction)) {
alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen,
ipproto, direction);
if (alproto != ALPROTO_UNKNOWN)
goto end;
}
/* Look if flow can be found in expectation list */
if (!FLOW_IS_PE_DONE(f, direction)) {
alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction);
}
end:
if (alproto == ALPROTO_UNKNOWN)
alproto = pm_alproto;
SCReturnUInt(alproto);
}
| 170,179
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void destroy_server_connect(SERVER_CONNECT_REC *conn)
{
IRC_SERVER_CONNECT_REC *ircconn;
ircconn = IRC_SERVER_CONNECT(conn);
if (ircconn == NULL)
return;
g_free_not_null(ircconn->usermode);
g_free_not_null(ircconn->alternate_nick);
}
Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect
copy sasl username and password values
CWE ID: CWE-416
|
static void destroy_server_connect(SERVER_CONNECT_REC *conn)
{
IRC_SERVER_CONNECT_REC *ircconn;
ircconn = IRC_SERVER_CONNECT(conn);
if (ircconn == NULL)
return;
g_free_not_null(ircconn->usermode);
g_free_not_null(ircconn->alternate_nick);
g_free_not_null(ircconn->sasl_username);
g_free_not_null(ircconn->sasl_password);
}
| 169,642
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType)
{
bool errorOccurred = false;
double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0;
ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred);
pendingScript.stopWatchingForLoad(this);
if (!isExecutingScript()) {
Microtask::performCheckpoint();
if (pendingScriptType == PendingScript::ParsingBlocking) {
m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady();
if (m_hasScriptsWaitingForResources)
return;
}
}
RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear();
double compilationFinishTime = 0;
if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) {
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document);
if (errorOccurred)
scriptLoader->dispatchErrorEvent();
else {
ASSERT(isExecutingScript());
if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) {
scriptLoader->dispatchErrorEvent();
} else {
element->dispatchEvent(createScriptLoadEvent());
}
}
}
const double epsilon = 1;
if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) {
Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50);
}
ASSERT(!isExecutingScript());
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
R=haraken@chromium.org
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254
|
void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType)
{
bool errorOccurred = false;
double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0;
ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred);
pendingScript.stopWatchingForLoad(this);
if (!isExecutingScript()) {
Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate());
if (pendingScriptType == PendingScript::ParsingBlocking) {
m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady();
if (m_hasScriptsWaitingForResources)
return;
}
}
RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear();
double compilationFinishTime = 0;
if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) {
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document);
if (errorOccurred)
scriptLoader->dispatchErrorEvent();
else {
ASSERT(isExecutingScript());
if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) {
scriptLoader->dispatchErrorEvent();
} else {
element->dispatchEvent(createScriptLoadEvent());
}
}
}
const double epsilon = 1;
if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) {
Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50);
}
ASSERT(!isExecutingScript());
}
| 171,946
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
{
ASSERT(!m_isDestroyingShadowSubtree);
m_isDestroyingShadowSubtree = true;
if (SpinButtonElement* element = spinButtonElement())
element->removeSpinButtonOwner();
if (ClearButtonElement* element = clearButtonElement())
element->removeClearButtonOwner();
if (DateTimeEditElement* element = dateTimeEditElement())
element->removeEditControlOwner();
if (PickerIndicatorElement* element = pickerIndicatorElement())
element->removePickerIndicatorOwner();
if (element()->focused())
element()->focus();
BaseDateAndTimeInputType::destroyShadowSubtree();
m_isDestroyingShadowSubtree = false;
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
{
ASSERT(!m_isDestroyingShadowSubtree);
m_isDestroyingShadowSubtree = true;
if (SpinButtonElement* element = spinButtonElement())
element->removeSpinButtonOwner();
if (ClearButtonElement* element = clearButtonElement())
element->removeClearButtonOwner();
if (DateTimeEditElement* element = dateTimeEditElement())
element->removeEditControlOwner();
if (PickerIndicatorElement* element = pickerIndicatorElement())
element->removePickerIndicatorOwner();
if (containsFocusedShadowElement())
element()->focus();
BaseDateAndTimeInputType::destroyShadowSubtree();
m_isDestroyingShadowSubtree = false;
}
| 171,210
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
| 174,502
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int v, i;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (length > 256 || !(s->state & PNG_PLTE))
return AVERROR_INVALIDDATA;
for (i = 0; i < length; i++) {
v = bytestream2_get_byte(&s->gb);
s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
}
} else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
(s->color_type == PNG_COLOR_TYPE_RGB && length != 6))
return AVERROR_INVALIDDATA;
for (i = 0; i < length / 2; i++) {
/* only use the least significant bits */
v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
if (s->bit_depth > 8)
AV_WB16(&s->transparent_color_be[2 * i], v);
else
s->transparent_color_be[i] = v;
}
} else {
return AVERROR_INVALIDDATA;
}
bytestream2_skip(&s->gb, 4); /* crc */
s->has_trns = 1;
return 0;
}
Commit Message: avcodec/pngdec: Check trns more completely
Fixes out of array access
Fixes: 546/clusterfuzz-testcase-4809433909559296
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-787
|
static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int v, i;
if (!(s->state & PNG_IHDR)) {
av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
return AVERROR_INVALIDDATA;
}
if (s->state & PNG_IDAT) {
av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
return AVERROR_INVALIDDATA;
}
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (length > 256 || !(s->state & PNG_PLTE))
return AVERROR_INVALIDDATA;
for (i = 0; i < length; i++) {
v = bytestream2_get_byte(&s->gb);
s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
}
} else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
(s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
s->bit_depth == 1)
return AVERROR_INVALIDDATA;
for (i = 0; i < length / 2; i++) {
/* only use the least significant bits */
v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
if (s->bit_depth > 8)
AV_WB16(&s->transparent_color_be[2 * i], v);
else
s->transparent_color_be[i] = v;
}
} else {
return AVERROR_INVALIDDATA;
}
bytestream2_skip(&s->gb, 4); /* crc */
s->has_trns = 1;
return 0;
}
| 168,248
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: mark_trusted_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20
|
mark_trusted_task_done (GObject *source_object,
mark_desktop_file_executable_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
| 167,749
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if ((*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length
Add check for packets that report zero packet length. Example
of fix:
src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null
Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets.
safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0
CWE ID: CWE-125
|
int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
| 168,947
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DaemonProcessTest::LaunchNetworkProcess() {
terminal_id_ = 0;
daemon_process_->OnChannelConnected();
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void DaemonProcessTest::LaunchNetworkProcess() {
terminal_id_ = 0;
daemon_process_->OnChannelConnected(0);
}
| 171,541
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
(void)s;
if (sp->libjpeg_jpeg_query_style==0)
{
if (OJPEGDecodeRaw(tif,buf,cc)==0)
return(0);
}
else
{
if (OJPEGDecodeScanlines(tif,buf,cc)==0)
return(0);
}
return(1);
}
Commit Message: * libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in
OJPEGPreDecode(). This will avoid a divide by zero, and potential other issues.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2611
CWE ID: CWE-369
|
OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
{
static const char module[]="OJPEGDecode";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
(void)s;
if( !sp->decoder_ok )
{
TIFFErrorExt(tif->tif_clientdata,module,"Cannot decode: decoder not correctly initialized");
return 0;
}
if (sp->libjpeg_jpeg_query_style==0)
{
if (OJPEGDecodeRaw(tif,buf,cc)==0)
return(0);
}
else
{
if (OJPEGDecodeScanlines(tif,buf,cc)==0)
return(0);
}
return(1);
}
| 168,468
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
bool profiling, const std::string& filename_prefix) {
#if !defined(OS_WIN)
if (profiling)
HeapProfilerStart(filename_prefix.c_str());
else
HeapProfilerStop();
#endif
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
TBR=darin@chromium.org
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
| 170,666
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void MaybeRestoreIBusConfig() {
if (!ibus_) {
return;
}
MaybeDestroyIBusConfig();
if (!ibus_config_) {
GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_);
if (!ibus_connection) {
LOG(INFO) << "Couldn't create an ibus config object since "
<< "IBus connection is not ready.";
return;
}
const gboolean disconnected
= g_dbus_connection_is_closed(ibus_connection);
if (disconnected) {
LOG(ERROR) << "Couldn't create an ibus config object since "
<< "IBus connection is closed.";
return;
}
ibus_config_ = ibus_config_new(ibus_connection,
NULL /* do not cancel the operation */,
NULL /* do not get error information */);
if (!ibus_config_) {
LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?";
return;
}
g_object_ref(ibus_config_);
LOG(INFO) << "ibus_config_ is ready.";
}
}
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 MaybeRestoreIBusConfig() {
if (!ibus_) {
return;
}
MaybeDestroyIBusConfig();
if (!ibus_config_) {
GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_);
if (!ibus_connection) {
VLOG(1) << "Couldn't create an ibus config object since "
<< "IBus connection is not ready.";
return;
}
const gboolean disconnected
= g_dbus_connection_is_closed(ibus_connection);
if (disconnected) {
LOG(ERROR) << "Couldn't create an ibus config object since "
<< "IBus connection is closed.";
return;
}
ibus_config_ = ibus_config_new(ibus_connection,
NULL /* do not cancel the operation */,
NULL /* do not get error information */);
if (!ibus_config_) {
LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?";
return;
}
g_object_ref(ibus_config_);
VLOG(1) << "ibus_config_ is ready.";
}
}
| 170,543
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION,
SyncPromoUI::SOURCE_UNKNOWN);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
| 171,247
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SecurityContext::SecurityContext()
: m_mayDisplaySeamlesslyWithParent(false)
, m_haveInitializedSecurityOrigin(false)
, m_sandboxFlags(SandboxNone)
{
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
R=haraken@chromium.org, abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
|
SecurityContext::SecurityContext()
: m_haveInitializedSecurityOrigin(false)
, m_sandboxFlags(SandboxNone)
{
}
| 170,700
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: stringprep (char *in,
size_t maxlen,
Stringprep_profile_flags flags,
const Stringprep_profile * profile)
{
int rc;
char *utf8 = NULL;
uint32_t *ucs4 = NULL;
size_t ucs4len, maxucs4len, adducs4len = 50;
do
{
uint32_t *newp;
free (ucs4);
ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len);
maxucs4len = ucs4len + adducs4len;
newp = realloc (ucs4, maxucs4len * sizeof (uint32_t));
if (!newp)
return STRINGPREP_MALLOC_ERROR;
}
ucs4 = newp;
rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile);
adducs4len += 50;
}
Commit Message:
CWE ID: CWE-119
|
stringprep (char *in,
size_t maxlen,
Stringprep_profile_flags flags,
const Stringprep_profile * profile)
{
int rc;
char *utf8 = NULL;
uint32_t *ucs4 = NULL;
size_t ucs4len, maxucs4len, adducs4len = 50;
do
{
uint32_t *newp;
free (ucs4);
ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len);
if (ucs4 == NULL)
return STRINGPREP_ICONV_ERROR;
maxucs4len = ucs4len + adducs4len;
newp = realloc (ucs4, maxucs4len * sizeof (uint32_t));
if (!newp)
return STRINGPREP_MALLOC_ERROR;
}
ucs4 = newp;
rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile);
adducs4len += 50;
}
| 164,762
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() {
DCHECK(MediaElement());
return (MediaElement()->GetWebMediaPlayer() &&
MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) ||
passes_current_src_cors_access_check_;
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Reviewed-by: Yutaka Hirano <yhirano@chromium.org>
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20
|
bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() {
| 173,147
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PrefService* DataReductionProxySettings::GetOriginalProfilePrefs() {
DCHECK(thread_checker_.CalledOnValidThread());
return prefs_;
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
PrefService* DataReductionProxySettings::GetOriginalProfilePrefs() {
PrefService* DataReductionProxySettings::GetOriginalProfilePrefs() const {
DCHECK(thread_checker_.CalledOnValidThread());
return prefs_;
}
| 172,551
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AudioOutputDevice::ShutDownOnIOThread() {
DCHECK(message_loop()->BelongsToCurrentThread());
if (stream_id_) {
is_started_ = false;
if (ipc_) {
ipc_->CloseStream(stream_id_);
ipc_->RemoveDelegate(stream_id_);
}
stream_id_ = 0;
}
base::AutoLock auto_lock_(audio_thread_lock_);
if (!audio_thread_.get())
return;
base::ThreadRestrictions::ScopedAllowIO allow_io;
audio_thread_->Stop(NULL);
audio_thread_.reset();
audio_callback_.reset();
}
Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call.
I've kept my unit test changes intact but disabled until I get a proper fix.
BUG=147499,150805
TBR=henrika
Review URL: https://codereview.chromium.org/10946040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
void AudioOutputDevice::ShutDownOnIOThread() {
DCHECK(message_loop()->BelongsToCurrentThread());
if (stream_id_) {
is_started_ = false;
if (ipc_) {
ipc_->CloseStream(stream_id_);
ipc_->RemoveDelegate(stream_id_);
}
stream_id_ = 0;
}
base::ThreadRestrictions::ScopedAllowIO allow_io;
audio_thread_.Stop(NULL);
audio_callback_.reset();
}
| 170,706
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(data_reduction_proxy_service_->compression_stats());
if (spdy_proxy_auth_enabled_.GetValue() != enabled) {
spdy_proxy_auth_enabled_.SetValue(enabled);
OnProxyEnabledPrefChange();
#if defined(OS_ANDROID)
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(enabled);
#endif // defined(OS_ANDROID)
}
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(data_reduction_proxy_service_->compression_stats());
if (GetOriginalProfilePrefs()->GetBoolean(prefs::kDataSaverEnabled) !=
enabled) {
GetOriginalProfilePrefs()->SetBoolean(prefs::kDataSaverEnabled, enabled);
OnProxyEnabledPrefChange();
#if defined(OS_ANDROID)
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(enabled);
#endif // defined(OS_ANDROID)
}
}
| 172,558
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cib_recv_plaintext(int sock)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = 512;
buf = calloc(1, chunk_size);
while (1) {
errno = 0;
rc = read(sock, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
if (errno == EINTR || errno == EAGAIN) {
crm_trace("Retry: %d", (int)rc);
if (rc > 0) {
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
}
} else if (rc < 0) {
crm_perror(LOG_ERR, "Error receiving message: %d", (int)rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_recv_plaintext(int sock)
/*!
* \internal
* \brief Read bytes off non blocking socket.
*
* \param session - tls session to read
* \param max_size - max bytes allowed to read for buffer. 0 assumes no limit
*
* \note only use with NON-Blocking sockets. Should only be used after polling socket.
* This function will return once max_size is met, the socket read buffer
* is empty, or an error is encountered.
*
* \retval '\0' terminated buffer on success
*/
static char *
crm_recv_plaintext(int sock, size_t max_size, size_t *recv_len, int *disconnected)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = max_size ? max_size : 1024;
size_t buf_size = 0;
size_t read_size = 0;
if (sock <= 0) {
if (disconnected) {
*disconnected = 1;
}
goto done;
}
buf = calloc(1, chunk_size + 1);
buf_size = chunk_size;
while (TRUE) {
errno = 0;
read_size = buf_size - len;
/* automatically grow the buffer when needed if max_size is not set.*/
if (!max_size && (read_size < (chunk_size / 2))) {
buf_size += chunk_size;
crm_trace("Grow buffer by %d more bytes. buf is now %d bytes", (int)chunk_size, buf_size);
buf = realloc(buf, buf_size + 1);
CRM_ASSERT(buf != NULL);
read_size = buf_size - len;
}
rc = read(sock, buf + len, chunk_size);
if (rc > 0) {
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
len += rc;
/* always null terminate buffer, the +1 to alloc always allows for this.*/
buf[len] = '\0';
}
if (max_size && (max_size == read_size)) {
crm_trace("Buffer max read size %d met" , max_size);
goto done;
}
if (rc > 0) {
continue;
} else if (rc == 0) {
if (disconnected) {
*disconnected = 1;
}
crm_trace("EOF encoutered during read");
goto done;
}
/* process errors */
if (errno == EINTR) {
crm_trace("EINTER encoutered, retry socket read.");
} else if (errno == EAGAIN) {
crm_trace("non-blocking, exiting read on rc = %d", rc);
goto done;
} else if (errno <= 0) {
if (disconnected) {
*disconnected = 1;
}
crm_debug("Error receiving message: %d", (int)rc);
goto done;
}
}
done:
if (recv_len) {
*recv_len = len;
}
if (!len) {
free(buf);
buf = NULL;
}
return buf;
}
| 166,158
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int NaClIPCAdapter::TakeClientFileDescriptor() {
return io_thread_data_.channel_->TakeClientFileDescriptor();
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
int NaClIPCAdapter::TakeClientFileDescriptor() {
| 170,731
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
return true;
}
Commit Message: Disable setxattr calls from quarantine subsystem on Chrome OS.
BUG=733943
Change-Id: I6e743469a8dc91536e180ecf4ff0df0cf427037c
Reviewed-on: https://chromium-review.googlesource.com/c/1380571
Commit-Queue: Will Harris <wfh@chromium.org>
Reviewed-by: Raymes Khoury <raymes@chromium.org>
Reviewed-by: David Trainor <dtrainor@chromium.org>
Reviewed-by: Thiemo Nagel <tnagel@chromium.org>
Cr-Commit-Position: refs/heads/master@{#617961}
CWE ID: CWE-200
|
bool SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
#if !defined(OS_CHROMEOS)
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
#endif // !defined(OS_CHROMEOS)
return true;
}
| 173,117
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ssh_packet_set_postauth(struct ssh *ssh)
{
struct sshcomp *comp;
int r, mode;
debug("%s: called", __func__);
/* This was set in net child, but is not visible in user child */
ssh->state->after_authentication = 1;
ssh->state->rekeying = 0;
for (mode = 0; mode < MODE_MAX; mode++) {
if (ssh->state->newkeys[mode] == NULL)
continue;
comp = &ssh->state->newkeys[mode]->comp;
if (comp && comp->enabled &&
(r = ssh_packet_init_compression(ssh)) != 0)
return r;
}
return 0;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
|
ssh_packet_set_postauth(struct ssh *ssh)
{
int r;
debug("%s: called", __func__);
/* This was set in net child, but is not visible in user child */
ssh->state->after_authentication = 1;
ssh->state->rekeying = 0;
if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
return r;
return 0;
}
| 168,655
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline int accept_server_socket(int s)
{
struct sockaddr_un client_address;
socklen_t clen;
int fd = accept(s, (struct sockaddr*)&client_address, &clen);
APPL_TRACE_DEBUG("accepted fd:%d for server fd:%d", fd, s);
return fd;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static inline int accept_server_socket(int s)
{
struct sockaddr_un client_address;
socklen_t clen;
int fd = TEMP_FAILURE_RETRY(accept(s, (struct sockaddr*)&client_address, &clen));
APPL_TRACE_DEBUG("accepted fd:%d for server fd:%d", fd, s);
return fd;
}
| 173,459
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
Commit Message: Fix #10091 - crash in AVR analysis
CWE ID: CWE-125
|
INST_HANDLER (sts) { // STS k, Rr
if (len < 4) {
return;
}
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
| 169,223
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_echo_variant (MyObject *obj, GValue *variant, GValue *ret, GError **error)
{
GType t;
t = G_VALUE_TYPE(variant);
g_value_init (ret, t);
g_value_copy (variant, ret);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_echo_variant (MyObject *obj, GValue *variant, GValue *ret, GError **error)
| 165,093
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_release(ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the 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 the buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb2_cache_entry *ce;
struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb2_cache_entry_find_first(ext2_mb_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
/*
* We have to be careful about races with freeing or
* rehashing of xattr block. Once we hold buffer lock
* xattr block's state is stable so we can check
* whether the block got freed / rehashed or not.
* Since we unhash mbcache entry under buffer lock when
* freeing / rehashing xattr block, checking whether
* entry is still hashed is reliable.
*/
if (hlist_bl_unhashed(&ce->e_hash_list)) {
mb2_cache_entry_put(ext2_mb_cache, ce);
unlock_buffer(bh);
brelse(bh);
goto again;
} else if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb2_cache_entry_touch(ext2_mb_cache, ce);
mb2_cache_entry_put(ext2_mb_cache, ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb2_cache_entry_find_next(ext2_mb_cache, ce);
}
return NULL;
}
| 169,977
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool GrabWindowSnapshot(gfx::NativeWindow window,
std::vector<unsigned char>* png_representation,
const gfx::Rect& snapshot_bounds) {
ui::Compositor* compositor = window->layer()->GetCompositor();
gfx::Rect read_pixels_bounds = snapshot_bounds;
read_pixels_bounds.set_origin(
snapshot_bounds.origin().Add(window->bounds().origin()));
gfx::Rect read_pixels_bounds_in_pixel =
ui::ConvertRectToPixel(window->layer(), read_pixels_bounds);
DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right());
DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom());
DCHECK_LE(0, read_pixels_bounds.x());
DCHECK_LE(0, read_pixels_bounds.y());
SkBitmap bitmap;
if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel))
return false;
unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels());
gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA,
read_pixels_bounds_in_pixel.size(),
bitmap.rowBytes(), true,
std::vector<gfx::PNGCodec::Comment>(),
png_representation);
return true;
}
Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS.
BUG=119492
TEST=manually done
Review URL: https://chromiumcodereview.appspot.com/10386124
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool GrabWindowSnapshot(gfx::NativeWindow window,
std::vector<unsigned char>* png_representation,
const gfx::Rect& snapshot_bounds) {
#if defined(OS_LINUX)
// We use XGetImage() for Linux/ChromeOS for performance reasons.
// See crbug.com/122720
if (window->GetRootWindow()->GrabSnapshot(
snapshot_bounds, png_representation))
return true;
#endif // OS_LINUX
ui::Compositor* compositor = window->layer()->GetCompositor();
gfx::Rect read_pixels_bounds = snapshot_bounds;
read_pixels_bounds.set_origin(
snapshot_bounds.origin().Add(window->bounds().origin()));
gfx::Rect read_pixels_bounds_in_pixel =
ui::ConvertRectToPixel(window->layer(), read_pixels_bounds);
DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right());
DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom());
DCHECK_LE(0, read_pixels_bounds.x());
DCHECK_LE(0, read_pixels_bounds.y());
SkBitmap bitmap;
if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel))
return false;
unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels());
gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA,
read_pixels_bounds_in_pixel.size(),
bitmap.rowBytes(), true,
std::vector<gfx::PNGCodec::Comment>(),
png_representation);
return true;
}
| 170,760
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssi_sd_state *s = (ssi_sd_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->mode = qemu_get_be32(f);
s->cmd = qemu_get_be32(f);
for (i = 0; i < 4; i++)
s->cmdarg[i] = qemu_get_be32(f);
for (i = 0; i < 5; i++)
s->response[i] = qemu_get_be32(f);
s->arglen = qemu_get_be32(f);
s->response_pos = qemu_get_be32(f);
s->stopping = qemu_get_be32(f);
ss->cs = qemu_get_be32(f);
s->mode = SSI_SD_CMD;
dinfo = drive_get_next(IF_SD);
s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true);
if (s->sd == NULL) {
return -1;
}
register_savevm(dev, "ssi_sd", -1, 1, ssi_sd_save, ssi_sd_load, s);
return 0;
}
Commit Message:
CWE ID: CWE-94
|
static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssi_sd_state *s = (ssi_sd_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->mode = qemu_get_be32(f);
s->cmd = qemu_get_be32(f);
for (i = 0; i < 4; i++)
s->cmdarg[i] = qemu_get_be32(f);
for (i = 0; i < 5; i++)
s->response[i] = qemu_get_be32(f);
s->arglen = qemu_get_be32(f);
if (s->mode == SSI_SD_CMDARG &&
(s->arglen < 0 || s->arglen >= ARRAY_SIZE(s->cmdarg))) {
return -EINVAL;
}
s->response_pos = qemu_get_be32(f);
s->stopping = qemu_get_be32(f);
if (s->mode == SSI_SD_RESPONSE &&
(s->response_pos < 0 || s->response_pos >= ARRAY_SIZE(s->response) ||
(!s->stopping && s->arglen > ARRAY_SIZE(s->response)))) {
return -EINVAL;
}
ss->cs = qemu_get_be32(f);
s->mode = SSI_SD_CMD;
dinfo = drive_get_next(IF_SD);
s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true);
if (s->sd == NULL) {
return -1;
}
register_savevm(dev, "ssi_sd", -1, 1, ssi_sd_save, ssi_sd_load, s);
return 0;
}
| 165,358
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void FrameSelection::Clear() {
granularity_ = TextGranularity::kCharacter;
if (granularity_strategy_)
granularity_strategy_->Clear();
SetSelection(SelectionInDOMTree());
}
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 <yosin@chromium.org>
Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org>
Reviewed-by: Kent Tamura <tkent@chromium.org>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
|
void FrameSelection::Clear() {
granularity_ = TextGranularity::kCharacter;
if (granularity_strategy_)
granularity_strategy_->Clear();
SetSelection(SelectionInDOMTree());
is_handle_visible_ = false;
}
| 171,754
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void *jas_malloc(size_t size)
{
void *result;
JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size));
result = malloc(size);
JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
return result;
}
Commit Message: Fixed an integer overflow problem.
CWE ID: CWE-190
|
void *jas_malloc(size_t size)
{
void *result;
JAS_DBGLOG(101, ("jas_malloc(%zu)\n", size));
result = malloc(size);
JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
return result;
}
| 168,474
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto out;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file))
rc = PTR_ERR(*lower_file);
out:
return rc;
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <jannh@google.com>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119
|
int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto have_file;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file)) {
rc = PTR_ERR(*lower_file);
goto out;
}
have_file:
if ((*lower_file)->f_op->mmap == NULL) {
fput(*lower_file);
*lower_file = NULL;
rc = -EMEDIUMTYPE;
}
out:
return rc;
}
| 167,443
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg ) );
#else
(void) md_alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#endif
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200
|
int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
MBEDTLS_MPI_CHK( ecdsa_sign_det_internal( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg,
f_rng, p_rng ) );
#else
(void) md_alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
| 170,182
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CrosLibrary::TestApi::SetUpdateLibrary(
UpdateLibrary* library, bool own) {
library_->update_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::SetUpdateLibrary(
| 170,649
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void EventBindings::AttachFilteredEvent(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_EQ(2, args.Length());
CHECK(args[0]->IsString());
CHECK(args[1]->IsObject());
std::string event_name = *v8::String::Utf8Value(args[0]);
if (!context()->HasAccessOrThrowError(event_name))
return;
std::unique_ptr<base::DictionaryValue> filter;
{
std::unique_ptr<content::V8ValueConverter> converter(
content::V8ValueConverter::create());
std::unique_ptr<base::Value> filter_value(converter->FromV8Value(
v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()));
if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) {
args.GetReturnValue().Set(static_cast<int32_t>(-1));
return;
}
filter = base::DictionaryValue::From(std::move(filter_value));
}
base::DictionaryValue* filter_weak = filter.get();
int id = g_event_filter.Get().AddEventMatcher(
event_name, ParseEventMatcher(std::move(filter)));
attached_matcher_ids_.insert(id);
std::string extension_id = context()->GetExtensionID();
if (AddFilter(event_name, extension_id, *filter_weak)) {
bool lazy = ExtensionFrameHelper::IsContextForEventPage(context());
content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
extension_id, event_name, *filter_weak, lazy));
}
args.GetReturnValue().Set(static_cast<int32_t>(id));
}
Commit Message: Ignore filtered event if an event matcher cannot be added.
BUG=625404
Review-Url: https://codereview.chromium.org/2236133002
Cr-Commit-Position: refs/heads/master@{#411472}
CWE ID: CWE-416
|
void EventBindings::AttachFilteredEvent(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_EQ(2, args.Length());
CHECK(args[0]->IsString());
CHECK(args[1]->IsObject());
std::string event_name = *v8::String::Utf8Value(args[0]);
if (!context()->HasAccessOrThrowError(event_name))
return;
std::unique_ptr<base::DictionaryValue> filter;
{
std::unique_ptr<content::V8ValueConverter> converter(
content::V8ValueConverter::create());
std::unique_ptr<base::Value> filter_value(converter->FromV8Value(
v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()));
if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) {
args.GetReturnValue().Set(static_cast<int32_t>(-1));
return;
}
filter = base::DictionaryValue::From(std::move(filter_value));
}
int id = g_event_filter.Get().AddEventMatcher(
event_name, ParseEventMatcher(std::move(filter)));
if (id == -1) {
args.GetReturnValue().Set(static_cast<int32_t>(-1));
return;
}
attached_matcher_ids_.insert(id);
const EventMatcher* matcher = g_event_filter.Get().GetEventMatcher(id);
DCHECK(matcher);
base::DictionaryValue* filter_weak = matcher->value();
std::string extension_id = context()->GetExtensionID();
if (AddFilter(event_name, extension_id, *filter_weak)) {
bool lazy = ExtensionFrameHelper::IsContextForEventPage(context());
content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
extension_id, event_name, *filter_weak, lazy));
}
args.GetReturnValue().Set(static_cast<int32_t>(id));
}
| 172,060
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GpuChannelHost::Connect(
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle client_process_for_gpu) {
DCHECK(factory_->IsMainThread());
scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
channel_.reset(new IPC::SyncChannel(
channel_handle, IPC::Channel::MODE_CLIENT, NULL,
io_loop, true,
factory_->GetShutDownEvent()));
sync_filter_ = new IPC::SyncMessageFilter(
factory_->GetShutDownEvent());
channel_->AddFilter(sync_filter_.get());
channel_filter_ = new MessageFilter(this);
channel_->AddFilter(channel_filter_.get());
state_ = kConnected;
Send(new GpuChannelMsg_Initialize(client_process_for_gpu));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void GpuChannelHost::Connect(
const IPC::ChannelHandle& channel_handle) {
DCHECK(factory_->IsMainThread());
scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
channel_.reset(new IPC::SyncChannel(
channel_handle, IPC::Channel::MODE_CLIENT, NULL,
io_loop, true,
factory_->GetShutDownEvent()));
sync_filter_ = new IPC::SyncMessageFilter(
factory_->GetShutDownEvent());
channel_->AddFilter(sync_filter_.get());
channel_filter_ = new MessageFilter(this);
channel_->AddFilter(channel_filter_.get());
state_ = kConnected;
}
| 170,928
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
sock_put(sk);
}
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <zzoru007@gmail.com>
Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Signed-off-by: Willem de Bruijn <willemb@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-125
|
void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
sock_put(sk);
}
}
| 170,073
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb->sk = sk;
llc_sap_state_process(sap, skb);
}
Commit Message: net/llc: avoid BUG_ON() in skb_orphan()
It seems nobody used LLC since linux-3.12.
Fortunately fuzzers like syzkaller still know how to run this code,
otherwise it would be no fun.
Setting skb->sk without skb->destructor leads to all kinds of
bugs, we now prefer to be very strict about it.
Ideally here we would use skb_set_owner() but this helper does not exist yet,
only CAN seems to have a private helper for that.
Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()")
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20
|
static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb_orphan(skb);
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_efree;
llc_sap_state_process(sap, skb);
}
| 168,349
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void perform_gamma_sbit_tests(png_modifier *pm)
{
png_byte sbit;
/* The only interesting cases are colour and grayscale, alpha is ignored here
* for overall speed. Only bit depths where sbit is less than the bit depth
* are tested.
*/
for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
{
png_byte colour_type = 0, bit_depth = 0;
unsigned int npalette = 0;
while (next_format(&colour_type, &bit_depth, &npalette, 1/*gamma*/))
if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
((colour_type == 3 && sbit < 8) ||
(colour_type != 3 && sbit < bit_depth)))
{
unsigned int i;
for (i=0; i<pm->ngamma_tests; ++i)
{
unsigned int j;
for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, npalette,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
static void perform_gamma_sbit_tests(png_modifier *pm)
{
png_byte sbit;
/* The only interesting cases are colour and grayscale, alpha is ignored here
* for overall speed. Only bit depths where sbit is less than the bit depth
* are tested.
*/
for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
{
png_byte colour_type = 0, bit_depth = 0;
unsigned int npalette = 0;
while (next_format(&colour_type, &bit_depth, &npalette,
pm->test_lbg_gamma_sbit, pm->test_tRNS))
if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
((colour_type == 3 && sbit < 8) ||
(colour_type != 3 && sbit < bit_depth)))
{
unsigned int i;
for (i=0; i<pm->ngamma_tests; ++i)
{
unsigned int j;
for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, npalette,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
}
| 173,680
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
Commit Message:
CWE ID: CWE-20
|
validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen < 0 || screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
| 165,270
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: on_response(void *data, krb5_error_code retval, otp_response response)
{
struct request_state rs = *(struct request_state *)data;
free(data);
if (retval == 0 && response != otp_response_success)
retval = KRB5_PREAUTH_FAILED;
rs.respond(rs.arg, retval, NULL, NULL, NULL);
}
Commit Message: Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]
CWE ID: CWE-264
|
on_response(void *data, krb5_error_code retval, otp_response response)
{
struct request_state rs = *(struct request_state *)data;
free(data);
if (retval == 0 && response != otp_response_success)
retval = KRB5_PREAUTH_FAILED;
if (retval == 0)
rs.enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
rs.respond(rs.arg, retval, NULL, NULL, NULL);
}
| 166,676
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c )
return cJSON_DetachItemFromArray( object, i );
return 0;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string )
| 167,285
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Commit Message: Fixed bug where PlzNavigate CSP in a iframe did not get the inherited CSP
When inheriting the CSP from a parent document to a local-scheme CSP,
it does not always get propagated to the PlzNavigate CSP. This means
that PlzNavigate CSP checks (like `frame-src`) would be ran against
a blank policy instead of the proper inherited policy.
Bug: 778658
Change-Id: I61bb0d432e1cea52f199e855624cb7b3078f56a9
Reviewed-on: https://chromium-review.googlesource.com/765969
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#518245}
CWE ID: CWE-732
|
void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
GetContentSecurityPolicy()->BindToExecutionContext(this);
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
| 172,683
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread())
blobRegistry().registerBlobURL(url, srcURL);
else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry())
registry->registerBlobURL(url, srcURL);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
| 170,685
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: init_ext2_xattr(void)
{
ext2_xattr_cache = mb_cache_create("ext2_xattr", 6);
if (!ext2_xattr_cache)
return -ENOMEM;
return 0;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the 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 the buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
init_ext2_xattr(void)
#define HASH_BUCKET_BITS 10
struct mb2_cache *ext2_xattr_create_cache(void)
{
return mb2_cache_create(HASH_BUCKET_BITS);
}
| 169,985
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info,
size_t* gc_info_index_slot) {
DCHECK(gc_info);
DCHECK(gc_info_index_slot);
DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ());
MutexLocker locker(mutex);
if (*gc_info_index_slot)
return;
int index = ++gc_info_index_;
size_t gc_info_index = static_cast<size_t>(index);
CHECK(gc_info_index < GCInfoTable::kMaxIndex);
if (gc_info_index >= gc_info_table_size_)
Resize();
g_gc_info_table[gc_info_index] = gc_info;
ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index);
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <mlippautz@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362
|
void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info,
size_t* gc_info_index_slot) {
DCHECK(gc_info);
DCHECK(gc_info_index_slot);
// Ensuring a new index involves current index adjustment as well
// as potentially resizing the table, both operations that require
// a lock.
MutexLocker locker(table_mutex_);
if (*gc_info_index_slot)
return;
int index = ++current_index_;
size_t gc_info_index = static_cast<size_t>(index);
CHECK(gc_info_index < GCInfoTable::kMaxIndex);
if (current_index_ >= limit_)
Resize();
table_[gc_info_index] = gc_info;
ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index);
}
| 173,134
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) {
current_content_source_id_ = next_source_id;
did_receive_first_frame_after_navigation_ = false;
if (enable_surface_synchronization_) {
visual_properties_ack_pending_ = false;
viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId();
if (view_)
view_->DidNavigate();
viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId();
if (old_surface_id == new_surface_id)
return;
} else {
if (last_received_content_source_id_ >= current_content_source_id_)
return;
}
if (!new_content_rendering_timeout_)
return;
new_content_rendering_timeout_->Start(new_content_rendering_delay_);
}
Commit Message: Start rendering timer after first navigation
Currently the new content rendering timer in the browser process,
which clears an old page's contents 4 seconds after a navigation if the
new page doesn't draw in that time, is not set on the first navigation
for a top-level frame.
This is problematic because content can exist before the first
navigation, for instance if it was created by a javascript: URL.
This CL removes the code that skips the timer activation on the first
navigation.
Bug: 844881
Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584
Reviewed-on: https://chromium-review.googlesource.com/1188589
Reviewed-by: Fady Samuel <fsamuel@chromium.org>
Reviewed-by: ccameron <ccameron@chromium.org>
Commit-Queue: Ken Buchanan <kenrb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#586913}
CWE ID: CWE-20
|
void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) {
current_content_source_id_ = next_source_id;
did_receive_first_frame_after_navigation_ = false;
if (enable_surface_synchronization_) {
visual_properties_ack_pending_ = false;
if (view_)
view_->DidNavigate();
} else {
if (last_received_content_source_id_ >= current_content_source_id_)
return;
}
if (!new_content_rendering_timeout_)
return;
new_content_rendering_timeout_->Start(new_content_rendering_delay_);
}
| 172,654
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static const char *parse_scheme(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr;
do {
switch (*state->ptr) {
case ':':
/* scheme delimiter */
state->url.scheme = &state->buffer[0];
state->buffer[state->offset++] = 0;
return ++state->ptr;
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case '+': case '-': case '.':
if (state->ptr == tmp) {
return tmp;
}
/* no break */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
/* scheme part */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) {
/* soft fail; parse path next */
return tmp;
}
state->ptr += mb - 1;
}
} while (++state->ptr != state->end);
return state->ptr = tmp;
}
Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions)
The parser's offset was not reset when we softfail in scheme
parsing and continue to parse a path.
Thanks to hlt99 at blinkenshell dot org for the report.
CWE ID: CWE-119
|
static const char *parse_scheme(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr;
do {
switch (*state->ptr) {
case ':':
/* scheme delimiter */
state->url.scheme = &state->buffer[0];
state->buffer[state->offset++] = 0;
return ++state->ptr;
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case '+': case '-': case '.':
if (state->ptr == tmp) {
goto softfail;
}
/* no break */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
/* scheme part */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) {
goto softfail;
}
state->ptr += mb - 1;
}
} while (++state->ptr != state->end);
softfail:
state->offset = 0;
return state->ptr = tmp;
}
| 168,833
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int hci_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr;
struct sock *sk = sock->sk;
struct hci_dev *hdev = hci_pi(sk)->hdev;
BT_DBG("sock %p sk %p", sock, sk);
if (!hdev)
return -EBADFD;
lock_sock(sk);
*addr_len = sizeof(*haddr);
haddr->hci_family = AF_BLUETOOTH;
haddr->hci_dev = hdev->id;
release_sock(sk);
return 0;
}
Commit Message: Bluetooth: HCI - Fix info leak via getsockname()
The HCI code fails to initialize the hci_channel member of struct
sockaddr_hci and that for leaks two bytes kernel stack via the
getsockname() syscall. Initialize hci_channel with 0 to avoid the
info leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Marcel Holtmann <marcel@holtmann.org>
Cc: Gustavo Padovan <gustavo@padovan.org>
Cc: Johan Hedberg <johan.hedberg@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static int hci_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr;
struct sock *sk = sock->sk;
struct hci_dev *hdev = hci_pi(sk)->hdev;
BT_DBG("sock %p sk %p", sock, sk);
if (!hdev)
return -EBADFD;
lock_sock(sk);
*addr_len = sizeof(*haddr);
haddr->hci_family = AF_BLUETOOTH;
haddr->hci_dev = hdev->id;
haddr->hci_channel= 0;
release_sock(sk);
return 0;
}
| 169,900
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void inbound_data_waiting(void *context) {
eager_reader_t *reader = (eager_reader_t *)context;
data_buffer_t *buffer = (data_buffer_t *)reader->allocator->alloc(reader->buffer_size + sizeof(data_buffer_t));
if (!buffer) {
LOG_ERROR("%s couldn't aquire memory for inbound data buffer.", __func__);
return;
}
buffer->length = 0;
buffer->offset = 0;
int bytes_read = read(reader->inbound_fd, buffer->data, reader->buffer_size);
if (bytes_read > 0) {
buffer->length = bytes_read;
fixed_queue_enqueue(reader->buffers, buffer);
eventfd_write(reader->bytes_available_fd, bytes_read);
} else {
if (bytes_read == 0)
LOG_WARN("%s fd said bytes existed, but none were found.", __func__);
else
LOG_WARN("%s unable to read from file descriptor: %s", __func__, strerror(errno));
reader->allocator->free(buffer);
}
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static void inbound_data_waiting(void *context) {
eager_reader_t *reader = (eager_reader_t *)context;
data_buffer_t *buffer = (data_buffer_t *)reader->allocator->alloc(reader->buffer_size + sizeof(data_buffer_t));
if (!buffer) {
LOG_ERROR("%s couldn't aquire memory for inbound data buffer.", __func__);
return;
}
buffer->length = 0;
buffer->offset = 0;
int bytes_read = TEMP_FAILURE_RETRY(read(reader->inbound_fd, buffer->data, reader->buffer_size));
if (bytes_read > 0) {
buffer->length = bytes_read;
fixed_queue_enqueue(reader->buffers, buffer);
eventfd_write(reader->bytes_available_fd, bytes_read);
} else {
if (bytes_read == 0)
LOG_WARN("%s fd said bytes existed, but none were found.", __func__);
else
LOG_WARN("%s unable to read from file descriptor: %s", __func__, strerror(errno));
reader->allocator->free(buffer);
}
}
| 173,481
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin(
Profile* profile,
const url::Origin& origin) {
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
EXPECT_TRUE(data_store);
std::unique_ptr<SiteCharacteristicsDataReader> reader =
data_store->GetReaderForOrigin(origin);
internal::LocalSiteCharacteristicsDataImpl* impl =
static_cast<LocalSiteCharacteristicsDataReader*>(reader.get())
->impl_for_testing()
.get();
while (!impl->site_characteristics_for_testing().IsInitialized())
base::RunLoop().RunUntilIdle();
return reader;
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin(
Profile* profile,
const url::Origin& origin) {
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
EXPECT_TRUE(data_store);
std::unique_ptr<SiteCharacteristicsDataReader> reader =
data_store->GetReaderForOrigin(origin);
const internal::LocalSiteCharacteristicsDataImpl* impl =
static_cast<LocalSiteCharacteristicsDataReader*>(reader.get())
->impl_for_testing();
while (!impl->site_characteristics_for_testing().IsInitialized())
base::RunLoop().RunUntilIdle();
return reader;
}
| 172,215
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)
{
struct snd_ctl_elem_id id;
unsigned int idx;
int err = -EINVAL;
if (! kcontrol)
return err;
if (snd_BUG_ON(!card || !kcontrol->info))
goto error;
id = kcontrol->id;
down_write(&card->controls_rwsem);
if (snd_ctl_find_id(card, &id)) {
up_write(&card->controls_rwsem);
dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n",
id.iface,
id.device,
id.subdevice,
id.name,
id.index);
err = -EBUSY;
goto error;
}
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
err = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return err;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Acked-by: Jaroslav Kysela <perex@perex.cz>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID:
|
int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)
{
struct snd_ctl_elem_id id;
unsigned int idx;
unsigned int count;
int err = -EINVAL;
if (! kcontrol)
return err;
if (snd_BUG_ON(!card || !kcontrol->info))
goto error;
id = kcontrol->id;
down_write(&card->controls_rwsem);
if (snd_ctl_find_id(card, &id)) {
up_write(&card->controls_rwsem);
dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n",
id.iface,
id.device,
id.subdevice,
id.name,
id.index);
err = -EBUSY;
goto error;
}
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
err = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
count = kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return err;
}
| 166,292
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
int i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, size_t offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
size_t i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
| 165,485
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RequestSender::OnNetworkFetcherComplete(
const GURL& original_url,
std::unique_ptr<std::string> response_body,
int net_error,
const std::string& header_etag,
int64_t xheader_retry_after_sec) {
DCHECK(thread_checker_.CalledOnValidThread());
VLOG(1) << "request completed from url: " << original_url.spec();
int error = -1;
if (response_body && response_code_ == 200) {
DCHECK_EQ(0, net_error);
error = 0;
} else if (response_code_ != -1) {
error = response_code_;
} else {
error = net_error;
}
int retry_after_sec = -1;
if (original_url.SchemeIsCryptographic() && error > 0)
retry_after_sec = base::saturated_cast<int>(xheader_retry_after_sec);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&RequestSender::SendInternalComplete,
base::Unretained(this), error,
response_body ? *response_body : std::string(),
header_etag, retry_after_sec));
}
Commit Message: Fix error handling in the request sender and url fetcher downloader.
That means handling the network errors by primarily looking at net_error.
Bug: 1028369
Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Commit-Queue: Sorin Jianu <sorin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#719199}
CWE ID: CWE-20
|
void RequestSender::OnNetworkFetcherComplete(
const GURL& original_url,
std::unique_ptr<std::string> response_body,
int net_error,
const std::string& header_etag,
int64_t xheader_retry_after_sec) {
DCHECK(thread_checker_.CalledOnValidThread());
VLOG(1) << "request completed from url: " << original_url.spec();
int error = -1;
if (!net_error && response_code_ == 200)
error = 0;
else if (response_code_ != -1)
error = response_code_;
else
error = net_error;
int retry_after_sec = -1;
if (original_url.SchemeIsCryptographic() && error > 0)
retry_after_sec = base::saturated_cast<int>(xheader_retry_after_sec);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&RequestSender::SendInternalComplete,
base::Unretained(this), error,
response_body ? *response_body : std::string(),
header_etag, retry_after_sec));
}
| 172,364
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob)
{
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num));
asn1_write(data, blob->data, blob->length);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob)
{
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num))) return false;
if (!asn1_write(data, blob->data, blob->length)) return false;
return asn1_pop_tag(data);
}
| 164,587
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(L,buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
Commit Message: Security: more cmsgpack fixes by @soloestoy.
@soloestoy sent me this additional fixes, after searching for similar
problems to the one reported in mp_pack(). I'm committing the changes
because it was not possible during to make a public PR to protect Redis
users and give Redis providers some time to patch their systems.
CWE ID: CWE-119
|
void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
luaL_checkstack(L, 3, "in function mp_encode_lua_table_as_map");
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(L,buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
| 169,240
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
VpxVideoWriter *writer) {
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0,
VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
static void encode_frame(vpx_codec_ctx_t *codec,
static int encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
VpxVideoWriter *writer) {
int got_pkts = 0;
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0,
VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
got_pkts = 1;
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
return got_pkts;
}
| 174,481
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
FALSE,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
}
| 170,142
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
| 170,267
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 0;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 0;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
|
_exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 1;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 1;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
| 173,290
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void numtostr(js_State *J, const char *fmt, int w, double n)
{
char buf[32], *e;
sprintf(buf, fmt, w, n);
e = strchr(buf, 'e');
if (e) {
int exp = atoi(e+1);
sprintf(e, "e%+d", exp);
}
js_pushstring(J, buf);
}
Commit Message: Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().
32 is not enough to fit sprintf("%.20f", 1e20).
We need at least 43 bytes to fit that format.
Bump the static buffer size.
CWE ID: CWE-119
|
static void numtostr(js_State *J, const char *fmt, int w, double n)
{
/* buf needs to fit printf("%.20f", 1e20) */
char buf[50], *e;
sprintf(buf, fmt, w, n);
e = strchr(buf, 'e');
if (e) {
int exp = atoi(e+1);
sprintf(e, "e%+d", exp);
}
js_pushstring(J, buf);
}
| 169,704
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
| 173,423
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void LauncherView::UpdateFirstButtonPadding() {
if (view_model_->view_size() > 0) {
view_model_->view_at(0)->set_border(views::Border::CreateEmptyBorder(
primary_axis_coordinate(0, kLeadingInset),
primary_axis_coordinate(kLeadingInset, 0),
0,
0));
}
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void LauncherView::UpdateFirstButtonPadding() {
if (view_model_->view_size() > 0) {
view_model_->view_at(0)->set_border(views::Border::CreateEmptyBorder(
primary_axis_coordinate(0, leading_inset()),
primary_axis_coordinate(leading_inset(), 0),
0,
0));
}
}
| 170,897
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: parse_range(char *str, size_t file_sz, int *nranges)
{
static struct range ranges[MAX_RANGES];
int i = 0;
char *p, *q;
/* Extract range unit */
if ((p = strchr(str, '=')) == NULL)
return (NULL);
*p++ = '\0';
/* Check if it's a bytes range spec */
if (strcmp(str, "bytes") != 0)
return (NULL);
while ((q = strchr(p, ',')) != NULL) {
*q++ = '\0';
/* Extract start and end positions */
if (parse_range_spec(p, file_sz, &ranges[i]) == 0)
continue;
i++;
if (i == MAX_RANGES)
return (NULL);
p = q;
}
if (parse_range_spec(p, file_sz, &ranges[i]) != 0)
i++;
*nranges = i;
return (i ? ranges : NULL);
}
Commit Message: Reimplement httpd's support for byte ranges.
The previous implementation loaded all the output into a single output
buffer and used its size to determine the Content-Length of the body.
The new implementation calculates the body length first and writes the
individual ranges in an async way using the bufferevent mechanism.
This prevents httpd from using too much memory and applies the
watermark and throttling mechanisms to range requests.
Problem reported by Pierre Kim (pierre.kim.sec at gmail.com)
OK benno@ sunil@
CWE ID: CWE-770
|
parse_range(char *str, size_t file_sz, int *nranges)
int
parse_ranges(struct client *clt, char *str, size_t file_sz)
{
int i = 0;
char *p, *q;
struct range_data *r = &clt->clt_ranges;
memset(r, 0, sizeof(*r));
/* Extract range unit */
if ((p = strchr(str, '=')) == NULL)
return (-1);
*p++ = '\0';
/* Check if it's a bytes range spec */
if (strcmp(str, "bytes") != 0)
return (-1);
while ((q = strchr(p, ',')) != NULL) {
*q++ = '\0';
/* Extract start and end positions */
if (parse_range_spec(p, file_sz, &r->range[i]) == 0)
continue;
i++;
if (i == SERVER_MAX_RANGES)
return (-1);
p = q;
}
if (parse_range_spec(p, file_sz, &r->range[i]) != 0)
i++;
r->range_total = file_sz;
r->range_count = i;
return (i);
}
| 168,376
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void send_auth(char *username, char *password) {
struct mt_packet data;
unsigned short width = 0;
unsigned short height = 0;
char *terminal = getenv("TERM");
char md5data[100];
unsigned char md5sum[17];
int plen;
md5_state_t state;
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(md5data, sizeof(md5data));
mlock(md5sum, sizeof(md5data));
#endif
/* Concat string of 0 + password + pass_salt */
md5data[0] = 0;
strncpy(md5data + 1, password, 82);
md5data[83] = '\0';
memcpy(md5data + 1 + strlen(password), pass_salt, 16);
/* Generate md5 sum of md5data with a leading 0 */
md5_init(&state);
md5_append(&state, (const md5_byte_t *)md5data, strlen(password) + 17);
md5_finish(&state, (md5_byte_t *)md5sum + 1);
md5sum[0] = 0;
/* Send combined packet to server */
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17);
plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username));
plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal));
if (is_a_tty && get_terminal_size(&width, &height) != -1) {
width = htole16(width);
height = htole16(height);
plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
}
outcounter += plen;
/* TODO: handle result */
send_udp(&data, 1);
}
Commit Message: Merge pull request #20 from eyalitki/master
2nd round security fixes from eyalitki
CWE ID: CWE-119
|
static void send_auth(char *username, char *password) {
struct mt_packet data;
unsigned short width = 0;
unsigned short height = 0;
char *terminal = getenv("TERM");
char md5data[100];
unsigned char md5sum[17];
int plen, act_pass_len;
md5_state_t state;
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(md5data, sizeof(md5data));
mlock(md5sum, sizeof(md5data));
#endif
/* calculate the actual password's length */
act_pass_len = strnlen(password, 82);
/* Concat string of 0 + password + pass_salt */
md5data[0] = 0;
memcpy(md5data + 1, password, act_pass_len);
/* in case that password is long, calculate only using the used-up parts */
memcpy(md5data + 1 + act_pass_len, pass_salt, 16);
/* Generate md5 sum of md5data with a leading 0 */
md5_init(&state);
md5_append(&state, (const md5_byte_t *)md5data, 1 + act_pass_len + 16);
md5_finish(&state, (md5_byte_t *)md5sum + 1);
md5sum[0] = 0;
/* Send combined packet to server */
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17);
plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username));
plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal));
if (is_a_tty && get_terminal_size(&width, &height) != -1) {
width = htole16(width);
height = htole16(height);
plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
}
outcounter += plen;
/* TODO: handle result */
send_udp(&data, 1);
}
| 166,963
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta,
gfx::Vector2dF overscroll_velocity) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(),
overscroll_delta.y(), overscroll_velocity.x(),
overscroll_velocity.y());
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta,
void AwContents::DidOverscroll(const gfx::Vector2d& overscroll_delta,
const gfx::Vector2dF& overscroll_velocity) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(),
overscroll_delta.y(), overscroll_velocity.x(),
overscroll_velocity.y());
}
| 171,616
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int bmpr_read_rle(struct iwbmprcontext *rctx)
{
int retval = 0;
if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) &&
!(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4))
{
iw_set_error(rctx->ctx,"Compression type incompatible with image type");
}
if(rctx->topdown) {
iw_set_error(rctx->ctx,"Compression not allowed with top-down images");
}
rctx->img->imgtype = IW_IMGTYPE_RGBA;
rctx->img->bit_depth = 8;
rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32);
rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height);
if(!rctx->img->pixels) goto done;
if(!bmpr_read_rle_internal(rctx)) goto done;
if(!bmpr_has_transparency(rctx->img)) {
bmpr_strip_alpha(rctx->img);
}
retval = 1;
done:
return retval;
}
Commit Message: Fixed a bug that could cause invalid memory to be accessed
The bug could happen when transparency is removed from an image.
Also fixed a semi-related BMP error handling logic bug.
Fixes issue #21
CWE ID: CWE-787
|
static int bmpr_read_rle(struct iwbmprcontext *rctx)
{
int retval = 0;
if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) &&
!(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4))
{
iw_set_error(rctx->ctx,"Compression type incompatible with image type");
goto done;
}
if(rctx->topdown) {
iw_set_error(rctx->ctx,"Compression not allowed with top-down images");
goto done;
}
rctx->img->imgtype = IW_IMGTYPE_RGBA;
rctx->img->bit_depth = 8;
rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32);
rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height);
if(!rctx->img->pixels) goto done;
if(!bmpr_read_rle_internal(rctx)) goto done;
if(!bmpr_has_transparency(rctx->img)) {
bmpr_strip_alpha(rctx->img);
}
retval = 1;
done:
return retval;
}
| 168,117
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
mWriteBuffer = buffer;
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
|
FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
memmove(mWriteBuffer, buffer, sizeof(const FLAC__int32 * const) * getChannels());
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
| 174,026
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
UINT16 data_size, UINT8 *p_data, UINT16 evt)
{
UINT8 app_idx, mcl_idx, mdl_idx;
btif_hl_mdl_cb_t *p_dcb;
tBTA_HL_STATUS status = BTA_HL_STATUS_FAIL;
int r;
BTIF_TRACE_DEBUG("%s app_id=%d mdl_handle=0x%x data_size=%d",
__FUNCTION__,app_id, mdl_handle, data_size);
if (btif_hl_find_mdl_idx_using_handle(mdl_handle, &app_idx, &mcl_idx, &mdl_idx))
{
p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx);
if ((p_dcb->p_rx_pkt = (UINT8 *)btif_hl_get_buf(data_size)) != NULL)
{
memcpy(p_dcb->p_rx_pkt, p_data, data_size);
if (p_dcb->p_scb)
{
BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=0x%x mdl_idx=0x%x data_size=%d",
app_idx, mcl_idx, mdl_idx, data_size);
r = send(p_dcb->p_scb->socket_id[1], p_dcb->p_rx_pkt, data_size, 0);
if (r == data_size)
{
BTIF_TRACE_DEBUG("socket send success data_size=%d", data_size);
status = BTA_HL_STATUS_OK;
}
else
{
BTIF_TRACE_ERROR("socket send failed r=%d data_size=%d",r, data_size);
}
}
btif_hl_free_buf((void **) &p_dcb->p_rx_pkt);
}
}
bta_hl_ci_put_rx_data(mdl_handle, status, evt);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
UINT16 data_size, UINT8 *p_data, UINT16 evt)
{
UINT8 app_idx, mcl_idx, mdl_idx;
btif_hl_mdl_cb_t *p_dcb;
tBTA_HL_STATUS status = BTA_HL_STATUS_FAIL;
int r;
BTIF_TRACE_DEBUG("%s app_id=%d mdl_handle=0x%x data_size=%d",
__FUNCTION__,app_id, mdl_handle, data_size);
if (btif_hl_find_mdl_idx_using_handle(mdl_handle, &app_idx, &mcl_idx, &mdl_idx))
{
p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx);
if ((p_dcb->p_rx_pkt = (UINT8 *)btif_hl_get_buf(data_size)) != NULL)
{
memcpy(p_dcb->p_rx_pkt, p_data, data_size);
if (p_dcb->p_scb)
{
BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=0x%x mdl_idx=0x%x data_size=%d",
app_idx, mcl_idx, mdl_idx, data_size);
r = TEMP_FAILURE_RETRY(send(p_dcb->p_scb->socket_id[1], p_dcb->p_rx_pkt, data_size, 0));
if (r == data_size)
{
BTIF_TRACE_DEBUG("socket send success data_size=%d", data_size);
status = BTA_HL_STATUS_OK;
}
else
{
BTIF_TRACE_ERROR("socket send failed r=%d data_size=%d",r, data_size);
}
}
btif_hl_free_buf((void **) &p_dcb->p_rx_pkt);
}
}
bta_hl_ci_put_rx_data(mdl_handle, status, evt);
}
| 173,434
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ChromeRenderProcessObserver::OnControlMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess,
OnSetIsIncognitoProcess)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup)
#if defined(USE_TCMALLOC)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetTcmallocHeapProfiling,
OnSetTcmallocHeapProfiling)
IPC_MESSAGE_HANDLER(ChromeViewMsg_WriteTcmallocHeapProfile,
OnWriteTcmallocHeapProfile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules,
OnSetContentSettingRules)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer,
OnToggleWebKitSharedTimer)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
TBR=darin@chromium.org
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool ChromeRenderProcessObserver::OnControlMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess,
OnSetIsIncognitoProcess)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules,
OnSetContentSettingRules)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer,
OnToggleWebKitSharedTimer)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
| 170,665
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GpuCommandBufferStub::OnCreateVideoDecoder(
media::VideoCodecProfile profile,
IPC::Message* reply_message) {
int decoder_route_id = channel_->GenerateRouteID();
GpuCommandBufferMsg_CreateVideoDecoder::WriteReplyParams(
reply_message, decoder_route_id);
GpuVideoDecodeAccelerator* decoder =
new GpuVideoDecodeAccelerator(this, decoder_route_id, this);
video_decoders_.AddWithID(decoder, decoder_route_id);
channel_->AddRoute(decoder_route_id, decoder);
decoder->Initialize(profile, reply_message,
channel_->renderer_process());
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void GpuCommandBufferStub::OnCreateVideoDecoder(
media::VideoCodecProfile profile,
IPC::Message* reply_message) {
int decoder_route_id = channel_->GenerateRouteID();
GpuCommandBufferMsg_CreateVideoDecoder::WriteReplyParams(
reply_message, decoder_route_id);
GpuVideoDecodeAccelerator* decoder =
new GpuVideoDecodeAccelerator(this, decoder_route_id, this);
video_decoders_.AddWithID(decoder, decoder_route_id);
channel_->AddRoute(decoder_route_id, decoder);
decoder->Initialize(profile, reply_message);
}
| 170,936
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 60 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 &&
rdesc[41] == 0x00 && rdesc[59] == 0x26 &&
rdesc[60] == 0xf9 && rdesc[61] == 0x00) {
hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n");
rdesc[60] = 0xfa;
rdesc[40] = 0xfa;
}
return rdesc;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: stable@vger.kernel.org
Reported-by: Ben Hawkes <hawkes@google.com>
Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 62 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 &&
rdesc[41] == 0x00 && rdesc[59] == 0x26 &&
rdesc[60] == 0xf9 && rdesc[61] == 0x00) {
hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n");
rdesc[60] = 0xfa;
rdesc[40] = 0xfa;
}
return rdesc;
}
| 166,374
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ServiceWorkerDevToolsAgentHost::WorkerDestroyed() {
DCHECK_NE(WORKER_TERMINATED, state_);
state_ = WORKER_TERMINATED;
agent_ptr_.reset();
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetCrashed();
for (DevToolsSession* session : sessions())
session->SetRenderer(nullptr, nullptr);
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void ServiceWorkerDevToolsAgentHost::WorkerDestroyed() {
DCHECK_NE(WORKER_TERMINATED, state_);
state_ = WORKER_TERMINATED;
agent_ptr_.reset();
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetCrashed();
for (DevToolsSession* session : sessions())
session->SetRenderer(-1, nullptr);
}
| 172,784
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
{
ssize_t ret;
uint8_t *buffer = g_malloc(MIN(65536, size));
while (size > 0) {
size_t count = MIN(65536, size);
ret = nbd_negotiate_read(ioc, buffer, count);
if (ret < 0) {
g_free(buffer);
return ret;
}
size -= count;
}
g_free(buffer);
return 0;
}
Commit Message:
CWE ID: CWE-20
|
static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
| 165,453
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: TracingControllerImpl::TracingControllerImpl()
: delegate_(GetContentClient()->browser()->GetTracingDelegate()),
weak_ptr_factory_(this) {
DCHECK(!g_tracing_controller);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::FileTracing::SetProvider(new FileTracingProviderImpl);
AddAgents();
base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver(
weak_ptr_factory_.GetWeakPtr());
g_tracing_controller = this;
}
Commit Message: Tracing: Connect to service on startup
Temporary workaround for flaky tests introduced by
https://chromium-review.googlesource.com/c/chromium/src/+/1439082
TBR=eseckler@chromium.org
Bug: 928410, 928363
Change-Id: I0dcf20cbdf91a7beea167a220ba9ef7e0604c1ab
Reviewed-on: https://chromium-review.googlesource.com/c/1452767
Reviewed-by: oysteine <oysteine@chromium.org>
Reviewed-by: Eric Seckler <eseckler@chromium.org>
Reviewed-by: Aaron Gable <agable@chromium.org>
Commit-Queue: oysteine <oysteine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#631052}
CWE ID: CWE-19
|
TracingControllerImpl::TracingControllerImpl()
: delegate_(GetContentClient()->browser()->GetTracingDelegate()),
weak_ptr_factory_(this) {
DCHECK(!g_tracing_controller);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::FileTracing::SetProvider(new FileTracingProviderImpl);
AddAgents();
base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver(
weak_ptr_factory_.GetWeakPtr());
g_tracing_controller = this;
// TODO(oysteine): Instead of connecting right away, we should connect
// in StartTracing once this no longer causes test flakiness.
ConnectToServiceIfNeeded();
}
| 172,057
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::RequestAuthorization(
const dbus::ObjectPath& device_path,
const ConfirmationCallback& callback) {
callback.Run(CANCELLED);
}
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::RequestAuthorization(
| 171,234
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void InspectorClientImpl::clearBrowserCache()
{
if (WebDevToolsAgentImpl* agent = devToolsAgent())
agent->clearBrowserCache();
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
void InspectorClientImpl::clearBrowserCache()
| 171,346
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection(
const IPC::Message& msg, int listen_socket_id,
net::IPEndPoint remote_address, int connected_socket_id) {
P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id);
if (!socket) {
LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection "
"for invalid socket_id.";
return;
}
P2PSocketHost* accepted_connection =
socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id);
if (accepted_connection) {
sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>(
ExtendedSocketId(msg.routing_id(), connected_socket_id),
accepted_connection));
}
}
Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE)
CIDs 16230, 16439, 16610, 16635
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/7215029
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection(
const IPC::Message& msg, int listen_socket_id,
const net::IPEndPoint& remote_address, int connected_socket_id) {
P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id);
if (!socket) {
LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection "
"for invalid socket_id.";
return;
}
P2PSocketHost* accepted_connection =
socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id);
if (accepted_connection) {
sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>(
ExtendedSocketId(msg.routing_id(), connected_socket_id),
accepted_connection));
}
}
| 170,312
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void ext4_invalidatepage(struct page *page, unsigned long offset)
{
journal_t *journal = EXT4_JOURNAL(page->mapping->host);
/*
* If it's a full truncate we just forget about the pending dirtying
*/
if (offset == 0)
ClearPageChecked(page);
if (journal)
jbd2_journal_invalidatepage(journal, page, offset);
else
block_invalidatepage(page, offset);
}
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 <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static void ext4_invalidatepage(struct page *page, unsigned long offset)
{
journal_t *journal = EXT4_JOURNAL(page->mapping->host);
/*
* free any io_end structure allocated for buffers to be discarded
*/
if (ext4_should_dioread_nolock(page->mapping->host))
ext4_invalidatepage_free_endio(page, offset);
/*
* If it's a full truncate we just forget about the pending dirtying
*/
if (offset == 0)
ClearPageChecked(page);
if (journal)
jbd2_journal_invalidatepage(journal, page, offset);
else
block_invalidatepage(page, offset);
}
| 167,547
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid,
afs_int32 *aid, afs_int32 *cid)
{
afs_int32 code;
struct ubik_trans *tt;
int admin;
char cname[PR_MAXNAMELEN];
stolower(aname);
code = Initdb();
if (code)
return code;
code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt);
if (code)
return code;
code = ubik_SetLock(tt, 1, 1, LOCKWRITE);
if (code)
ABORT_WITH(tt, code);
code = read_DbHeader(tt);
if (code)
ABORT_WITH(tt, code);
/* this is for cross-cell self registration. It is not added in the
* SPR_INewEntry because we want self-registration to only do
* automatic id assignment.
*/
code = WhoIsThisWithName(call, tt, cid, cname);
if (code != 2) { /* 2 specifies that this is a foreign cell request */
if (code)
ABORT_WITH(tt, PRPERM);
admin = IsAMemberOf(tt, *cid, SYSADMINID);
} else {
admin = ((!restricted && !strcmp(aname, cname))) || IsAMemberOf(tt, *cid, SYSADMINID);
oid = *cid = SYSADMINID;
}
if (!CreateOK(tt, *cid, oid, flag, admin))
ABORT_WITH(tt, PRPERM);
if (code)
return code;
return PRSUCCESS;
}
Commit Message:
CWE ID: CWE-284
|
newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid,
afs_int32 *aid, afs_int32 *cid)
{
afs_int32 code;
struct ubik_trans *tt;
int admin;
char cname[PR_MAXNAMELEN];
stolower(aname);
code = Initdb();
if (code)
return code;
code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt);
if (code)
return code;
code = ubik_SetLock(tt, 1, 1, LOCKWRITE);
if (code)
ABORT_WITH(tt, code);
code = read_DbHeader(tt);
if (code)
ABORT_WITH(tt, code);
/* this is for cross-cell self registration. It is not added in the
* SPR_INewEntry because we want self-registration to only do
* automatic id assignment.
*/
code = WhoIsThisWithName(call, tt, cid, cname);
if (code && code != 2)
ABORT_WITH(tt, PRPERM);
admin = IsAMemberOf(tt, *cid, SYSADMINID);
if (code == 2 /* foreign cell request */) {
if (!restricted && (strcmp(aname, cname) == 0)) {
/* can't autoregister while providing an owner id */
if (oid != 0)
ABORT_WITH(tt, PRPERM);
admin = 1;
oid = SYSADMINID;
*cid = SYSADMINID;
}
}
if (!CreateOK(tt, *cid, oid, flag, admin))
ABORT_WITH(tt, PRPERM);
if (code)
return code;
return PRSUCCESS;
}
| 165,179
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
if (err != OK) {
mMetaDataSize = -1ll;
mContentType = "";
mSniffedMIME = "";
{
sp<DataSource> dataSource = mDataSource;
sp<NuCachedSource2> cachedSource = mCachedSource;
sp<DataSource> httpSource = mHttpSource;
{
Mutex::Autolock _l(mDisconnectLock);
mDataSource.clear();
mCachedSource.clear();
mHttpSource.clear();
}
}
cancelPollBuffering();
}
notifyPrepared(err);
}
Commit Message: GenericSource: reset mDrmManagerClient when mDataSource is cleared.
Bug: 25070434
Change-Id: Iade3472c496ac42456e42db35e402f7b66416f5b
(cherry picked from commit b41fd0d4929f0a89811bafcc4fd944b128f00ce2)
CWE ID: CWE-119
|
void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
if (err != OK) {
mMetaDataSize = -1ll;
mContentType = "";
mSniffedMIME = "";
{
sp<DataSource> dataSource = mDataSource;
sp<NuCachedSource2> cachedSource = mCachedSource;
sp<DataSource> httpSource = mHttpSource;
{
Mutex::Autolock _l(mDisconnectLock);
mDataSource.clear();
mDrmManagerClient = NULL;
mCachedSource.clear();
mHttpSource.clear();
}
}
cancelPollBuffering();
}
notifyPrepared(err);
}
| 173,969
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ~CreateFileResult()
{
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
~CreateFileResult()
| 171,416
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int rock_continue(struct rock_state *rs)
{
int ret = 1;
int blocksize = 1 << rs->inode->i_blkbits;
const int min_de_size = offsetof(struct rock_ridge, u);
kfree(rs->buffer);
rs->buffer = NULL;
if ((unsigned)rs->cont_offset > blocksize - min_de_size ||
(unsigned)rs->cont_size > blocksize ||
(unsigned)(rs->cont_offset + rs->cont_size) > blocksize) {
printk(KERN_NOTICE "rock: corrupted directory entry. "
"extent=%d, offset=%d, size=%d\n",
rs->cont_extent, rs->cont_offset, rs->cont_size);
ret = -EIO;
goto out;
}
if (rs->cont_extent) {
struct buffer_head *bh;
rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL);
if (!rs->buffer) {
ret = -ENOMEM;
goto out;
}
ret = -EIO;
bh = sb_bread(rs->inode->i_sb, rs->cont_extent);
if (bh) {
memcpy(rs->buffer, bh->b_data + rs->cont_offset,
rs->cont_size);
put_bh(bh);
rs->chr = rs->buffer;
rs->len = rs->cont_size;
rs->cont_extent = 0;
rs->cont_size = 0;
rs->cont_offset = 0;
return 0;
}
printk("Unable to read rock-ridge attributes\n");
}
out:
kfree(rs->buffer);
rs->buffer = NULL;
return ret;
}
Commit Message: isofs: Fix infinite looping over CE entries
Rock Ridge extensions define so called Continuation Entries (CE) which
define where is further space with Rock Ridge data. Corrupted isofs
image can contain arbitrarily long chain of these, including a one
containing loop and thus causing kernel to end in an infinite loop when
traversing these entries.
Limit the traversal to 32 entries which should be more than enough space
to store all the Rock Ridge data.
Reported-by: P J P <ppandit@redhat.com>
CC: stable@vger.kernel.org
Signed-off-by: Jan Kara <jack@suse.cz>
CWE ID: CWE-399
|
static int rock_continue(struct rock_state *rs)
{
int ret = 1;
int blocksize = 1 << rs->inode->i_blkbits;
const int min_de_size = offsetof(struct rock_ridge, u);
kfree(rs->buffer);
rs->buffer = NULL;
if ((unsigned)rs->cont_offset > blocksize - min_de_size ||
(unsigned)rs->cont_size > blocksize ||
(unsigned)(rs->cont_offset + rs->cont_size) > blocksize) {
printk(KERN_NOTICE "rock: corrupted directory entry. "
"extent=%d, offset=%d, size=%d\n",
rs->cont_extent, rs->cont_offset, rs->cont_size);
ret = -EIO;
goto out;
}
if (rs->cont_extent) {
struct buffer_head *bh;
rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL);
if (!rs->buffer) {
ret = -ENOMEM;
goto out;
}
ret = -EIO;
if (++rs->cont_loops >= RR_MAX_CE_ENTRIES)
goto out;
bh = sb_bread(rs->inode->i_sb, rs->cont_extent);
if (bh) {
memcpy(rs->buffer, bh->b_data + rs->cont_offset,
rs->cont_size);
put_bh(bh);
rs->chr = rs->buffer;
rs->len = rs->cont_size;
rs->cont_extent = 0;
rs->cont_size = 0;
rs->cont_offset = 0;
return 0;
}
printk("Unable to read rock-ridge attributes\n");
}
out:
kfree(rs->buffer);
rs->buffer = NULL;
return ret;
}
| 166,236
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
(*sp->decodepfunc)(tif, op0, occ0);
return 1;
} else
return 0;
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
return (*sp->decodepfunc)(tif, op0, occ0);
} else
return 0;
}
| 166,876
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: is_link_trusted (NautilusFile *file,
gboolean is_launcher)
{
GFile *location;
gboolean res;
if (!is_launcher)
{
return TRUE;
}
if (nautilus_file_can_execute (file))
{
return TRUE;
}
res = FALSE;
if (nautilus_file_is_local (file))
{
location = nautilus_file_get_location (file);
res = nautilus_is_in_system_dir (location);
g_object_unref (location);
}
return res;
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20
|
is_link_trusted (NautilusFile *file,
gboolean is_launcher)
{
GFile *location;
gboolean res;
g_autofree gchar* trusted = NULL;
if (!is_launcher)
{
return TRUE;
}
trusted = nautilus_file_get_metadata (file,
NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED,
NULL);
if (nautilus_file_can_execute (file) && trusted != NULL)
{
return TRUE;
}
res = FALSE;
if (nautilus_file_is_local (file))
{
location = nautilus_file_get_location (file);
res = nautilus_is_in_system_dir (location);
g_object_unref (location);
}
return res;
}
| 167,746
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!indexed_db_observer_) {
indexed_db_observer_ = std::make_unique<IndexedDBObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<IndexedDBContextImpl*>(
process_->GetStoragePartition()->GetIndexedDBContext()));
}
return indexed_db_observer_.get();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!indexed_db_observer_) {
indexed_db_observer_ = std::make_unique<IndexedDBObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<IndexedDBContextImpl*>(
storage_partition_->GetIndexedDBContext()));
}
return indexed_db_observer_.get();
}
| 172,772
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.