instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuProcessHost::OnProcessLaunched() {
base::ProcessHandle child_handle = in_process_ ?
base::GetCurrentProcessHandle() : process_->GetData().handle;
#if defined(OS_WIN)
DuplicateHandle(base::GetCurrentProcessHandle(),
child_handle,
base::GetCurrentProcessHandle(),
&gpu_process_,
PROCESS_DUP_HANDLE,
FALSE,
0);
#else
gpu_process_ = child_handle;
#endif
UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
base::TimeTicks::Now() - init_start_time_);
}
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 GpuProcessHost::OnProcessLaunched() {
UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
base::TimeTicks::Now() - init_start_time_);
}
| 170,923 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LockContentsView::UserState::UserState(AccountId account_id)
: account_id(account_id) {}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | LockContentsView::UserState::UserState(AccountId account_id)
| 172,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (IsInvalidIndex(index))
return;
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
| 170,822 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target,
GLenum attachment,
WebGLTexture* texture,
GLint level,
GLint layer) {
if (isContextLost() || !ValidateFramebufferFuncParameters(
"framebufferTextureLayer", target, attachment))
return;
if (texture && !texture->Validate(ContextGroup(), this)) {
SynthesizeGLError(GL_INVALID_VALUE, "framebufferTextureLayer",
"no texture or texture not from this context");
return;
}
GLenum textarget = texture ? texture->GetTarget() : 0;
if (texture) {
if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"invalid texture type");
return;
}
if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer))
return;
if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level))
return;
}
WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target);
if (!framebuffer_binding || !framebuffer_binding->Object()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"no framebuffer bound");
return;
}
if (framebuffer_binding && framebuffer_binding->Opaque()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"opaque framebuffer bound");
return;
}
framebuffer_binding->SetAttachmentForBoundFramebuffer(
target, attachment, textarget, texture, level, layer);
ApplyStencilTest();
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | void WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target,
GLenum attachment,
WebGLTexture* texture,
GLint level,
GLint layer) {
if (isContextLost() || !ValidateFramebufferFuncParameters(
"framebufferTextureLayer", target, attachment))
return;
if (texture && !texture->Validate(ContextGroup(), this)) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"texture does not belong to this context");
return;
}
GLenum textarget = texture ? texture->GetTarget() : 0;
if (texture) {
if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"invalid texture type");
return;
}
if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer))
return;
if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level))
return;
}
WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target);
if (!framebuffer_binding || !framebuffer_binding->Object()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"no framebuffer bound");
return;
}
if (framebuffer_binding && framebuffer_binding->Opaque()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"opaque framebuffer bound");
return;
}
framebuffer_binding->SetAttachmentForBoundFramebuffer(
target, attachment, textarget, texture, level, layer);
ApplyStencilTest();
}
| 173,125 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static uint32_t readU16(const uint8_t* data, size_t offset) {
return data[offset] << 8 | data[offset + 1];
}
Commit Message: Avoid integer overflows in parsing fonts
A malformed TTF can cause size calculations to overflow. This patch
checks the maximum reasonable value so that the total size fits in 32
bits. It also adds some explicit casting to avoid possible technical
undefined behavior when parsing sized unsigned values.
Bug: 25645298
Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616
(cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274)
CWE ID: CWE-19 | static uint32_t readU16(const uint8_t* data, size_t offset) {
return ((uint32_t)data[offset]) << 8 | ((uint32_t)data[offset + 1]);
}
| 173,966 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int http_proxy_open(URLContext *h, const char *uri, int flags)
{
HTTPContext *s = h->priv_data;
char hostname[1024], hoststr[1024];
char auth[1024], pathbuf[1024], *path;
char lower_url[100];
int port, ret = 0, attempts = 0;
HTTPAuthType cur_auth_type;
char *authstr;
int new_loc;
if( s->seekable == 1 )
h->is_streamed = 0;
else
h->is_streamed = 1;
av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
pathbuf, sizeof(pathbuf), uri);
ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
path = pathbuf;
if (*path == '/')
path++;
ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
NULL);
redo:
ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
&h->interrupt_callback, NULL,
h->protocol_whitelist, h->protocol_blacklist, h);
if (ret < 0)
return ret;
authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
path, "CONNECT");
snprintf(s->buffer, sizeof(s->buffer),
"CONNECT %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"%s%s"
"\r\n",
path,
hoststr,
authstr ? "Proxy-" : "", authstr ? authstr : "");
av_freep(&authstr);
if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto fail;
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->filesize = -1;
cur_auth_type = s->proxy_auth_state.auth_type;
/* Note: This uses buffering, potentially reading more than the
* HTTP header. If tunneling a protocol where the server starts
* the conversation, we might buffer part of that here, too.
* Reading that requires using the proper ffurl_read() function
* on this URLContext, not using the fd directly (as the tls
* protocol does). This shouldn't be an issue for tls though,
* since the client starts the conversation there, so there
* is no extra data that we might buffer up here.
*/
ret = http_read_header(h, &new_loc);
if (ret < 0)
goto fail;
attempts++;
if (s->http_code == 407 &&
(cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
ffurl_closep(&s->hd);
goto redo;
}
if (s->http_code < 400)
return 0;
ret = ff_http_averror(s->http_code, AVERROR(EIO));
fail:
http_proxy_close(h);
return ret;
}
Commit Message: http: make length/offset-related variables unsigned.
Fixes #5992, reported and found by Paul Cher <[email protected]>.
CWE ID: CWE-119 | static int http_proxy_open(URLContext *h, const char *uri, int flags)
{
HTTPContext *s = h->priv_data;
char hostname[1024], hoststr[1024];
char auth[1024], pathbuf[1024], *path;
char lower_url[100];
int port, ret = 0, attempts = 0;
HTTPAuthType cur_auth_type;
char *authstr;
int new_loc;
if( s->seekable == 1 )
h->is_streamed = 0;
else
h->is_streamed = 1;
av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
pathbuf, sizeof(pathbuf), uri);
ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
path = pathbuf;
if (*path == '/')
path++;
ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
NULL);
redo:
ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
&h->interrupt_callback, NULL,
h->protocol_whitelist, h->protocol_blacklist, h);
if (ret < 0)
return ret;
authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
path, "CONNECT");
snprintf(s->buffer, sizeof(s->buffer),
"CONNECT %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"%s%s"
"\r\n",
path,
hoststr,
authstr ? "Proxy-" : "", authstr ? authstr : "");
av_freep(&authstr);
if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto fail;
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->filesize = UINT64_MAX;
cur_auth_type = s->proxy_auth_state.auth_type;
/* Note: This uses buffering, potentially reading more than the
* HTTP header. If tunneling a protocol where the server starts
* the conversation, we might buffer part of that here, too.
* Reading that requires using the proper ffurl_read() function
* on this URLContext, not using the fd directly (as the tls
* protocol does). This shouldn't be an issue for tls though,
* since the client starts the conversation there, so there
* is no extra data that we might buffer up here.
*/
ret = http_read_header(h, &new_loc);
if (ret < 0)
goto fail;
attempts++;
if (s->http_code == 407 &&
(cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
ffurl_closep(&s->hd);
goto redo;
}
if (s->http_code < 400)
return 0;
ret = ff_http_averror(s->http_code, AVERROR(EIO));
fail:
http_proxy_close(h);
return ret;
}
| 168,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,
int cpu_id)
{
struct ring_buffer_per_cpu *cpu_buffer;
unsigned long nr_pages;
int cpu, err = 0;
/*
* Always succeed at resizing a non-existent buffer:
*/
if (!buffer)
return size;
/* Make sure the requested buffer exists */
if (cpu_id != RING_BUFFER_ALL_CPUS &&
!cpumask_test_cpu(cpu_id, buffer->cpumask))
return size;
size = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
size *= BUF_PAGE_SIZE;
/* we need a minimum of two pages */
if (size < BUF_PAGE_SIZE * 2)
size = BUF_PAGE_SIZE * 2;
nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
/*
* Don't succeed if resizing is disabled, as a reader might be
* manipulating the ring buffer and is expecting a sane state while
* this is true.
*/
if (atomic_read(&buffer->resize_disabled))
return -EBUSY;
/* prevent another thread from changing buffer sizes */
mutex_lock(&buffer->mutex);
if (cpu_id == RING_BUFFER_ALL_CPUS) {
/* calculate the pages to update */
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
cpu_buffer->nr_pages_to_update = nr_pages -
cpu_buffer->nr_pages;
/*
* nothing more to do for removing pages or no update
*/
if (cpu_buffer->nr_pages_to_update <= 0)
continue;
/*
* to add pages, make sure all new pages can be
* allocated without receiving ENOMEM
*/
INIT_LIST_HEAD(&cpu_buffer->new_pages);
if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
&cpu_buffer->new_pages, cpu)) {
/* not enough memory for new pages */
err = -ENOMEM;
goto out_err;
}
}
get_online_cpus();
/*
* Fire off all the required work handlers
* We can't schedule on offline CPUs, but it's not necessary
* since we can change their buffer sizes without any race.
*/
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
if (!cpu_buffer->nr_pages_to_update)
continue;
/* Can't run something on an offline CPU. */
if (!cpu_online(cpu)) {
rb_update_pages(cpu_buffer);
cpu_buffer->nr_pages_to_update = 0;
} else {
schedule_work_on(cpu,
&cpu_buffer->update_pages_work);
}
}
/* wait for all the updates to complete */
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
if (!cpu_buffer->nr_pages_to_update)
continue;
if (cpu_online(cpu))
wait_for_completion(&cpu_buffer->update_done);
cpu_buffer->nr_pages_to_update = 0;
}
put_online_cpus();
} else {
/* Make sure this CPU has been intitialized */
if (!cpumask_test_cpu(cpu_id, buffer->cpumask))
goto out;
cpu_buffer = buffer->buffers[cpu_id];
if (nr_pages == cpu_buffer->nr_pages)
goto out;
cpu_buffer->nr_pages_to_update = nr_pages -
cpu_buffer->nr_pages;
INIT_LIST_HEAD(&cpu_buffer->new_pages);
if (cpu_buffer->nr_pages_to_update > 0 &&
__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
&cpu_buffer->new_pages, cpu_id)) {
err = -ENOMEM;
goto out_err;
}
get_online_cpus();
/* Can't run something on an offline CPU. */
if (!cpu_online(cpu_id))
rb_update_pages(cpu_buffer);
else {
schedule_work_on(cpu_id,
&cpu_buffer->update_pages_work);
wait_for_completion(&cpu_buffer->update_done);
}
cpu_buffer->nr_pages_to_update = 0;
put_online_cpus();
}
out:
/*
* The ring buffer resize can happen with the ring buffer
* enabled, so that the update disturbs the tracing as little
* as possible. But if the buffer is disabled, we do not need
* to worry about that, and we can take the time to verify
* that the buffer is not corrupt.
*/
if (atomic_read(&buffer->record_disabled)) {
atomic_inc(&buffer->record_disabled);
/*
* Even though the buffer was disabled, we must make sure
* that it is truly disabled before calling rb_check_pages.
* There could have been a race between checking
* record_disable and incrementing it.
*/
synchronize_sched();
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
rb_check_pages(cpu_buffer);
}
atomic_dec(&buffer->record_disabled);
}
mutex_unlock(&buffer->mutex);
return size;
out_err:
for_each_buffer_cpu(buffer, cpu) {
struct buffer_page *bpage, *tmp;
cpu_buffer = buffer->buffers[cpu];
cpu_buffer->nr_pages_to_update = 0;
if (list_empty(&cpu_buffer->new_pages))
continue;
list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
list) {
list_del_init(&bpage->list);
free_buffer_page(bpage);
}
}
mutex_unlock(&buffer->mutex);
return err;
}
Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize()
If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE
then the DIV_ROUND_UP() will return zero.
Here's the details:
# echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb
tracing_entries_write() processes this and converts kb to bytes.
18014398509481980 << 10 = 18446744073709547520
and this is passed to ring_buffer_resize() as unsigned long size.
size = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
Where DIV_ROUND_UP(a, b) is (a + b - 1)/b
BUF_PAGE_SIZE is 4080 and here
18446744073709547520 + 4080 - 1 = 18446744073709551599
where 18446744073709551599 is still smaller than 2^64
2^64 - 18446744073709551599 = 17
But now 18446744073709551599 / 4080 = 4521260802379792
and size = size * 4080 = 18446744073709551360
This is checked to make sure its still greater than 2 * 4080,
which it is.
Then we convert to the number of buffer pages needed.
nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE)
but this time size is 18446744073709551360 and
2^64 - (18446744073709551360 + 4080 - 1) = -3823
Thus it overflows and the resulting number is less than 4080, which makes
3823 / 4080 = 0
an nr_pages is set to this. As we already checked against the minimum that
nr_pages may be, this causes the logic to fail as well, and we crash the
kernel.
There's no reason to have the two DIV_ROUND_UP() (that's just result of
historical code changes), clean up the code and fix this bug.
Cc: [email protected] # 3.5+
Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic")
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID: CWE-190 | int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,
int cpu_id)
{
struct ring_buffer_per_cpu *cpu_buffer;
unsigned long nr_pages;
int cpu, err = 0;
/*
* Always succeed at resizing a non-existent buffer:
*/
if (!buffer)
return size;
/* Make sure the requested buffer exists */
if (cpu_id != RING_BUFFER_ALL_CPUS &&
!cpumask_test_cpu(cpu_id, buffer->cpumask))
return size;
nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
/* we need a minimum of two pages */
if (nr_pages < 2)
nr_pages = 2;
size = nr_pages * BUF_PAGE_SIZE;
/*
* Don't succeed if resizing is disabled, as a reader might be
* manipulating the ring buffer and is expecting a sane state while
* this is true.
*/
if (atomic_read(&buffer->resize_disabled))
return -EBUSY;
/* prevent another thread from changing buffer sizes */
mutex_lock(&buffer->mutex);
if (cpu_id == RING_BUFFER_ALL_CPUS) {
/* calculate the pages to update */
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
cpu_buffer->nr_pages_to_update = nr_pages -
cpu_buffer->nr_pages;
/*
* nothing more to do for removing pages or no update
*/
if (cpu_buffer->nr_pages_to_update <= 0)
continue;
/*
* to add pages, make sure all new pages can be
* allocated without receiving ENOMEM
*/
INIT_LIST_HEAD(&cpu_buffer->new_pages);
if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
&cpu_buffer->new_pages, cpu)) {
/* not enough memory for new pages */
err = -ENOMEM;
goto out_err;
}
}
get_online_cpus();
/*
* Fire off all the required work handlers
* We can't schedule on offline CPUs, but it's not necessary
* since we can change their buffer sizes without any race.
*/
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
if (!cpu_buffer->nr_pages_to_update)
continue;
/* Can't run something on an offline CPU. */
if (!cpu_online(cpu)) {
rb_update_pages(cpu_buffer);
cpu_buffer->nr_pages_to_update = 0;
} else {
schedule_work_on(cpu,
&cpu_buffer->update_pages_work);
}
}
/* wait for all the updates to complete */
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
if (!cpu_buffer->nr_pages_to_update)
continue;
if (cpu_online(cpu))
wait_for_completion(&cpu_buffer->update_done);
cpu_buffer->nr_pages_to_update = 0;
}
put_online_cpus();
} else {
/* Make sure this CPU has been intitialized */
if (!cpumask_test_cpu(cpu_id, buffer->cpumask))
goto out;
cpu_buffer = buffer->buffers[cpu_id];
if (nr_pages == cpu_buffer->nr_pages)
goto out;
cpu_buffer->nr_pages_to_update = nr_pages -
cpu_buffer->nr_pages;
INIT_LIST_HEAD(&cpu_buffer->new_pages);
if (cpu_buffer->nr_pages_to_update > 0 &&
__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
&cpu_buffer->new_pages, cpu_id)) {
err = -ENOMEM;
goto out_err;
}
get_online_cpus();
/* Can't run something on an offline CPU. */
if (!cpu_online(cpu_id))
rb_update_pages(cpu_buffer);
else {
schedule_work_on(cpu_id,
&cpu_buffer->update_pages_work);
wait_for_completion(&cpu_buffer->update_done);
}
cpu_buffer->nr_pages_to_update = 0;
put_online_cpus();
}
out:
/*
* The ring buffer resize can happen with the ring buffer
* enabled, so that the update disturbs the tracing as little
* as possible. But if the buffer is disabled, we do not need
* to worry about that, and we can take the time to verify
* that the buffer is not corrupt.
*/
if (atomic_read(&buffer->record_disabled)) {
atomic_inc(&buffer->record_disabled);
/*
* Even though the buffer was disabled, we must make sure
* that it is truly disabled before calling rb_check_pages.
* There could have been a race between checking
* record_disable and incrementing it.
*/
synchronize_sched();
for_each_buffer_cpu(buffer, cpu) {
cpu_buffer = buffer->buffers[cpu];
rb_check_pages(cpu_buffer);
}
atomic_dec(&buffer->record_disabled);
}
mutex_unlock(&buffer->mutex);
return size;
out_err:
for_each_buffer_cpu(buffer, cpu) {
struct buffer_page *bpage, *tmp;
cpu_buffer = buffer->buffers[cpu];
cpu_buffer->nr_pages_to_update = 0;
if (list_empty(&cpu_buffer->new_pages))
continue;
list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
list) {
list_del_init(&bpage->list);
free_buffer_page(bpage);
}
}
mutex_unlock(&buffer->mutex);
return err;
}
| 168,676 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: g_NPN_GetValue(NPP instance, NPNVariable variable, void *value)
{
D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable)));
if (!thread_check()) {
npw_printf("WARNING: NPN_GetValue not called from the main thread\n");
return NPERR_INVALID_INSTANCE_ERROR;
}
PluginInstance *plugin = NULL;
if (instance)
plugin = PLUGIN_INSTANCE(instance);
switch (variable) {
case NPNVxDisplay:
*(void **)value = x_display;
break;
case NPNVxtAppContext:
*(void **)value = XtDisplayToApplicationContext(x_display);
break;
case NPNVToolkit:
*(NPNToolkitType *)value = NPW_TOOLKIT;
break;
#if USE_XPCOM
case NPNVserviceManager: {
nsIServiceManager *sm;
int ret = NS_GetServiceManager(&sm);
if (NS_FAILED(ret)) {
npw_printf("WARNING: NS_GetServiceManager failed\n");
return NPERR_GENERIC_ERROR;
}
*(nsIServiceManager **)value = sm;
break;
}
case NPNVDOMWindow:
case NPNVDOMElement:
npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable));
return NPERR_INVALID_PARAM;
#endif
case NPNVnetscapeWindow:
if (plugin == NULL) {
npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n");
return NPERR_INVALID_INSTANCE_ERROR;
}
if (plugin->browser_toplevel == NULL) {
GdkNativeWindow netscape_xid = None;
NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid);
if (error != NPERR_NO_ERROR)
return error;
if (netscape_xid == None)
return NPERR_GENERIC_ERROR;
plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid);
if (plugin->browser_toplevel == NULL)
return NPERR_GENERIC_ERROR;
}
*((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel);
break;
#if ALLOW_WINDOWLESS_PLUGINS
case NPNVSupportsWindowless:
#endif
case NPNVSupportsXEmbedBool:
case NPNVWindowNPObject:
case NPNVPluginElementNPObject:
return g_NPN_GetValue_real(instance, variable, value);
default:
switch (variable & 0xff) {
case 13: /* NPNVToolkit */
if (NPW_TOOLKIT == NPNVGtk2) {
*(NPNToolkitType *)value = NPW_TOOLKIT;
return NPERR_NO_ERROR;
}
break;
}
D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable)));
return NPERR_INVALID_PARAM;
}
return NPERR_NO_ERROR;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264 | g_NPN_GetValue(NPP instance, NPNVariable variable, void *value)
{
D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable)));
if (!thread_check()) {
npw_printf("WARNING: NPN_GetValue not called from the main thread\n");
return NPERR_INVALID_INSTANCE_ERROR;
}
PluginInstance *plugin = NULL;
if (instance)
plugin = PLUGIN_INSTANCE(instance);
switch (variable) {
case NPNVxDisplay:
*(void **)value = x_display;
break;
case NPNVxtAppContext:
*(void **)value = XtDisplayToApplicationContext(x_display);
break;
case NPNVToolkit:
*(NPNToolkitType *)value = NPW_TOOLKIT;
break;
#if USE_XPCOM
case NPNVserviceManager: {
nsIServiceManager *sm;
int ret = NS_GetServiceManager(&sm);
if (NS_FAILED(ret)) {
npw_printf("WARNING: NS_GetServiceManager failed\n");
return NPERR_GENERIC_ERROR;
}
*(nsIServiceManager **)value = sm;
break;
}
case NPNVDOMWindow:
case NPNVDOMElement:
npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable));
return NPERR_INVALID_PARAM;
#endif
case NPNVnetscapeWindow:
if (plugin == NULL) {
npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n");
return NPERR_INVALID_INSTANCE_ERROR;
}
if (plugin->browser_toplevel == NULL) {
GdkNativeWindow netscape_xid = None;
NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid);
if (error != NPERR_NO_ERROR)
return error;
if (netscape_xid == None)
return NPERR_GENERIC_ERROR;
plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid);
if (plugin->browser_toplevel == NULL)
return NPERR_GENERIC_ERROR;
}
*((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel);
break;
#if ALLOW_WINDOWLESS_PLUGINS
case NPNVSupportsWindowless:
#endif
case NPNVSupportsXEmbedBool:
case NPNVWindowNPObject:
case NPNVPluginElementNPObject:
case NPNVprivateModeBool:
case NPNVsupportsAdvancedKeyHandling:
return g_NPN_GetValue_real(instance, variable, value);
default:
switch (variable & 0xff) {
case 13: /* NPNVToolkit */
if (NPW_TOOLKIT == NPNVGtk2) {
*(NPNToolkitType *)value = NPW_TOOLKIT;
return NPERR_NO_ERROR;
}
break;
}
D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable)));
return NPERR_INVALID_PARAM;
}
return NPERR_NO_ERROR;
}
| 165,864 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rename_in_ns(int pid, char *oldname, char **newnamep)
{
int fd = -1, ofd = -1, ret, ifindex = -1;
bool grab_newname = false;
ofd = lxc_preserve_ns(getpid(), "net");
if (ofd < 0) {
fprintf(stderr, "Failed opening network namespace path for '%d'.", getpid());
return -1;
}
fd = lxc_preserve_ns(pid, "net");
if (fd < 0) {
fprintf(stderr, "Failed opening network namespace path for '%d'.", pid);
return -1;
}
if (setns(fd, 0) < 0) {
fprintf(stderr, "setns to container network namespace\n");
goto out_err;
}
close(fd); fd = -1;
if (!*newnamep) {
grab_newname = true;
*newnamep = VETH_DEF_NAME;
if (!(ifindex = if_nametoindex(oldname))) {
fprintf(stderr, "failed to get netdev index\n");
goto out_err;
}
}
if ((ret = lxc_netdev_rename_by_name(oldname, *newnamep)) < 0) {
fprintf(stderr, "Error %d renaming netdev %s to %s in container\n", ret, oldname, *newnamep);
goto out_err;
}
if (grab_newname) {
char ifname[IFNAMSIZ], *namep = ifname;
if (!if_indextoname(ifindex, namep)) {
fprintf(stderr, "Failed to get new netdev name\n");
goto out_err;
}
*newnamep = strdup(namep);
if (!*newnamep)
goto out_err;
}
if (setns(ofd, 0) < 0) {
fprintf(stderr, "Error returning to original netns\n");
close(ofd);
return -1;
}
close(ofd);
return 0;
out_err:
if (ofd >= 0)
close(ofd);
if (setns(ofd, 0) < 0)
fprintf(stderr, "Error returning to original network namespace\n");
if (fd >= 0)
close(fd);
return -1;
}
Commit Message: CVE-2017-5985: Ensure target netns is caller-owned
Before this commit, lxc-user-nic could potentially have been tricked into
operating on a network namespace over which the caller did not hold privilege.
This commit ensures that the caller is privileged over the network namespace by
temporarily dropping privilege.
Launchpad: https://bugs.launchpad.net/ubuntu/+source/lxc/+bug/1654676
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Christian Brauner <[email protected]>
CWE ID: CWE-862 | static int rename_in_ns(int pid, char *oldname, char **newnamep)
{
uid_t ruid, suid, euid;
int fret = -1;
int fd = -1, ifindex = -1, ofd = -1, ret;
bool grab_newname = false;
ofd = lxc_preserve_ns(getpid(), "net");
if (ofd < 0) {
usernic_error("Failed opening network namespace path for '%d'.", getpid());
return fret;
}
fd = lxc_preserve_ns(pid, "net");
if (fd < 0) {
usernic_error("Failed opening network namespace path for '%d'.", pid);
goto do_partial_cleanup;
}
ret = getresuid(&ruid, &euid, &suid);
if (ret < 0) {
usernic_error("Failed to retrieve real, effective, and saved "
"user IDs: %s\n",
strerror(errno));
goto do_partial_cleanup;
}
ret = setns(fd, CLONE_NEWNET);
close(fd);
fd = -1;
if (ret < 0) {
usernic_error("Failed to setns() to the network namespace of "
"the container with PID %d: %s.\n",
pid, strerror(errno));
goto do_partial_cleanup;
}
ret = setresuid(ruid, ruid, 0);
if (ret < 0) {
usernic_error("Failed to drop privilege by setting effective "
"user id and real user id to %d, and saved user "
"ID to 0: %s.\n",
ruid, strerror(errno));
// COMMENT(brauner): It's ok to jump to do_full_cleanup here
// since setresuid() will succeed when trying to set real,
// effective, and saved to values they currently have.
goto do_full_cleanup;
}
if (!*newnamep) {
grab_newname = true;
*newnamep = VETH_DEF_NAME;
ifindex = if_nametoindex(oldname);
if (!ifindex) {
usernic_error("Failed to get netdev index: %s.\n", strerror(errno));
goto do_full_cleanup;
}
}
ret = lxc_netdev_rename_by_name(oldname, *newnamep);
if (ret < 0) {
usernic_error("Error %d renaming netdev %s to %s in container.\n", ret, oldname, *newnamep);
goto do_full_cleanup;
}
if (grab_newname) {
char ifname[IFNAMSIZ];
char *namep = ifname;
if (!if_indextoname(ifindex, namep)) {
usernic_error("Failed to get new netdev name: %s.\n", strerror(errno));
goto do_full_cleanup;
}
*newnamep = strdup(namep);
if (!*newnamep)
goto do_full_cleanup;
}
fret = 0;
do_full_cleanup:
ret = setresuid(ruid, euid, suid);
if (ret < 0) {
usernic_error("Failed to restore privilege by setting effective "
"user id to %d, real user id to %d, and saved user "
"ID to %d: %s.\n",
ruid, euid, suid, strerror(errno));
fret = -1;
// COMMENT(brauner): setns() should fail if setresuid() doesn't
// succeed but there's no harm in falling through; keeps the
// code cleaner.
}
ret = setns(ofd, CLONE_NEWNET);
if (ret < 0) {
usernic_error("Failed to setns() to original network namespace "
"of PID %d: %s.\n",
ofd, strerror(errno));
fret = -1;
}
do_partial_cleanup:
if (fd >= 0)
close(fd);
close(ofd);
return fret;
}
| 168,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode clamp_mode,
ImageDecodingMode) {
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode,
PaintImageForCurrentFrame());
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode clamp_mode,
ImageDecodingMode) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode,
PaintImageForCurrentFrame());
}
| 172,600 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Chapters::Display::Clear()
{
delete[] m_string;
m_string = NULL;
delete[] m_language;
m_language = NULL;
delete[] m_country;
m_country = NULL;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Chapters::Display::Clear()
| 174,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
return FALSE;
}
sock_cmd_t cmd = {CMD_USER_PRIVATE, 0, type, size, user_id};
APPL_TRACE_DEBUG("post cmd type:%d, size:%d, h:%d, ", type, size, h);
sock_cmd_t* cmd_send = &cmd;
int size_send = sizeof(cmd);
if(data && size)
{
size_send = sizeof(cmd) + size;
cmd_send = (sock_cmd_t*)alloca(size_send);
if(cmd_send)
{
*cmd_send = cmd;
memcpy(cmd_send + 1, data, size);
}
else
{
APPL_TRACE_ERROR("alloca failed at h:%d, cmd type:%d, size:%d", h, type, size_send);
return FALSE;
}
}
return send(ts[h].cmd_fdw, cmd_send, size_send, 0) == size_send;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
return FALSE;
}
sock_cmd_t cmd = {CMD_USER_PRIVATE, 0, type, size, user_id};
APPL_TRACE_DEBUG("post cmd type:%d, size:%d, h:%d, ", type, size, h);
sock_cmd_t* cmd_send = &cmd;
int size_send = sizeof(cmd);
if(data && size)
{
size_send = sizeof(cmd) + size;
cmd_send = (sock_cmd_t*)alloca(size_send);
if(cmd_send)
{
*cmd_send = cmd;
memcpy(cmd_send + 1, data, size);
}
else
{
APPL_TRACE_ERROR("alloca failed at h:%d, cmd type:%d, size:%d", h, type, size_send);
return FALSE;
}
}
return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, cmd_send, size_send, 0)) == size_send;
}
| 173,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SVGStyleElement::DidNotifySubtreeInsertionsToDocument() {
if (StyleElement::ProcessStyleSheet(GetDocument(), *this) ==
StyleElement::kProcessingFatalError)
NotifyLoadedSheetAndAllCriticalSubresources(
kErrorOccurredLoadingSubresource);
}
Commit Message: Do not crash while reentrantly appending to style element.
When a node is inserted into a container, it is notified via
::InsertedInto. However, a node may request a second notification via
DidNotifySubtreeInsertionsToDocument, which occurs after all the children
have been notified as well. *StyleElement is currently using this
second notification.
This causes a problem, because *ScriptElement is using the same mechanism,
which in turn means that scripts can execute before the state of
*StyleElements are properly updated.
This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead
processes the stylesheet in ::InsertedInto. The original reason for using
::DidNotifySubtreeInsertionsToDocument in the first place appears to be
invalid now, as the test case is still passing.
[email protected], [email protected]
Bug: 853709, 847570
Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel
Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14
Reviewed-on: https://chromium-review.googlesource.com/1104347
Commit-Queue: Anders Ruud <[email protected]>
Reviewed-by: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#568368}
CWE ID: CWE-416 | void SVGStyleElement::DidNotifySubtreeInsertionsToDocument() {
if (isConnected()) {
if (StyleElement::ProcessStyleSheet(GetDocument(), *this) ==
StyleElement::kProcessingFatalError) {
NotifyLoadedSheetAndAllCriticalSubresources(
kErrorOccurredLoadingSubresource);
}
}
return kInsertionDone;
}
| 173,173 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_ini_end(PNG_CONST image_transform *this,
transform_display *that)
{
UNUSED(this)
UNUSED(that)
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_ini_end(PNG_CONST image_transform *this,
image_transform_ini_end(const image_transform *this,
transform_display *that)
{
UNUSED(this)
UNUSED(that)
}
| 173,622 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ClientControlledShellSurface::OnPreWidgetCommit() {
if (!widget_) {
if (!pending_geometry_.IsEmpty())
origin_ = pending_geometry_.origin();
CreateShellSurfaceWidget(ash::ToWindowShowState(pending_window_state_));
}
ash::wm::WindowState* window_state = GetWindowState();
if (window_state->GetStateType() == pending_window_state_) {
if (window_state->IsPip() && !window_state->is_dragged()) {
client_controlled_state_->set_next_bounds_change_animation_type(
ash::wm::ClientControlledState::kAnimationAnimated);
}
return true;
}
if (IsPinned(window_state)) {
VLOG(1) << "State change was requested while pinned";
return true;
}
auto animation_type = ash::wm::ClientControlledState::kAnimationNone;
switch (pending_window_state_) {
case ash::WindowStateType::kNormal:
if (widget_->IsMaximized() || widget_->IsFullscreen()) {
animation_type = ash::wm::ClientControlledState::kAnimationCrossFade;
}
break;
case ash::WindowStateType::kMaximized:
case ash::WindowStateType::kFullscreen:
if (!window_state->IsPip())
animation_type = ash::wm::ClientControlledState::kAnimationCrossFade;
break;
default:
break;
}
if (pending_window_state_ == ash::WindowStateType::kPip) {
if (ash::features::IsPipRoundedCornersEnabled()) {
decorator_ = std::make_unique<ash::RoundedCornerDecorator>(
window_state->window(), host_window(), host_window()->layer(),
ash::kPipRoundedCornerRadius);
}
} else {
decorator_.reset(); // Remove rounded corners.
}
bool wasPip = window_state->IsPip();
if (client_controlled_state_->EnterNextState(window_state,
pending_window_state_)) {
client_controlled_state_->set_next_bounds_change_animation_type(
animation_type);
}
if (wasPip && !window_state->IsMinimized()) {
ash::Shell::Get()->split_view_controller()->EndSplitView(
ash::SplitViewController::EndReason::kPipExpanded);
window_state->Activate();
}
return true;
}
Commit Message: Ignore updatePipBounds before initial bounds is set
When PIP enter/exit transition happens, window state change and
initial bounds change are committed in the same commit. However,
as state change is applied first in OnPreWidgetCommit and the
bounds is update later, if updatePipBounds is called between the
gap, it ends up returning a wrong bounds based on the previous
bounds.
Currently, there are two callstacks that end up triggering
updatePipBounds between the gap: (i) The state change causes
OnWindowAddedToLayout and updatePipBounds is called in OnWMEvent,
(ii) updatePipBounds is called in UpdatePipState to prevent it
from being placed under some system ui.
As it doesn't make sense to call updatePipBounds before the first
bounds is not set, this CL adds a boolean to defer updatePipBounds.
position.
Bug: b130782006
Test: Got VLC into PIP and confirmed it was placed at the correct
Change-Id: I5b9f3644bfb2533fd3f905bc09d49708a5d08a90
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1578719
Commit-Queue: Kazuki Takise <[email protected]>
Auto-Submit: Kazuki Takise <[email protected]>
Reviewed-by: Mitsuru Oshima <[email protected]>
Cr-Commit-Position: refs/heads/master@{#668724}
CWE ID: CWE-787 | bool ClientControlledShellSurface::OnPreWidgetCommit() {
if (!widget_) {
if (!pending_geometry_.IsEmpty())
origin_ = pending_geometry_.origin();
CreateShellSurfaceWidget(ash::ToWindowShowState(pending_window_state_));
}
ash::wm::WindowState* window_state = GetWindowState();
if (window_state->GetStateType() == pending_window_state_) {
if (window_state->IsPip() && !window_state->is_dragged()) {
client_controlled_state_->set_next_bounds_change_animation_type(
ash::wm::ClientControlledState::kAnimationAnimated);
}
return true;
}
if (IsPinned(window_state)) {
VLOG(1) << "State change was requested while pinned";
return true;
}
auto animation_type = ash::wm::ClientControlledState::kAnimationNone;
switch (pending_window_state_) {
case ash::WindowStateType::kNormal:
if (widget_->IsMaximized() || widget_->IsFullscreen()) {
animation_type = ash::wm::ClientControlledState::kAnimationCrossFade;
}
break;
case ash::WindowStateType::kMaximized:
case ash::WindowStateType::kFullscreen:
if (!window_state->IsPip())
animation_type = ash::wm::ClientControlledState::kAnimationCrossFade;
break;
default:
break;
}
if (pending_window_state_ == ash::WindowStateType::kPip) {
if (ash::features::IsPipRoundedCornersEnabled()) {
decorator_ = std::make_unique<ash::RoundedCornerDecorator>(
window_state->window(), host_window(), host_window()->layer(),
ash::kPipRoundedCornerRadius);
}
} else {
decorator_.reset(); // Remove rounded corners.
}
bool wasPip = window_state->IsPip();
// As the bounds of the widget is updated later, ensure that no bounds change
// happens with this state change (e.g. updatePipBounds can be triggered).
base::AutoReset<bool> resetter(&ignore_bounds_change_request_, true);
if (client_controlled_state_->EnterNextState(window_state,
pending_window_state_)) {
client_controlled_state_->set_next_bounds_change_animation_type(
animation_type);
}
if (wasPip && !window_state->IsMinimized()) {
ash::Shell::Get()->split_view_controller()->EndSplitView(
ash::SplitViewController::EndReason::kPipExpanded);
window_state->Activate();
}
return true;
}
| 172,409 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct bpf_prog *bpf_prog_get(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_prog *prog;
prog = __bpf_prog_get(f);
if (IS_ERR(prog))
return prog;
atomic_inc(&prog->aux->refcnt);
fdput(f);
return prog;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | struct bpf_prog *bpf_prog_get(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_prog *prog;
prog = __bpf_prog_get(f);
if (IS_ERR(prog))
return prog;
prog = bpf_prog_inc(prog);
fdput(f);
return prog;
}
| 167,254 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, request_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
g_print_preview_request_id_map.Get().Set(id_, request_id);
}
| 170,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId) + drdynvc_cblen_to_bytes(Sp))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
| 168,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
{
assign_eip_near(ctxt, ctxt->_eip + rel);
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static inline void jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
{
return assign_eip_near(ctxt, ctxt->_eip + rel);
}
| 169,916 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintWebViewHelper::Print(WebKit::WebFrame* frame, WebKit::WebNode* node) {
if (print_web_view_)
return;
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(frame, node, &prepare))
return; // Failed to init print page settings.
int expected_page_count = 0;
bool use_browser_overlays = true;
expected_page_count = prepare->GetExpectedPageCount();
if (expected_page_count)
use_browser_overlays = prepare->ShouldUseBrowserOverlays();
prepare.reset();
if (!expected_page_count) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!GetPrintSettingsFromUser(frame, expected_page_count,
use_browser_overlays)) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!RenderPagesForPrint(frame, node, NULL)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
ResetScriptedPrintCount();
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PrintWebViewHelper::Print(WebKit::WebFrame* frame, WebKit::WebNode* node) {
if (print_web_view_)
return;
scoped_ptr<PrepareFrameAndViewForPrint> prepare;
if (!InitPrintSettingsAndPrepareFrame(frame, node, &prepare)) {
DidFinishPrinting(FAIL_PRINT);
return; // Failed to init print page settings.
}
int expected_page_count = 0;
bool use_browser_overlays = true;
expected_page_count = prepare->GetExpectedPageCount();
if (expected_page_count)
use_browser_overlays = prepare->ShouldUseBrowserOverlays();
prepare.reset();
if (!expected_page_count) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!GetPrintSettingsFromUser(frame, expected_page_count,
use_browser_overlays)) {
DidFinishPrinting(OK); // Release resources and fail silently.
return;
}
if (!RenderPagesForPrint(frame, node, NULL)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
ResetScriptedPrintCount();
}
| 170,263 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn)
{
OMX_ERRORTYPE eRet = OMX_ErrorNone;
struct v4l2_format fmt;
if (!portDefn) {
return OMX_ErrorBadParameter;
}
DEBUG_PRINT_LOW("omx_vdec::update_portdef");
portDefn->nVersion.nVersion = OMX_SPEC_VERSION;
portDefn->nSize = sizeof(portDefn);
portDefn->eDomain = OMX_PortDomainVideo;
if (drv_ctx.frame_rate.fps_denominator > 0)
portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator /
drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format
else {
DEBUG_PRINT_ERROR("Error: Divide by zero");
return OMX_ErrorBadParameter;
}
memset(&fmt, 0x0, sizeof(struct v4l2_format));
if (0 == portDefn->nPortIndex) {
portDefn->eDir = OMX_DirInput;
portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount;
portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount;
portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size;
portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused;
portDefn->format.video.eCompressionFormat = eCompressionFormat;
portDefn->bEnabled = m_inp_bEnabled;
portDefn->bPopulated = m_inp_bPopulated;
fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
fmt.fmt.pix_mp.pixelformat = output_capability;
} else if (1 == portDefn->nPortIndex) {
unsigned int buf_size = 0;
if (!client_buffers.update_buffer_req()) {
DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed");
return OMX_ErrorHardware;
}
if (!client_buffers.get_buffer_req(buf_size)) {
DEBUG_PRINT_ERROR("update buffer requirements");
return OMX_ErrorHardware;
}
portDefn->nBufferSize = buf_size;
portDefn->eDir = OMX_DirOutput;
portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount;
portDefn->nBufferCountMin = drv_ctx.op_buf.mincount;
portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused;
portDefn->bEnabled = m_out_bEnabled;
portDefn->bPopulated = m_out_bPopulated;
if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) {
DEBUG_PRINT_ERROR("Error in getting color format");
return OMX_ErrorHardware;
}
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
fmt.fmt.pix_mp.pixelformat = capture_capability;
} else {
portDefn->eDir = OMX_DirMax;
DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d",
(int)portDefn->nPortIndex);
eRet = OMX_ErrorBadPortIndex;
}
if (is_down_scalar_enabled) {
int ret = 0;
ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt);
if (ret) {
DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution");
return OMX_ErrorHardware;
} else {
portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width;
portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height;
portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline;
portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0];
}
} else {
portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height;
portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width;
portDefn->format.video.nStride = drv_ctx.video_resolution.stride;
portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines;
}
if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) ||
(portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) {
portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16);
portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height;
}
DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d "
"SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u",
(unsigned int)portDefn->nPortIndex,
(unsigned int)portDefn->format.video.nFrameWidth,
(unsigned int)portDefn->format.video.nFrameHeight,
(int)portDefn->format.video.nStride,
(unsigned int)portDefn->format.video.nSliceHeight,
(unsigned int)portDefn->format.video.eColorFormat,
(unsigned int)portDefn->nBufferSize,
(unsigned int)portDefn->nBufferCountActual);
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data
Check the sanity of config/param strcuture objects
passed to get/set _ config()/parameter() methods.
Bug: 27533317
Security Vulnerability in MediaServer
omx_vdec::get_config() Can lead to arbitrary write
Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809
Conflicts:
mm-core/inc/OMX_QCOMExtns.h
mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp
mm-video-v4l2/vidc/venc/src/omx_video_base.cpp
mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp
CWE ID: CWE-20 | OMX_ERRORTYPE omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn)
{
OMX_ERRORTYPE eRet = OMX_ErrorNone;
struct v4l2_format fmt;
if (!portDefn) {
return OMX_ErrorBadParameter;
}
DEBUG_PRINT_LOW("omx_vdec::update_portdef");
portDefn->nVersion.nVersion = OMX_SPEC_VERSION;
portDefn->nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
portDefn->eDomain = OMX_PortDomainVideo;
if (drv_ctx.frame_rate.fps_denominator > 0)
portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator /
drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format
else {
DEBUG_PRINT_ERROR("Error: Divide by zero");
return OMX_ErrorBadParameter;
}
memset(&fmt, 0x0, sizeof(struct v4l2_format));
if (0 == portDefn->nPortIndex) {
portDefn->eDir = OMX_DirInput;
portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount;
portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount;
portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size;
portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused;
portDefn->format.video.eCompressionFormat = eCompressionFormat;
portDefn->bEnabled = m_inp_bEnabled;
portDefn->bPopulated = m_inp_bPopulated;
fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
fmt.fmt.pix_mp.pixelformat = output_capability;
} else if (1 == portDefn->nPortIndex) {
unsigned int buf_size = 0;
if (!client_buffers.update_buffer_req()) {
DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed");
return OMX_ErrorHardware;
}
if (!client_buffers.get_buffer_req(buf_size)) {
DEBUG_PRINT_ERROR("update buffer requirements");
return OMX_ErrorHardware;
}
portDefn->nBufferSize = buf_size;
portDefn->eDir = OMX_DirOutput;
portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount;
portDefn->nBufferCountMin = drv_ctx.op_buf.mincount;
portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused;
portDefn->bEnabled = m_out_bEnabled;
portDefn->bPopulated = m_out_bPopulated;
if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) {
DEBUG_PRINT_ERROR("Error in getting color format");
return OMX_ErrorHardware;
}
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
fmt.fmt.pix_mp.pixelformat = capture_capability;
} else {
portDefn->eDir = OMX_DirMax;
DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d",
(int)portDefn->nPortIndex);
eRet = OMX_ErrorBadPortIndex;
}
if (is_down_scalar_enabled) {
int ret = 0;
ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt);
if (ret) {
DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution");
return OMX_ErrorHardware;
} else {
portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width;
portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height;
portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline;
portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0];
}
} else {
portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height;
portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width;
portDefn->format.video.nStride = drv_ctx.video_resolution.stride;
portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines;
}
if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) ||
(portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) {
portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16);
portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height;
}
DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d "
"SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u",
(unsigned int)portDefn->nPortIndex,
(unsigned int)portDefn->format.video.nFrameWidth,
(unsigned int)portDefn->format.video.nFrameHeight,
(int)portDefn->format.video.nStride,
(unsigned int)portDefn->format.video.nSliceHeight,
(unsigned int)portDefn->format.video.eColorFormat,
(unsigned int)portDefn->nBufferSize,
(unsigned int)portDefn->nBufferCountActual);
return eRet;
}
| 173,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
}
Commit Message: Unsupported TGA bpp/alphabit combinations should error gracefully
Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are
really supported. All other combinations will be rejected with a warning.
CWE ID: CWE-125 | BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 && tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
}
| 167,004 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCache::RemoveEntry(const GURL& url) {
auto found = entries_.find(url);
DCHECK(found != entries_.end());
cache_size_ -= found->second.response_size();
entries_.erase(found);
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCache::RemoveEntry(const GURL& url) {
auto found = entries_.find(url);
DCHECK(found != entries_.end());
DCHECK_GE(cache_size_, found->second.response_size());
DCHECK_GE(padding_size_, found->second.padding_size());
cache_size_ -= found->second.response_size();
padding_size_ -= found->second.padding_size();
entries_.erase(found);
}
| 172,971 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)
{
gdImagePtr pim = 0, tim = im;
int interlace, BitsPerPixel;
interlace = im->interlace;
if (im->trueColor) {
/* Expensive, but the only way that produces an
acceptable result: mix down to a palette
based temporary image. */
pim = gdImageCreatePaletteFromTrueColor(im, 1, 256);
if (!pim) {
return;
}
tim = pim;
}
BitsPerPixel = colorstobpp(tim->colorsTotal);
/* All set, let's do it. */
GIFEncode(
out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel,
tim->red, tim->green, tim->blue, tim);
if (pim) {
/* Destroy palette based temporary image. */
gdImageDestroy( pim);
}
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415 | void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)
{
_gdImageGifCtx(im, out);
}
/* returns 0 on success, 1 on failure */
static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)
{
gdImagePtr pim = 0, tim = im;
int interlace, BitsPerPixel;
interlace = im->interlace;
if (im->trueColor) {
/* Expensive, but the only way that produces an
acceptable result: mix down to a palette
based temporary image. */
pim = gdImageCreatePaletteFromTrueColor(im, 1, 256);
if (!pim) {
return 1;
}
tim = pim;
}
BitsPerPixel = colorstobpp(tim->colorsTotal);
/* All set, let's do it. */
GIFEncode(
out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel,
tim->red, tim->green, tim->blue, tim);
if (pim) {
/* Destroy palette based temporary image. */
gdImageDestroy( pim);
}
return 0;
}
| 169,733 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SchedulerObject::hold(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, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-20 | SchedulerObject::hold(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, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
| 164,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register double
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (length == 0.0)
{
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
Commit Message: Prevent buffer overflow in magick/draw.c
CWE ID: CWE-119 | static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register double
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (length == 0.0)
{
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
| 167,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fdct8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct8x8_c(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void fdct8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
const int kSignBiasMaxDiff255 = 1500;
const int kSignBiasMaxDiff15 = 10000;
typedef void (*FdctFunc)(const int16_t *in, tran_low_t *out, int stride);
typedef void (*IdctFunc)(const tran_low_t *in, uint8_t *out, int stride);
typedef void (*FhtFunc)(const int16_t *in, tran_low_t *out, int stride,
int tx_type);
typedef void (*IhtFunc)(const tran_low_t *in, uint8_t *out, int stride,
int tx_type);
typedef std::tr1::tuple<FdctFunc, IdctFunc, int, vpx_bit_depth_t> Dct8x8Param;
typedef std::tr1::tuple<FhtFunc, IhtFunc, int, vpx_bit_depth_t> Ht8x8Param;
typedef std::tr1::tuple<IdctFunc, IdctFunc, int, vpx_bit_depth_t> Idct8x8Param;
void reference_8x8_dct_1d(const double in[8], double out[8], int stride) {
const double kInvSqrt2 = 0.707106781186547524400844362104;
for (int k = 0; k < 8; k++) {
out[k] = 0.0;
for (int n = 0; n < 8; n++)
out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 16.0);
if (k == 0)
out[k] = out[k] * kInvSqrt2;
}
}
| 174,564 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void registerURL(const char* url, const char* file, const char* mimeType)
{
registerMockedURLLoad(KURL(m_baseUrl, url), WebString::fromUTF8(file), m_folder, WebString::fromUTF8(mimeType));
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void registerURL(const char* url, const char* file, const char* mimeType)
| 171,574 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual InputMethodDescriptors* GetActiveInputMethods() {
chromeos::InputMethodDescriptors* result =
new chromeos::InputMethodDescriptors;
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
if (result->empty()) {
LOG(WARNING) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual InputMethodDescriptors* GetActiveInputMethods() {
virtual input_method::InputMethodDescriptors* GetActiveInputMethods() {
input_method::InputMethodDescriptors* result =
new input_method::InputMethodDescriptors;
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const input_method::InputMethodDescriptor* descriptor =
input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
if (result->empty()) {
LOG(WARNING) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
| 170,486 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zval *arg1;
zend_error_handling error_handling;
if (!file_path || !file_path_len) {
#if defined(PHP_WIN32)
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path");
if (file_path && !use_copy) {
efree(file_path);
}
#else
if (file_path && !use_copy) {
efree(file_path);
}
file_path_len = 1;
file_path = "/";
#endif
return NULL;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return intern;
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zval *arg1;
zend_error_handling error_handling;
if (!file_path || !file_path_len) {
#if defined(PHP_WIN32)
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path");
if (file_path && !use_copy) {
efree(file_path);
}
#else
if (file_path && !use_copy) {
efree(file_path);
}
file_path_len = 1;
file_path = "/";
#endif
return NULL;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return intern;
} /* }}} */
| 167,081 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseComment(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int size = XML_PARSER_BUFFER_SIZE;
int len = 0;
xmlParserInputState state;
const xmlChar *in;
int nbchar = 0, ccol;
int inputid;
/*
* Check that there is a comment right here.
*/
if ((RAW != '<') || (NXT(1) != '!') ||
(NXT(2) != '-') || (NXT(3) != '-')) return;
state = ctxt->instate;
ctxt->instate = XML_PARSER_COMMENT;
inputid = ctxt->input->id;
SKIP(4);
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
in = ctxt->input->cur;
do {
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
}
get_more:
ccol = ctxt->input->col;
while (((*in > '-') && (*in <= 0x7F)) ||
((*in >= 0x20) && (*in < '-')) ||
(*in == 0x09)) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
nbchar = in - ctxt->input->cur;
/*
* save current set of data
*/
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->comment != NULL)) {
if (buf == NULL) {
if ((*in == '-') && (in[1] == '-'))
size = nbchar + 1;
else
size = XML_PARSER_BUFFER_SIZE + nbchar;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
len = 0;
} else if (len + nbchar + 1 >= size) {
xmlChar *new_buf;
size += len + nbchar + XML_PARSER_BUFFER_SIZE;
new_buf = (xmlChar *) xmlRealloc(buf,
size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
buf = new_buf;
}
memcpy(&buf[len], ctxt->input->cur, nbchar);
len += nbchar;
buf[len] = 0;
}
}
ctxt->input->cur = in;
if (*in == 0xA) {
in++;
ctxt->input->line++; ctxt->input->col = 1;
}
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
SHRINK;
GROW;
in = ctxt->input->cur;
if (*in == '-') {
if (in[1] == '-') {
if (in[2] == '>') {
if (ctxt->input->id != inputid) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"comment doesn't start and stop in the same entity\n");
}
SKIP(3);
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX)) {
if (buf != NULL)
ctxt->sax->comment(ctxt->userData, buf);
else
ctxt->sax->comment(ctxt->userData, BAD_CAST "");
}
if (buf != NULL)
xmlFree(buf);
ctxt->instate = state;
return;
}
if (buf != NULL)
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n",
buf);
else
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n", NULL);
in++;
ctxt->input->col++;
}
in++;
ctxt->input->col++;
goto get_more;
}
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
xmlParseCommentComplex(ctxt, buf, len, size);
ctxt->instate = state;
return;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseComment(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int size = XML_PARSER_BUFFER_SIZE;
int len = 0;
xmlParserInputState state;
const xmlChar *in;
int nbchar = 0, ccol;
int inputid;
/*
* Check that there is a comment right here.
*/
if ((RAW != '<') || (NXT(1) != '!') ||
(NXT(2) != '-') || (NXT(3) != '-')) return;
state = ctxt->instate;
ctxt->instate = XML_PARSER_COMMENT;
inputid = ctxt->input->id;
SKIP(4);
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
in = ctxt->input->cur;
do {
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
}
get_more:
ccol = ctxt->input->col;
while (((*in > '-') && (*in <= 0x7F)) ||
((*in >= 0x20) && (*in < '-')) ||
(*in == 0x09)) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
nbchar = in - ctxt->input->cur;
/*
* save current set of data
*/
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->comment != NULL)) {
if (buf == NULL) {
if ((*in == '-') && (in[1] == '-'))
size = nbchar + 1;
else
size = XML_PARSER_BUFFER_SIZE + nbchar;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
len = 0;
} else if (len + nbchar + 1 >= size) {
xmlChar *new_buf;
size += len + nbchar + XML_PARSER_BUFFER_SIZE;
new_buf = (xmlChar *) xmlRealloc(buf,
size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
buf = new_buf;
}
memcpy(&buf[len], ctxt->input->cur, nbchar);
len += nbchar;
buf[len] = 0;
}
}
ctxt->input->cur = in;
if (*in == 0xA) {
in++;
ctxt->input->line++; ctxt->input->col = 1;
}
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
SHRINK;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
in = ctxt->input->cur;
if (*in == '-') {
if (in[1] == '-') {
if (in[2] == '>') {
if (ctxt->input->id != inputid) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"comment doesn't start and stop in the same entity\n");
}
SKIP(3);
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX)) {
if (buf != NULL)
ctxt->sax->comment(ctxt->userData, buf);
else
ctxt->sax->comment(ctxt->userData, BAD_CAST "");
}
if (buf != NULL)
xmlFree(buf);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
if (buf != NULL)
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n",
buf);
else
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n", NULL);
in++;
ctxt->input->col++;
}
in++;
ctxt->input->col++;
goto get_more;
}
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
xmlParseCommentComplex(ctxt, buf, len, size);
ctxt->instate = state;
return;
}
| 171,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UnloadController::TabDetachedAt(TabContents* contents, int index) {
TabDetachedImpl(contents);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void UnloadController::TabDetachedAt(TabContents* contents, int index) {
void UnloadController::TabDetachedAt(content::WebContents* contents,
int index) {
TabDetachedImpl(contents);
}
| 171,519 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)
{
char obj_txt[128];
int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);
BIO_write(bio, obj_txt, len);
BIO_write(bio, "\n", 1);
return 1;
}
Commit Message: Fix OOB read in TS_OBJ_print_bio().
TS_OBJ_print_bio() misuses OBJ_txt2obj: it should print the result
as a null terminated buffer. The length value returned is the total
length the complete text reprsentation would need not the amount of
data written.
CVE-2016-2180
Thanks to Shi Lei for reporting this bug.
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: CWE-125 | int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)
{
char obj_txt[128];
OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);
BIO_printf(bio, "%s\n", obj_txt);
return 1;
}
| 167,435 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, unsigned int *timeouts)
{
return true;
}
Commit Message: netfilter: conntrack: disable generic tracking for known protocols
Given following iptables ruleset:
-P FORWARD DROP
-A FORWARD -m sctp --dport 9 -j ACCEPT
-A FORWARD -p tcp --dport 80 -j ACCEPT
-A FORWARD -p tcp -m conntrack -m state ESTABLISHED,RELATED -j ACCEPT
One would assume that this allows SCTP on port 9 and TCP on port 80.
Unfortunately, if the SCTP conntrack module is not loaded, this allows
*all* SCTP communication, to pass though, i.e. -p sctp -j ACCEPT,
which we think is a security issue.
This is because on the first SCTP packet on port 9, we create a dummy
"generic l4" conntrack entry without any port information (since
conntrack doesn't know how to extract this information).
All subsequent packets that are unknown will then be in established
state since they will fallback to proto_generic and will match the
'generic' entry.
Our originally proposed version [1] completely disabled generic protocol
tracking, but Jozsef suggests to not track protocols for which a more
suitable helper is available, hence we now mitigate the issue for in
tree known ct protocol helpers only, so that at least NAT and direction
information will still be preserved for others.
[1] http://www.spinics.net/lists/netfilter-devel/msg33430.html
Joint work with Daniel Borkmann.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Jozsef Kadlecsik <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-254 | static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, unsigned int *timeouts)
{
return nf_generic_should_process(nf_ct_protonum(ct));
}
| 166,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: kadm5_randkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock **keyblocks,
int *n_keys)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_int32 now;
kadm5_policy_ent_rec pol;
int ret, last_pwd;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
if (keyblocks)
*keyblocks = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if (krb5_principal_compare(handle->context, principal, hist_princ)) {
/* If changing the history entry, the new entry must have exactly one
* key. */
if (keepold)
return KADM5_PROTECT_PRINCIPAL;
new_n_ks_tuple = 1;
}
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd);
if (ret)
goto done;
#if 0
/*
* The spec says this check is overridden if the caller has
* modify privilege. The admin server therefore makes this
* check itself (in chpass_principal_wrapper, misc.c). A
* local caller implicitly has all authorization bits.
*/
if((now - last_pwd) < pol.pw_min_life &&
!(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) {
ret = KADM5_PASS_TOOSOON;
goto done;
}
#endif
if (pol.pw_max_life)
kdb->pw_expiration = now + pol.pw_max_life;
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
if (keyblocks) {
ret = decrypt_key_data(handle->context,
kdb->n_key_data, kdb->key_data,
keyblocks, n_keys);
if (ret)
goto done;
}
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
/* | KADM5_RANDKEY_USED */;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, NULL);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, NULL);
ret = KADM5_OK;
done:
free(new_ks_tuple);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
Commit Message: Return only new keys in randkey [CVE-2014-5351]
In kadmind's randkey operation, if a client specifies the keepold
flag, do not include the preserved old keys in the response.
CVE-2014-5351:
An authenticated remote attacker can retrieve the current keys for a
service principal when generating a new set of keys for that
principal. The attacker needs to be authenticated as a user who has
the elevated privilege for randomizing the keys of other principals.
Normally, when a Kerberos administrator randomizes the keys of a
service principal, kadmind returns only the new keys. This prevents
an administrator who lacks legitimate privileged access to a service
from forging tickets to authenticate to that service. If the
"keepold" flag to the kadmin randkey RPC operation is true, kadmind
retains the old keys in the KDC database as intended, but also
unexpectedly returns the old keys to the client, which exposes the
service to ticket forgery attacks from the administrator.
A mitigating factor is that legitimate clients of the affected service
will start failing to authenticate to the service once they begin to
receive service tickets encrypted in the new keys. The affected
service will be unable to decrypt the newly issued tickets, possibly
alerting the legitimate administrator of the affected service.
CVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C
[[email protected]: CVE description and CVSS score]
ticket: 8018 (new)
target_version: 1.13
tags: pullup
CWE ID: CWE-255 | kadm5_randkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock **keyblocks,
int *n_keys)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_int32 now;
kadm5_policy_ent_rec pol;
int ret, last_pwd, n_new_keys;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
if (keyblocks)
*keyblocks = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if (krb5_principal_compare(handle->context, principal, hist_princ)) {
/* If changing the history entry, the new entry must have exactly one
* key. */
if (keepold)
return KADM5_PROTECT_PRINCIPAL;
new_n_ks_tuple = 1;
}
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd);
if (ret)
goto done;
#if 0
/*
* The spec says this check is overridden if the caller has
* modify privilege. The admin server therefore makes this
* check itself (in chpass_principal_wrapper, misc.c). A
* local caller implicitly has all authorization bits.
*/
if((now - last_pwd) < pol.pw_min_life &&
!(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) {
ret = KADM5_PASS_TOOSOON;
goto done;
}
#endif
if (pol.pw_max_life)
kdb->pw_expiration = now + pol.pw_max_life;
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
if (keyblocks) {
/* Return only the new keys added by krb5_dbe_crk. */
n_new_keys = count_new_keys(kdb->n_key_data, kdb->key_data);
ret = decrypt_key_data(handle->context, n_new_keys, kdb->key_data,
keyblocks, n_keys);
if (ret)
goto done;
}
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
/* | KADM5_RANDKEY_USED */;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, NULL);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, NULL);
ret = KADM5_OK;
done:
free(new_ks_tuple);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
| 166,275 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
}
Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-787 | static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0; i < 4 ; ++i) {
if (offsets[i] >= *total)
return -EINVAL;
if (i == 0)
continue;
if (offsets[i-1] > offsets[i])
return -EINVAL;
}
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
}
| 169,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,
struct ipcm_cookie *ipc, struct rtable **rtp)
{
struct inet_sock *inet = inet_sk(sk);
struct ip_options *opt;
struct rtable *rt;
/*
* setup for corking.
*/
opt = ipc->opt;
if (opt) {
if (cork->opt == NULL) {
cork->opt = kmalloc(sizeof(struct ip_options) + 40,
sk->sk_allocation);
if (unlikely(cork->opt == NULL))
return -ENOBUFS;
}
memcpy(cork->opt, opt, sizeof(struct ip_options) + opt->optlen);
cork->flags |= IPCORK_OPT;
cork->addr = ipc->addr;
}
rt = *rtp;
if (unlikely(!rt))
return -EFAULT;
/*
* We steal reference to this route, caller should not release it
*/
*rtp = NULL;
cork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
cork->dst = &rt->dst;
cork->length = 0;
cork->tx_flags = ipc->tx_flags;
cork->page = NULL;
cork->off = 0;
return 0;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,
struct ipcm_cookie *ipc, struct rtable **rtp)
{
struct inet_sock *inet = inet_sk(sk);
struct ip_options_rcu *opt;
struct rtable *rt;
/*
* setup for corking.
*/
opt = ipc->opt;
if (opt) {
if (cork->opt == NULL) {
cork->opt = kmalloc(sizeof(struct ip_options) + 40,
sk->sk_allocation);
if (unlikely(cork->opt == NULL))
return -ENOBUFS;
}
memcpy(cork->opt, &opt->opt, sizeof(struct ip_options) + opt->opt.optlen);
cork->flags |= IPCORK_OPT;
cork->addr = ipc->addr;
}
rt = *rtp;
if (unlikely(!rt))
return -EFAULT;
/*
* We steal reference to this route, caller should not release it
*/
*rtp = NULL;
cork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
cork->dst = &rt->dst;
cork->length = 0;
cork->tx_flags = ipc->tx_flags;
cork->page = NULL;
cork->off = 0;
return 0;
}
| 165,565 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
CWE ID: CWE-416 | INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op = {0};
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
| 169,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
struct mb2_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
| 169,989 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, mc, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
Commit Message: infiniband: fix a possible use-after-free bug
ucma_process_join() will free the new allocated "mc" struct,
if there is any error after that, especially the copy_to_user().
But in parallel, ucma_leave_multicast() could find this "mc"
through idr_find() before ucma_process_join() frees it, since it
is already published.
So "mc" could be used in ucma_leave_multicast() after it is been
allocated and freed in ucma_process_join(), since we don't refcnt
it.
Fix this by separating "publish" from ID allocation, so that we
can get an ID first and publish it later after copy_to_user().
Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support")
Reported-by: Noam Rathaus <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-416 | static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, NULL, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
| 169,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) {
if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) {
MediaBuffer *mBuf;
uint32_t numSamples = 0;
uint64_t curGranulePosition = 0;
while (true) {
status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false);
if (err != OK && err != ERROR_END_OF_STREAM) {
return err;
}
if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) {
break;
}
curGranulePosition = mCurrentPage.mGranulePosition;
numSamples += getNumSamplesInPacket(mBuf);
mBuf->release();
mBuf = NULL;
}
if (curGranulePosition > numSamples) {
mStartGranulePosition = curGranulePosition - numSamples;
} else {
mStartGranulePosition = 0;
}
seekToOffset(0);
}
status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false);
if (err != OK) {
return err;
}
int32_t currentPageSamples;
if ((*out)->meta_data()->findInt32(kKeyValidSamples, ¤tPageSamples)) {
if (mOffset == mFirstDataOffset) {
currentPageSamples -= mStartGranulePosition;
(*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples);
}
mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples;
}
int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition);
(*out)->meta_data()->setInt64(kKeyTime, timeUs);
uint32_t frames = getNumSamplesInPacket(*out);
mCurGranulePosition += frames;
return OK;
}
Commit Message: Fix memory leak in OggExtractor
Test: added a temporal log and run poc
Bug: 63581671
Change-Id: I436a08e54d5e831f9fbdb33c26d15397ce1fbeba
(cherry picked from commit 63079e7c8e12cda4eb124fbe565213d30b9ea34c)
CWE ID: CWE-772 | status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) {
if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) {
MediaBuffer *mBuf;
uint32_t numSamples = 0;
uint64_t curGranulePosition = 0;
while (true) {
status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false);
if (err != OK && err != ERROR_END_OF_STREAM) {
return err;
}
if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) {
if (mBuf != NULL) {
mBuf->release();
mBuf = NULL;
}
break;
}
curGranulePosition = mCurrentPage.mGranulePosition;
numSamples += getNumSamplesInPacket(mBuf);
mBuf->release();
mBuf = NULL;
}
if (curGranulePosition > numSamples) {
mStartGranulePosition = curGranulePosition - numSamples;
} else {
mStartGranulePosition = 0;
}
seekToOffset(0);
}
status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false);
if (err != OK) {
return err;
}
int32_t currentPageSamples;
if ((*out)->meta_data()->findInt32(kKeyValidSamples, ¤tPageSamples)) {
if (mOffset == mFirstDataOffset) {
currentPageSamples -= mStartGranulePosition;
(*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples);
}
mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples;
}
int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition);
(*out)->meta_data()->setInt64(kKeyTime, timeUs);
uint32_t frames = getNumSamplesInPacket(*out);
mCurGranulePosition += frames;
return OK;
}
| 173,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
if (too_many_unix_fds(current))
return -ETOOMANYREFS;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
return max_level;
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
if (too_many_unix_fds(current))
return -ETOOMANYREFS;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->user, scm->fp->fp[i]);
return max_level;
}
| 167,394 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool config_save(const config_t *config, const char *filename) {
assert(config != NULL);
assert(filename != NULL);
assert(*filename != '\0');
char *temp_filename = osi_calloc(strlen(filename) + 5);
if (!temp_filename) {
LOG_ERROR("%s unable to allocate memory for filename.", __func__);
return false;
}
strcpy(temp_filename, filename);
strcat(temp_filename, ".new");
FILE *fp = fopen(temp_filename, "wt");
if (!fp) {
LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) {
const section_t *section = (const section_t *)list_node(node);
fprintf(fp, "[%s]\n", section->name);
for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) {
const entry_t *entry = (const entry_t *)list_node(enode);
fprintf(fp, "%s = %s\n", entry->key, entry->value);
}
if (list_next(node) != list_end(config->sections))
fputc('\n', fp);
}
fflush(fp);
fclose(fp);
if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) {
LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno));
goto error;
}
if (rename(temp_filename, filename) == -1) {
LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno));
goto error;
}
osi_free(temp_filename);
return true;
error:;
unlink(temp_filename);
osi_free(temp_filename);
return false;
}
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 | bool config_save(const config_t *config, const char *filename) {
assert(config != NULL);
assert(filename != NULL);
assert(*filename != '\0');
// Steps to ensure content of config file gets to disk:
//
// 1) Open and write to temp file (e.g. bt_config.conf.new).
// 2) Sync the temp file to disk with fsync().
// 3) Rename temp file to actual config file (e.g. bt_config.conf).
// This ensures atomic update.
// 4) Sync directory that has the conf file with fsync().
// This ensures directory entries are up-to-date.
int dir_fd = -1;
FILE *fp = NULL;
// Build temp config file based on config file (e.g. bt_config.conf.new).
static const char *temp_file_ext = ".new";
const int filename_len = strlen(filename);
const int temp_filename_len = filename_len + strlen(temp_file_ext) + 1;
char *temp_filename = osi_calloc(temp_filename_len);
snprintf(temp_filename, temp_filename_len, "%s%s", filename, temp_file_ext);
// Extract directory from file path (e.g. /data/misc/bluedroid).
char *temp_dirname = osi_strdup(filename);
const char *directoryname = dirname(temp_dirname);
if (!directoryname) {
LOG_ERROR("%s error extracting directory from '%s': %s", __func__, filename, strerror(errno));
goto error;
}
dir_fd = TEMP_FAILURE_RETRY(open(directoryname, O_RDONLY));
if (dir_fd < 0) {
LOG_ERROR("%s unable to open dir '%s': %s", __func__, directoryname, strerror(errno));
goto error;
}
fp = fopen(temp_filename, "wt");
if (!fp) {
LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) {
const section_t *section = (const section_t *)list_node(node);
if (fprintf(fp, "[%s]\n", section->name) < 0) {
LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) {
const entry_t *entry = (const entry_t *)list_node(enode);
if (fprintf(fp, "%s = %s\n", entry->key, entry->value) < 0) {
LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
}
if (list_next(node) != list_end(config->sections)) {
if (fputc('\n', fp) == EOF) {
LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
}
}
// Sync written temp file out to disk. fsync() is blocking until data makes it to disk.
if (fsync(fileno(fp)) < 0) {
LOG_WARN("%s unable to fsync file '%s': %s", __func__, temp_filename, strerror(errno));
}
if (fclose(fp) == EOF) {
LOG_ERROR("%s unable to close file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
fp = NULL;
if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) {
LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno));
goto error;
}
// Rename written temp file to the actual config file.
if (rename(temp_filename, filename) == -1) {
LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno));
goto error;
}
// This should ensure the directory is updated as well.
if (fsync(dir_fd) < 0) {
LOG_WARN("%s unable to fsync dir '%s': %s", __func__, directoryname, strerror(errno));
}
if (close(dir_fd) < 0) {
LOG_ERROR("%s unable to close dir '%s': %s", __func__, directoryname, strerror(errno));
goto error;
}
osi_free(temp_filename);
osi_free(temp_dirname);
return true;
error:
// This indicates there is a write issue. Unlink as partial data is not acceptable.
unlink(temp_filename);
if (fp)
fclose(fp);
if (dir_fd != -1)
close(dir_fd);
osi_free(temp_filename);
osi_free(temp_dirname);
return false;
}
| 173,479 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
{
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,
const char *str2, u_int l2)
{
if (!ND_TTEST2(*str2, tl1)) {
/*
* We don't have tl1 bytes worth of captured data
* for the string, so we can't check for this
* string.
*/
return 0;
}
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
| 167,885 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InputDispatcher::enqueueDispatchEntryLocked(
const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
int32_t dispatchMode) {
int32_t inputTargetFlags = inputTarget->flags;
if (!(inputTargetFlags & dispatchMode)) {
return;
}
inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
inputTarget->scaleFactor);
switch (eventEntry->type) {
case EventEntry::TYPE_KEY: {
KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
dispatchEntry->resolvedAction = keyEntry->action;
dispatchEntry->resolvedFlags = keyEntry->flags;
if (!connection->inputState.trackKey(keyEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
case EventEntry::TYPE_MOTION: {
MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
} else {
dispatchEntry->resolvedAction = motionEntry->action;
}
if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
&& !connection->inputState.isHovering(
motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
connection->getInputChannelName());
#endif
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
}
dispatchEntry->resolvedFlags = motionEntry->flags;
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
}
if (!connection->inputState.trackMotion(motionEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
}
if (dispatchEntry->hasForegroundTarget()) {
incrementPendingForegroundDispatchesLocked(eventEntry);
}
connection->outboundQueue.enqueueAtTail(dispatchEntry);
traceOutboundQueueLengthLocked(connection);
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
CWE ID: CWE-264 | void InputDispatcher::enqueueDispatchEntryLocked(
const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
int32_t dispatchMode) {
int32_t inputTargetFlags = inputTarget->flags;
if (!(inputTargetFlags & dispatchMode)) {
return;
}
inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
inputTarget->scaleFactor);
switch (eventEntry->type) {
case EventEntry::TYPE_KEY: {
KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
dispatchEntry->resolvedAction = keyEntry->action;
dispatchEntry->resolvedFlags = keyEntry->flags;
if (!connection->inputState.trackKey(keyEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
case EventEntry::TYPE_MOTION: {
MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
} else {
dispatchEntry->resolvedAction = motionEntry->action;
}
if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
&& !connection->inputState.isHovering(
motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
connection->getInputChannelName());
#endif
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
}
dispatchEntry->resolvedFlags = motionEntry->flags;
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
}
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
}
if (!connection->inputState.trackMotion(motionEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
}
if (dispatchEntry->hasForegroundTarget()) {
incrementPendingForegroundDispatchesLocked(eventEntry);
}
connection->outboundQueue.enqueueAtTail(dispatchEntry);
traceOutboundQueueLengthLocked(connection);
}
| 174,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: vrrp_print_stats(void)
{
FILE *file;
file = fopen (stats_file, "w");
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
stats_file, errno, strerror(errno));
return;
}
list l = vrrp_data->vrrp;
element e;
vrrp_t *vrrp;
for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) {
vrrp = ELEMENT_DATA(e);
fprintf(file, "VRRP Instance: %s\n", vrrp->iname);
fprintf(file, " Advertisements:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->advert_rcvd);
fprintf(file, " Sent: %d\n", vrrp->stats->advert_sent);
fprintf(file, " Became master: %d\n", vrrp->stats->become_master);
fprintf(file, " Released master: %d\n",
vrrp->stats->release_master);
fprintf(file, " Packet Errors:\n");
fprintf(file, " Length: %" PRIu64 "\n", vrrp->stats->packet_len_err);
fprintf(file, " TTL: %" PRIu64 "\n", vrrp->stats->ip_ttl_err);
fprintf(file, " Invalid Type: %" PRIu64 "\n",
vrrp->stats->invalid_type_rcvd);
fprintf(file, " Advertisement Interval: %" PRIu64 "\n",
vrrp->stats->advert_interval_err);
fprintf(file, " Address List: %" PRIu64 "\n",
vrrp->stats->addr_list_err);
fprintf(file, " Authentication Errors:\n");
fprintf(file, " Invalid Type: %d\n",
vrrp->stats->invalid_authtype);
#ifdef _WITH_VRRP_AUTH_
fprintf(file, " Type Mismatch: %d\n",
vrrp->stats->authtype_mismatch);
fprintf(file, " Failure: %d\n",
vrrp->stats->auth_failure);
#endif
fprintf(file, " Priority Zero:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->pri_zero_rcvd);
fprintf(file, " Sent: %" PRIu64 "\n", vrrp->stats->pri_zero_sent);
}
fclose(file);
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | vrrp_print_stats(void)
{
FILE *file = fopen_safe(stats_file, "w");
element e;
vrrp_t *vrrp;
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
stats_file, errno, strerror(errno));
return;
}
LIST_FOREACH(vrrp_data->vrrp, vrrp, e) {
fprintf(file, "VRRP Instance: %s\n", vrrp->iname);
fprintf(file, " Advertisements:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->advert_rcvd);
fprintf(file, " Sent: %d\n", vrrp->stats->advert_sent);
fprintf(file, " Became master: %d\n", vrrp->stats->become_master);
fprintf(file, " Released master: %d\n", vrrp->stats->release_master);
fprintf(file, " Packet Errors:\n");
fprintf(file, " Length: %" PRIu64 "\n", vrrp->stats->packet_len_err);
fprintf(file, " TTL: %" PRIu64 "\n", vrrp->stats->ip_ttl_err);
fprintf(file, " Invalid Type: %" PRIu64 "\n",
vrrp->stats->invalid_type_rcvd);
fprintf(file, " Advertisement Interval: %" PRIu64 "\n",
vrrp->stats->advert_interval_err);
fprintf(file, " Address List: %" PRIu64 "\n",
vrrp->stats->addr_list_err);
fprintf(file, " Authentication Errors:\n");
fprintf(file, " Invalid Type: %d\n",
vrrp->stats->invalid_authtype);
#ifdef _WITH_VRRP_AUTH_
fprintf(file, " Type Mismatch: %d\n",
vrrp->stats->authtype_mismatch);
fprintf(file, " Failure: %d\n",
vrrp->stats->auth_failure);
#endif
fprintf(file, " Priority Zero:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->pri_zero_rcvd);
fprintf(file, " Sent: %" PRIu64 "\n", vrrp->stats->pri_zero_sent);
}
fclose(file);
}
| 168,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
if (!name)
return ERR_PTR(-ENOENT);
mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
type &= mask;
alg = crypto_alg_lookup(name, type, mask);
if (!alg) {
request_module("%s", name);
if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
CRYPTO_ALG_NEED_FALLBACK))
request_module("%s-all", name);
alg = crypto_alg_lookup(name, type, mask);
}
if (alg)
return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg;
return crypto_larval_add(name, type, mask);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264 | struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
if (!name)
return ERR_PTR(-ENOENT);
mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
type &= mask;
alg = crypto_alg_lookup(name, type, mask);
if (!alg) {
request_module("crypto-%s", name);
if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
CRYPTO_ALG_NEED_FALLBACK))
request_module("crypto-%s-all", name);
alg = crypto_alg_lookup(name, type, mask);
}
if (alg)
return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg;
return crypto_larval_add(name, type, mask);
}
| 166,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void 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 <[email protected]>
Commit-Queue: Sorin Jianu <[email protected]>
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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int send_full_color_rect(VncState *vs, int x, int y, int w, int h)
{
int stream = 0;
ssize_t bytes;
#ifdef CONFIG_VNC_PNG
if (tight_can_send_png_rect(vs, w, h)) {
return send_png_rect(vs, x, y, w, h, NULL);
}
#endif
tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset);
bytes = 3;
} else {
bytes = vs->clientds.pf.bytes_per_pixel;
}
Commit Message:
CWE ID: CWE-125 | static int send_full_color_rect(VncState *vs, int x, int y, int w, int h)
{
int stream = 0;
ssize_t bytes;
#ifdef CONFIG_VNC_PNG
if (tight_can_send_png_rect(vs, w, h)) {
return send_png_rect(vs, x, y, w, h, NULL);
}
#endif
tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset);
bytes = 3;
} else {
bytes = vs->client_pf.bytes_per_pixel;
}
| 165,461 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ChromeGeolocationPermissionContext::ChromeGeolocationPermissionContext(
Profile* profile)
: profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(geolocation_infobar_queue_controller_(
new GeolocationInfoBarQueueController(
base::Bind(
&ChromeGeolocationPermissionContext::NotifyPermissionSet,
this),
profile))) {
}
Commit Message: Don't retain reference to ChromeGeolocationPermissionContext
ChromeGeolocationPermissionContext owns
GeolocationInfoBarQueueController, so make sure that the callback
passed to GeolocationInfoBarQueueController doesn't increase the
reference count on ChromeGeolocationPermissionContext (which
https://chromiumcodereview.appspot.com/11072012 accidentally does).
TBR=bulach
BUG=152921
TEST=unittest:chrome_geolocation_permission_context on memory.fyi bot
Review URL: https://chromiumcodereview.appspot.com/11087030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@160881 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | ChromeGeolocationPermissionContext::ChromeGeolocationPermissionContext(
Profile* profile)
: profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(geolocation_infobar_queue_controller_(
new GeolocationInfoBarQueueController(
base::Bind(
&ChromeGeolocationPermissionContext::NotifyPermissionSet,
base::Unretained(this)),
profile))) {
}
| 171,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nfs_readlink_reply(unsigned char *pkt, unsigned len)
{
uint32_t *data;
char *path;
int rlen;
int ret;
ret = rpc_check_reply(pkt, 1);
if (ret)
return ret;
data = (uint32_t *)(pkt + sizeof(struct rpc_reply));
data++;
rlen = ntohl(net_read_uint32(data)); /* new path length */
data++;
path = (char *)data;
} else {
memcpy(nfs_path, path, rlen);
nfs_path[rlen] = 0;
}
Commit Message:
CWE ID: CWE-119 | static int nfs_readlink_reply(unsigned char *pkt, unsigned len)
{
uint32_t *data;
char *path;
unsigned int rlen;
int ret;
ret = rpc_check_reply(pkt, 1);
if (ret)
return ret;
data = (uint32_t *)(pkt + sizeof(struct rpc_reply));
data++;
rlen = ntohl(net_read_uint32(data)); /* new path length */
rlen = max_t(unsigned int, rlen,
len - sizeof(struct rpc_reply) - sizeof(uint32_t));
data++;
path = (char *)data;
} else {
memcpy(nfs_path, path, rlen);
nfs_path[rlen] = 0;
}
| 164,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh,
bool source_is_modifiable) {
DCHECK(print_preview_rfh_);
if (rfh != print_preview_rfh_)
return;
PrintPreviewDialogController* dialog_controller =
PrintPreviewDialogController::GetInstance();
if (!dialog_controller) {
PrintPreviewDone();
return;
}
dialog_controller->PrintPreview(web_contents());
PrintHostMsg_RequestPrintPreview_Params params;
params.is_modifiable = source_is_modifiable;
PrintPreviewUI::SetInitialParams(
dialog_controller->GetPrintPreviewForContents(web_contents()), params);
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh,
bool source_is_modifiable) {
DCHECK(print_preview_rfh_);
if (rfh != print_preview_rfh_)
return;
PrintPreviewDialogController* dialog_controller =
PrintPreviewDialogController::GetInstance();
if (!dialog_controller) {
PrintPreviewDone();
return;
}
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (web_contents()->IsFullscreenForCurrentTab())
web_contents()->ExitFullscreen(true);
dialog_controller->PrintPreview(web_contents());
PrintHostMsg_RequestPrintPreview_Params params;
params.is_modifiable = source_is_modifiable;
PrintPreviewUI::SetInitialParams(
dialog_controller->GetPrintPreviewForContents(web_contents()), params);
}
| 172,314 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL("about:swappedout"))
return WebKit::WebNavigationPolicyIgnore;
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
if (!frame->parent() && is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
request.httpMethod() == "GET" && !url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
bool should_fork =
(enabled_bindings_ & content::BINDINGS_POLICY_WEB_UI) ||
frame->isViewSourceModeEnabled() ||
url.SchemeIs(chrome::kViewSourceScheme);
if (!should_fork) {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL("about:swappedout"))
return WebKit::WebNavigationPolicyIgnore;
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
// top-level navigations (not iframes). But we sometimes navigate to
// about:blank to clear a tab, and we want to still allow that.
// Note: this is known to break POST submissions when crossing process
// boundaries until http://crbug.com/101395 is fixed. This is better for
// security than loading a WebUI, extension or app page in the wrong process.
// POST requests don't work because this mechanism does not preserve form
// POST data. We will need to send the request's httpBody data up to the
// browser process, and issue a special POST navigation in WebKit (via
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
// All navigations to WebUI URLs or within WebUI-enabled RenderProcesses
// must be handled by the browser process so that the correct bindings and
// data sources can be registered.
// Similarly, navigations to view-source URLs or within ViewSource mode
// must be handled by the browser process.
int cumulative_bindings =
RenderProcess::current()->GetEnabledBindings();
bool should_fork =
content::GetContentClient()->HasWebUIScheme(url) ||
(cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
frame->isViewSourceModeEnabled();
if (!should_fork) {
// For now, we skip this for POST submissions. This is because
// http://crbug.com/101395 is more likely to cause compatibility issues
// with hosted apps and extensions than WebUI pages. We will remove this
// check when cross-process POST submissions are supported.
if (request.httpMethod() == "GET") {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
| 171,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < ETH_MAX_L2_HDR_LEN) {
l2_hdr->iov_len = 0;
return false;
} else {
l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base);
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
l2_hdr->iov_len + sizeof(struct ip_header),
l3_hdr->iov_base + sizeof(struct ip_header),
l3_hdr->iov_len - sizeof(struct ip_header));
if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
Commit Message:
CWE ID: CWE-20 | static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < sizeof(struct eth_header)) {
l2_hdr->iov_len = 0;
return false;
}
l2_hdr->iov_len = sizeof(struct eth_header);
switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
case ETH_P_VLAN:
l2_hdr->iov_len += sizeof(struct vlan_header);
break;
case ETH_P_DVLAN:
l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
break;
}
if (bytes_read < l2_hdr->iov_len) {
l2_hdr->iov_len = 0;
return false;
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
l2_hdr->iov_len + sizeof(struct ip_header),
l3_hdr->iov_base + sizeof(struct ip_header),
l3_hdr->iov_len - sizeof(struct ip_header));
if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
| 165,277 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kLightShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
| 171,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
Commit Message: bridge: netfilter: fix information leak
Struct tmp is copied from userspace. It is not checked whether the "name"
field is NULL terminated. This may lead to buffer overflow and passing
contents of kernel stack as a module name to try_then_request_module() and,
consequently, to modprobe commandline. It would be seen by all userspace
processes.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Patrick McHardy <[email protected]>
CWE ID: CWE-20 | static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
tmp.name[sizeof(tmp.name) - 1] = 0;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
| 165,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int tpm_open(struct inode *inode, struct file *file)
{
int minor = iminor(inode);
struct tpm_chip *chip = NULL, *pos;
rcu_read_lock();
list_for_each_entry_rcu(pos, &tpm_chip_list, list) {
if (pos->vendor.miscdev.minor == minor) {
chip = pos;
get_device(chip->dev);
break;
}
}
rcu_read_unlock();
if (!chip)
return -ENODEV;
if (test_and_set_bit(0, &chip->is_open)) {
dev_dbg(chip->dev, "Another process owns this TPM\n");
put_device(chip->dev);
return -EBUSY;
}
chip->data_buffer = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL);
if (chip->data_buffer == NULL) {
clear_bit(0, &chip->is_open);
put_device(chip->dev);
return -ENOMEM;
}
atomic_set(&chip->data_pending, 0);
file->private_data = chip;
return 0;
}
Commit Message: char/tpm: Fix unitialized usage of data buffer
This patch fixes information leakage to the userspace by initializing
the data buffer to zero.
Reported-by: Peter Huewe <[email protected]>
Signed-off-by: Peter Huewe <[email protected]>
Signed-off-by: Marcel Selhorst <[email protected]>
[ Also removed the silly "* sizeof(u8)". If that isn't 1, we have way
deeper problems than a simple multiplication can fix. - Linus ]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | int tpm_open(struct inode *inode, struct file *file)
{
int minor = iminor(inode);
struct tpm_chip *chip = NULL, *pos;
rcu_read_lock();
list_for_each_entry_rcu(pos, &tpm_chip_list, list) {
if (pos->vendor.miscdev.minor == minor) {
chip = pos;
get_device(chip->dev);
break;
}
}
rcu_read_unlock();
if (!chip)
return -ENODEV;
if (test_and_set_bit(0, &chip->is_open)) {
dev_dbg(chip->dev, "Another process owns this TPM\n");
put_device(chip->dev);
return -EBUSY;
}
chip->data_buffer = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
if (chip->data_buffer == NULL) {
clear_bit(0, &chip->is_open);
put_device(chip->dev);
return -ENOMEM;
}
atomic_set(&chip->data_pending, 0);
file->private_data = chip;
return 0;
}
| 165,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LocalFileSystem::fileSystemNotAvailable(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
PassRefPtr<CallbackWrapper> callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
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 | void LocalFileSystem::fileSystemNotAvailable(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
CallbackWrapper* callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
| 171,428 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
Commit Message:
CWE ID: CWE-200 | xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options &= ~XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
| 164,725 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: double AffineTransform::xScale() const
{
return sqrt(m_transform[0] * m_transform[0] + m_transform[1] * m_transform[1]);
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID: | double AffineTransform::xScale() const
{
return sqrt(xScaleSquared());
}
double AffineTransform::yScaleSquared() const
{
return m_transform[2] * m_transform[2] + m_transform[3] * m_transform[3];
}
| 171,669 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)
{
zval **login, **password;
zval **login, **password;
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS &&
!zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) {
unsigned char* buf;
int len;
smart_str auth = {0};
smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));
smart_str_appendc(&auth, ':');
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS) {
smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));
}
smart_str_0(&auth);
efree(buf);
smart_str_free(&auth);
return 1;
}
return 0;
}
Commit Message:
CWE ID: | int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)
{
zval **login, **password;
zval **login, **password;
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS &&
Z_TYPE_PP(login) == IS_STRING &&
!zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) {
unsigned char* buf;
int len;
smart_str auth = {0};
smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));
smart_str_appendc(&auth, ':');
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS &&
Z_TYPE_PP(password) == IS_STRING) {
smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));
}
smart_str_0(&auth);
efree(buf);
smart_str_free(&auth);
return 1;
}
return 0;
}
| 165,304 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
#ifndef _MSC_VER
char fpath[grub_strlen (currpath) + 1];
#else
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
#endif
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno)
return grub_errno;
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
return 0;
}
name = next;
}
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119 | find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
free (fpath);
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
free (fpath);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno) {
free (fpath);
return grub_errno;
}
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
free (fpath);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
free (fpath);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
free (fpath);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
free (fpath);
return 0;
}
name = next;
}
free (fpath);
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
| 168,089 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void markPointer(Visitor* visitor, HeapObjectHeader* header) {
ASSERT(header->checkHeader());
const GCInfo* gcInfo = ThreadHeap::gcInfo(header->gcInfoIndex());
if (gcInfo->hasVTable() && !vTableInitialized(header->payload())) {
visitor->markHeaderNoTracing(header);
ASSERT(isUninitializedMemory(header->payload(), header->payloadSize()));
} else {
visitor->markHeader(header, gcInfo->m_trace);
}
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | static void markPointer(Visitor* visitor, HeapObjectHeader* header) {
header->checkHeader();
const GCInfo* gcInfo = ThreadHeap::gcInfo(header->gcInfoIndex());
if (gcInfo->hasVTable() && !vTableInitialized(header->payload())) {
visitor->markHeaderNoTracing(header);
ASSERT(isUninitializedMemory(header->payload(), header->payloadSize()));
} else {
visitor->markHeader(header, gcInfo->m_trace);
}
}
| 172,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_HELP:
default:
usage();
break;
}
}
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
numcmpts = jas_image_numcmpts(image);
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
Commit Message: Fixed a sanitizer failure in the BMP codec.
Also, added a --debug-level command line option to the imginfo command
for debugging purposes.
CWE ID: CWE-476 | int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
numcmpts = jas_image_numcmpts(image);
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
| 168,761 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SocketStream::SocketStream(const GURL& url, Delegate* delegate)
: delegate_(delegate),
url_(url),
max_pending_send_allowed_(kMaxPendingSendAllowed),
next_state_(STATE_NONE),
factory_(ClientSocketFactory::GetDefaultFactory()),
proxy_mode_(kDirectConnection),
proxy_url_(url),
pac_request_(NULL),
privacy_mode_(kPrivacyModeDisabled),
io_callback_(base::Bind(&SocketStream::OnIOCompleted,
base::Unretained(this))),
read_buf_(NULL),
current_write_buf_(NULL),
waiting_for_write_completion_(false),
closing_(false),
server_closed_(false),
metrics_(new SocketStreamMetrics(url)) {
DCHECK(base::MessageLoop::current())
<< "The current base::MessageLoop must exist";
DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
<< "The current base::MessageLoop must be TYPE_IO";
DCHECK(delegate_);
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | SocketStream::SocketStream(const GURL& url, Delegate* delegate)
: delegate_(delegate),
url_(url),
max_pending_send_allowed_(kMaxPendingSendAllowed),
context_(NULL),
next_state_(STATE_NONE),
factory_(ClientSocketFactory::GetDefaultFactory()),
proxy_mode_(kDirectConnection),
proxy_url_(url),
pac_request_(NULL),
privacy_mode_(kPrivacyModeDisabled),
io_callback_(base::Bind(&SocketStream::OnIOCompleted,
base::Unretained(this))),
read_buf_(NULL),
current_write_buf_(NULL),
waiting_for_write_completion_(false),
closing_(false),
server_closed_(false),
metrics_(new SocketStreamMetrics(url)) {
DCHECK(base::MessageLoop::current())
<< "The current base::MessageLoop must exist";
DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
<< "The current base::MessageLoop must be TYPE_IO";
DCHECK(delegate_);
}
| 171,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _XcursorReadImage (XcursorFile *file,
XcursorFileHeader *fileHeader,
int toc)
{
XcursorChunkHeader chunkHeader;
XcursorImage head;
XcursorImage *image;
int n;
XcursorPixel *p;
if (!file || !fileHeader)
return NULL;
if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader))
return NULL;
if (!_XcursorReadUInt (file, &head.width))
return NULL;
if (!_XcursorReadUInt (file, &head.height))
return NULL;
if (!_XcursorReadUInt (file, &head.xhot))
return NULL;
if (!_XcursorReadUInt (file, &head.yhot))
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width >= 0x10000 || head.height > 0x10000)
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width >= 0x10000 || head.height > 0x10000)
return NULL;
if (head.width == 0 || head.height == 0)
return NULL;
return NULL;
if (chunkHeader.version < image->version)
image->version = chunkHeader.version;
image->size = chunkHeader.subtype;
image->xhot = head.xhot;
image->yhot = head.yhot;
image->delay = head.delay;
n = image->width * image->height;
p = image->pixels;
while (n--)
{
if (!_XcursorReadUInt (file, p))
{
XcursorImageDestroy (image);
return NULL;
}
p++;
}
return image;
}
Commit Message:
CWE ID: CWE-190 | _XcursorReadImage (XcursorFile *file,
XcursorFileHeader *fileHeader,
int toc)
{
XcursorChunkHeader chunkHeader;
XcursorImage head;
XcursorImage *image;
int n;
XcursorPixel *p;
if (!file || !fileHeader)
return NULL;
if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader))
return NULL;
if (!_XcursorReadUInt (file, &head.width))
return NULL;
if (!_XcursorReadUInt (file, &head.height))
return NULL;
if (!_XcursorReadUInt (file, &head.xhot))
return NULL;
if (!_XcursorReadUInt (file, &head.yhot))
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width >= 0x10000 || head.height > 0x10000)
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width > XCURSOR_IMAGE_MAX_SIZE ||
head.height > XCURSOR_IMAGE_MAX_SIZE)
return NULL;
if (head.width == 0 || head.height == 0)
return NULL;
return NULL;
if (chunkHeader.version < image->version)
image->version = chunkHeader.version;
image->size = chunkHeader.subtype;
image->xhot = head.xhot;
image->yhot = head.yhot;
image->delay = head.delay;
n = image->width * image->height;
p = image->pixels;
while (n--)
{
if (!_XcursorReadUInt (file, p))
{
XcursorImageDestroy (image);
return NULL;
}
p++;
}
return image;
}
| 164,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppControllerImpl::LaunchApp(const std::string& app_id) {
app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE,
apps::mojom::LaunchSource::kFromAppListGrid,
display::kDefaultDisplayId);
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void AppControllerImpl::LaunchApp(const std::string& app_id) {
void AppControllerService::LaunchApp(const std::string& app_id) {
app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE,
apps::mojom::LaunchSource::kFromAppListGrid,
display::kDefaultDisplayId);
}
| 172,084 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_decrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_decrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC);
}
| 167,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NavigatorImpl::NavigateToEntry(
FrameTreeNode* frame_tree_node,
const FrameNavigationEntry& frame_entry,
const NavigationEntryImpl& entry,
ReloadType reload_type,
bool is_same_document_history_load,
bool is_history_navigation_in_new_child,
bool is_pending_entry,
const scoped_refptr<ResourceRequestBodyImpl>& post_body) {
TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
GURL dest_url = frame_entry.url();
Referrer dest_referrer = frame_entry.referrer();
if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
dest_url = entry.GetOriginalRequestURL();
dest_referrer = Referrer();
}
if (!dest_url.is_valid() && !dest_url.is_empty()) {
LOG(WARNING) << "Refusing to load invalid URL: "
<< dest_url.possibly_invalid_spec();
return false;
}
if (dest_url.spec().size() > url::kMaxURLChars) {
LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
<< " characters.";
return false;
}
base::TimeTicks navigation_start = base::TimeTicks::Now();
TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
"navigation,rail", "NavigationTiming navigationStart",
TRACE_EVENT_SCOPE_GLOBAL, navigation_start);
LoFiState lofi_state = LOFI_UNSPECIFIED;
if (!frame_tree_node->IsMainFrame()) {
lofi_state = frame_tree_node->frame_tree()
->root()
->current_frame_host()
->last_navigation_lofi_state();
} else if (reload_type == ReloadType::DISABLE_LOFI_MODE) {
lofi_state = LOFI_OFF;
}
if (IsBrowserSideNavigationEnabled()) {
navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
entry.restore_type()));
RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
entry, reload_type, lofi_state,
is_same_document_history_load,
is_history_navigation_in_new_child, navigation_start);
if (frame_tree_node->IsMainFrame() &&
frame_tree_node->navigation_request()) {
TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1(
"navigation", "Navigation timeToNetworkStack",
frame_tree_node->navigation_request()->navigation_handle(),
navigation_start,
"FrameTreeNode id", frame_tree_node->frame_tree_node_id());
}
} else {
RenderFrameHostImpl* dest_render_frame_host =
frame_tree_node->render_manager()->Navigate(
dest_url, frame_entry, entry, reload_type != ReloadType::NONE);
if (!dest_render_frame_host)
return false; // Unable to create the desired RenderFrameHost.
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);
bool is_transfer = entry.transferred_global_request_id().child_id != -1;
if (is_transfer)
dest_render_frame_host->set_is_loading(true);
if (is_pending_entry && controller_->GetPendingEntryIndex() != -1)
DCHECK(frame_entry.page_state().IsValid());
bool is_transfer_to_same =
is_transfer &&
entry.transferred_global_request_id().child_id ==
dest_render_frame_host->GetProcess()->GetID();
if (!is_transfer_to_same) {
navigation_data_.reset(new NavigationMetricsData(
navigation_start, dest_url, entry.restore_type()));
FrameMsg_Navigate_Type::Value navigation_type = GetNavigationType(
controller_->GetBrowserContext(), entry, reload_type);
dest_render_frame_host->Navigate(
entry.ConstructCommonNavigationParams(
frame_entry, post_body, dest_url, dest_referrer, navigation_type,
lofi_state, navigation_start),
entry.ConstructStartNavigationParams(),
entry.ConstructRequestNavigationParams(
frame_entry, is_same_document_history_load,
is_history_navigation_in_new_child,
entry.GetSubframeUniqueNames(frame_tree_node),
frame_tree_node->has_committed_real_load(),
controller_->GetPendingEntryIndex() == -1,
controller_->GetIndexOfEntry(&entry),
controller_->GetLastCommittedEntryIndex(),
controller_->GetEntryCount()));
}
}
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
if (controller_->GetPendingEntryIndex() == -1 &&
dest_url.SchemeIs(url::kJavaScriptScheme)) {
return false;
}
if (delegate_ && is_pending_entry)
delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
return true;
}
Commit Message: Drop navigations to NavigationEntry with invalid virtual URLs.
BUG=657720
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2452443002
Cr-Commit-Position: refs/heads/master@{#428056}
CWE ID: CWE-20 | bool NavigatorImpl::NavigateToEntry(
FrameTreeNode* frame_tree_node,
const FrameNavigationEntry& frame_entry,
const NavigationEntryImpl& entry,
ReloadType reload_type,
bool is_same_document_history_load,
bool is_history_navigation_in_new_child,
bool is_pending_entry,
const scoped_refptr<ResourceRequestBodyImpl>& post_body) {
TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
GURL dest_url = frame_entry.url();
Referrer dest_referrer = frame_entry.referrer();
if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
dest_url = entry.GetOriginalRequestURL();
dest_referrer = Referrer();
}
// Don't attempt to navigate if the virtual URL is non-empty and invalid.
if (frame_tree_node->IsMainFrame()) {
const GURL& virtual_url = entry.GetVirtualURL();
if (!virtual_url.is_valid() && !virtual_url.is_empty()) {
LOG(WARNING) << "Refusing to load for invalid virtual URL: "
<< virtual_url.possibly_invalid_spec();
return false;
}
}
if (!dest_url.is_valid() && !dest_url.is_empty()) {
LOG(WARNING) << "Refusing to load invalid URL: "
<< dest_url.possibly_invalid_spec();
return false;
}
if (dest_url.spec().size() > url::kMaxURLChars) {
LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
<< " characters.";
return false;
}
base::TimeTicks navigation_start = base::TimeTicks::Now();
TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
"navigation,rail", "NavigationTiming navigationStart",
TRACE_EVENT_SCOPE_GLOBAL, navigation_start);
LoFiState lofi_state = LOFI_UNSPECIFIED;
if (!frame_tree_node->IsMainFrame()) {
lofi_state = frame_tree_node->frame_tree()
->root()
->current_frame_host()
->last_navigation_lofi_state();
} else if (reload_type == ReloadType::DISABLE_LOFI_MODE) {
lofi_state = LOFI_OFF;
}
if (IsBrowserSideNavigationEnabled()) {
navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
entry.restore_type()));
RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
entry, reload_type, lofi_state,
is_same_document_history_load,
is_history_navigation_in_new_child, navigation_start);
if (frame_tree_node->IsMainFrame() &&
frame_tree_node->navigation_request()) {
TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1(
"navigation", "Navigation timeToNetworkStack",
frame_tree_node->navigation_request()->navigation_handle(),
navigation_start,
"FrameTreeNode id", frame_tree_node->frame_tree_node_id());
}
} else {
RenderFrameHostImpl* dest_render_frame_host =
frame_tree_node->render_manager()->Navigate(
dest_url, frame_entry, entry, reload_type != ReloadType::NONE);
if (!dest_render_frame_host)
return false; // Unable to create the desired RenderFrameHost.
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);
bool is_transfer = entry.transferred_global_request_id().child_id != -1;
if (is_transfer)
dest_render_frame_host->set_is_loading(true);
if (is_pending_entry && controller_->GetPendingEntryIndex() != -1)
DCHECK(frame_entry.page_state().IsValid());
bool is_transfer_to_same =
is_transfer &&
entry.transferred_global_request_id().child_id ==
dest_render_frame_host->GetProcess()->GetID();
if (!is_transfer_to_same) {
navigation_data_.reset(new NavigationMetricsData(
navigation_start, dest_url, entry.restore_type()));
FrameMsg_Navigate_Type::Value navigation_type = GetNavigationType(
controller_->GetBrowserContext(), entry, reload_type);
dest_render_frame_host->Navigate(
entry.ConstructCommonNavigationParams(
frame_entry, post_body, dest_url, dest_referrer, navigation_type,
lofi_state, navigation_start),
entry.ConstructStartNavigationParams(),
entry.ConstructRequestNavigationParams(
frame_entry, is_same_document_history_load,
is_history_navigation_in_new_child,
entry.GetSubframeUniqueNames(frame_tree_node),
frame_tree_node->has_committed_real_load(),
controller_->GetPendingEntryIndex() == -1,
controller_->GetIndexOfEntry(&entry),
controller_->GetLastCommittedEntryIndex(),
controller_->GetEntryCount()));
}
}
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
if (controller_->GetPendingEntryIndex() == -1 &&
dest_url.SchemeIs(url::kJavaScriptScheme)) {
return false;
}
if (delegate_ && is_pending_entry)
delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
return true;
}
| 172,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostViewAura::AcceleratedSurfaceRelease(
uint64 surface_handle) {
DCHECK(image_transport_clients_.find(surface_handle) !=
image_transport_clients_.end());
if (current_surface_ == surface_handle) {
current_surface_ = 0;
UpdateExternalTexture();
}
image_transport_clients_.erase(surface_handle);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostViewAura::AcceleratedSurfaceRelease(
void RenderWidgetHostViewAura::AcceleratedSurfaceRelease() {
// This really tells us to release the frontbuffer.
if (current_surface_ && ShouldReleaseFrontSurface()) {
ui::Compositor* compositor = GetCompositor();
if (compositor) {
// We need to wait for a commit to clear to guarantee that all we
// will not issue any more GL referencing the previous surface.
can_lock_compositor_ = NO_PENDING_COMMIT;
scoped_refptr<ui::Texture> surface_ref =
image_transport_clients_[current_surface_];
on_compositing_did_commit_callbacks_.push_back(
base::Bind(&RenderWidgetHostViewAura::
SetSurfaceNotInUseByCompositor,
AsWeakPtr(),
surface_ref));
if (!compositor->HasObserver(this))
compositor->AddObserver(this);
}
image_transport_clients_.erase(current_surface_);
current_surface_ = 0;
UpdateExternalTexture();
}
}
| 171,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dccp_error(struct net *net, struct nf_conn *tmpl,
struct sk_buff *skb, unsigned int dataoff,
enum ip_conntrack_info *ctinfo,
u_int8_t pf, unsigned int hooknum)
{
struct dccp_hdr _dh, *dh;
unsigned int dccp_len = skb->len - dataoff;
unsigned int cscov;
const char *msg;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
if (dh == NULL) {
msg = "nf_ct_dccp: short packet ";
goto out_invalid;
}
if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) ||
dh->dccph_doff * 4 > dccp_len) {
msg = "nf_ct_dccp: truncated/malformed packet ";
goto out_invalid;
}
cscov = dccp_len;
if (dh->dccph_cscov) {
cscov = (dh->dccph_cscov - 1) * 4;
if (cscov > dccp_len) {
msg = "nf_ct_dccp: bad checksum coverage ";
goto out_invalid;
}
}
if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP,
pf)) {
msg = "nf_ct_dccp: bad checksum ";
goto out_invalid;
}
if (dh->dccph_type >= DCCP_PKT_INVALID) {
msg = "nf_ct_dccp: reserved packet type ";
goto out_invalid;
}
return NF_ACCEPT;
out_invalid:
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg);
return -NF_ACCEPT;
}
Commit Message: netfilter: nf_conntrack_dccp: fix skb_header_pointer API usages
Some occurences in the netfilter tree use skb_header_pointer() in
the following way ...
struct dccp_hdr _dh, *dh;
...
skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
... where dh itself is a pointer that is being passed as the copy
buffer. Instead, we need to use &_dh as the forth argument so that
we're copying the data into an actual buffer that sits on the stack.
Currently, we probably could overwrite memory on the stack (e.g.
with a possibly mal-formed DCCP packet), but unintentionally, as
we only want the buffer to be placed into _dh variable.
Fixes: 2bc780499aa3 ("[NETFILTER]: nf_conntrack: add DCCP protocol support")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-20 | static int dccp_error(struct net *net, struct nf_conn *tmpl,
struct sk_buff *skb, unsigned int dataoff,
enum ip_conntrack_info *ctinfo,
u_int8_t pf, unsigned int hooknum)
{
struct dccp_hdr _dh, *dh;
unsigned int dccp_len = skb->len - dataoff;
unsigned int cscov;
const char *msg;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh);
if (dh == NULL) {
msg = "nf_ct_dccp: short packet ";
goto out_invalid;
}
if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) ||
dh->dccph_doff * 4 > dccp_len) {
msg = "nf_ct_dccp: truncated/malformed packet ";
goto out_invalid;
}
cscov = dccp_len;
if (dh->dccph_cscov) {
cscov = (dh->dccph_cscov - 1) * 4;
if (cscov > dccp_len) {
msg = "nf_ct_dccp: bad checksum coverage ";
goto out_invalid;
}
}
if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP,
pf)) {
msg = "nf_ct_dccp: bad checksum ";
goto out_invalid;
}
if (dh->dccph_type >= DCCP_PKT_INVALID) {
msg = "nf_ct_dccp: reserved packet type ";
goto out_invalid;
}
return NF_ACCEPT;
out_invalid:
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg);
return -NF_ACCEPT;
}
| 166,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LinkChangeSerializerMarkupAccumulator::LinkChangeSerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes, LinkLocalPathMap* links, String directoryName)
: SerializerMarkupAccumulator(serializer, document, nodes)
, m_replaceLinks(links)
, m_directoryName(directoryName)
{
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | LinkChangeSerializerMarkupAccumulator::LinkChangeSerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes, LinkLocalPathMap* links, String directoryName)
| 171,562 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAAC2::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
aacParams->nBitRate = 0;
aacParams->nAudioBandWidth = 0;
aacParams->nAACtools = 0;
aacParams->nAACERtools = 0;
aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
aacParams->eAACStreamFormat =
mIsADTS
? OMX_AUDIO_AACStreamFormatMP4ADTS
: OMX_AUDIO_AACStreamFormatMP4FF;
aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
if (!isConfigured()) {
aacParams->nChannels = 1;
aacParams->nSampleRate = 44100;
aacParams->nFrameLength = 0;
} else {
aacParams->nChannels = mStreamInfo->numChannels;
aacParams->nSampleRate = mStreamInfo->sampleRate;
aacParams->nFrameLength = mStreamInfo->frameSize;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF;
pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE;
pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS;
pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mStreamInfo->numChannels;
pcmParams->nSamplingRate = mStreamInfo->sampleRate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAAC2::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
aacParams->nBitRate = 0;
aacParams->nAudioBandWidth = 0;
aacParams->nAACtools = 0;
aacParams->nAACERtools = 0;
aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
aacParams->eAACStreamFormat =
mIsADTS
? OMX_AUDIO_AACStreamFormatMP4ADTS
: OMX_AUDIO_AACStreamFormatMP4FF;
aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
if (!isConfigured()) {
aacParams->nChannels = 1;
aacParams->nSampleRate = 44100;
aacParams->nFrameLength = 0;
} else {
aacParams->nChannels = mStreamInfo->numChannels;
aacParams->nSampleRate = mStreamInfo->sampleRate;
aacParams->nFrameLength = mStreamInfo->frameSize;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF;
pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE;
pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS;
pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mStreamInfo->numChannels;
pcmParams->nSamplingRate = mStreamInfo->sampleRate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,186 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Chapters::Atom::GetStopTimecode() const
{
return m_stop_timecode;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Chapters::Atom::GetStopTimecode() const
| 174,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void edge_bulk_in_callback(struct urb *urb)
{
struct edgeport_port *edge_port = urb->context;
struct device *dev = &edge_port->port->dev;
unsigned char *data = urb->transfer_buffer;
int retval = 0;
int port_number;
int status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status);
return;
default:
dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status);
}
if (status == -EPIPE)
goto exit;
if (status) {
dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__);
return;
}
port_number = edge_port->port->port_number;
if (edge_port->lsr_event) {
edge_port->lsr_event = 0;
dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n",
__func__, port_number, edge_port->lsr_mask, *data);
handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data);
/* Adjust buffer length/pointer */
--urb->actual_length;
++data;
}
if (urb->actual_length) {
usb_serial_debug_data(dev, __func__, urb->actual_length, data);
if (edge_port->close_pending)
dev_dbg(dev, "%s - close pending, dropping data on the floor\n",
__func__);
else
edge_tty_recv(edge_port->port, data,
urb->actual_length);
edge_port->port->icount.rx += urb->actual_length;
}
exit:
/* continue read unless stopped */
spin_lock(&edge_port->ep_lock);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING)
retval = usb_submit_urb(urb, GFP_ATOMIC);
else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING)
edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED;
spin_unlock(&edge_port->ep_lock);
if (retval)
dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval);
}
Commit Message: USB: serial: io_ti: fix information leak in completion handler
Add missing sanity check to the bulk-in completion handler to avoid an
integer underflow that can be triggered by a malicious device.
This avoids leaking 128 kB of memory content from after the URB transfer
buffer to user space.
Fixes: 8c209e6782ca ("USB: make actual_length in struct urb field u32")
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <[email protected]> # 2.6.30
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-191 | static void edge_bulk_in_callback(struct urb *urb)
{
struct edgeport_port *edge_port = urb->context;
struct device *dev = &edge_port->port->dev;
unsigned char *data = urb->transfer_buffer;
int retval = 0;
int port_number;
int status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status);
return;
default:
dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status);
}
if (status == -EPIPE)
goto exit;
if (status) {
dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__);
return;
}
port_number = edge_port->port->port_number;
if (urb->actual_length > 0 && edge_port->lsr_event) {
edge_port->lsr_event = 0;
dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n",
__func__, port_number, edge_port->lsr_mask, *data);
handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data);
/* Adjust buffer length/pointer */
--urb->actual_length;
++data;
}
if (urb->actual_length) {
usb_serial_debug_data(dev, __func__, urb->actual_length, data);
if (edge_port->close_pending)
dev_dbg(dev, "%s - close pending, dropping data on the floor\n",
__func__);
else
edge_tty_recv(edge_port->port, data,
urb->actual_length);
edge_port->port->icount.rx += urb->actual_length;
}
exit:
/* continue read unless stopped */
spin_lock(&edge_port->ep_lock);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING)
retval = usb_submit_urb(urb, GFP_ATOMIC);
else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING)
edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED;
spin_unlock(&edge_port->ep_lock);
if (retval)
dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval);
}
| 168,189 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() {
DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult();
if (!array_buffer) {
RejectPromise(kAllocationFailureImageBitmapRejectionReason);
return;
}
ScheduleAsyncImageBitmapDecoding(array_buffer);
}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416 | void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() {
DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult();
loader_.reset();
if (!array_buffer) {
RejectPromise(kAllocationFailureImageBitmapRejectionReason);
return;
}
ScheduleAsyncImageBitmapDecoding(array_buffer);
}
| 173,066 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title)
: valid_(true),
native_dialog_(NULL),
title_(title),
web_contents_(web_contents) {
}
Commit Message: Fix a Windows crash bug with javascript alerts from extension popups.
BUG=137707
Review URL: https://chromiumcodereview.appspot.com/10828423
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title)
: valid_(true),
native_dialog_(NULL),
title_(title),
web_contents_(web_contents),
completed_(false) {
}
| 170,753 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
size_t fname_len;
int zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename();
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
size_t fname_len;
int zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename();
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
| 165,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId,
wStream* s)
{
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp,
cbChId,
ChannelId);
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId,
wStream* s)
{
UINT32 ChannelId;
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp,
cbChId,
ChannelId);
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
| 168,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_stringify (MyObject *obj, GValue *value, char **ret, GError **error)
{
GValue valstr = {0, };
g_value_init (&valstr, G_TYPE_STRING);
if (!g_value_transform (value, &valstr))
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"couldn't transform value");
return FALSE;
}
*ret = g_value_dup_string (&valstr);
g_value_unset (&valstr);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_stringify (MyObject *obj, GValue *value, char **ret, GError **error)
| 165,122 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.