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: WebGLObject::WebGLObject(WebGLRenderingContext* context)
: m_object(0)
, m_attachmentCount(0)
, m_deleted(false)
{
}
Commit Message: Unreviewed, build fix for unused argument warning after r104954.
https://bugs.webkit.org/show_bug.cgi?id=75906
Also fixed up somebody's bad merge in Source/WebCore/ChangeLog.
* html/canvas/WebGLObject.cpp:
(WebCore::WebGLObject::WebGLObject):
git-svn-id: svn://svn.chromium.org/blink/trunk@104959 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | WebGLObject::WebGLObject(WebGLRenderingContext* context)
WebGLObject::WebGLObject(WebGLRenderingContext*)
: m_object(0)
, m_attachmentCount(0)
, m_deleted(false)
{
}
| 170,251 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct uvesafb_pal_entry *entries;
int shift = 16 - dac_width;
int i, err = 0;
if (info->var.bits_per_pixel == 8) {
if (cmap->start + cmap->len > info->cmap.start +
info->cmap.len || cmap->start < info->cmap.start)
return -EINVAL;
entries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL);
if (!entries)
return -ENOMEM;
for (i = 0; i < cmap->len; i++) {
entries[i].red = cmap->red[i] >> shift;
entries[i].green = cmap->green[i] >> shift;
entries[i].blue = cmap->blue[i] >> shift;
entries[i].pad = 0;
}
err = uvesafb_setpalette(entries, cmap->len, cmap->start, info);
kfree(entries);
} else {
/*
* For modes with bpp > 8, we only set the pseudo palette in
* the fb_info struct. We rely on uvesafb_setcolreg to do all
* sanity checking.
*/
for (i = 0; i < cmap->len; i++) {
err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],
cmap->green[i], cmap->blue[i],
0, info);
}
}
return err;
}
Commit Message: video: uvesafb: Fix integer overflow in allocation
cmap->len can get close to INT_MAX/2, allowing for an integer overflow in
allocation. This uses kmalloc_array() instead to catch the condition.
Reported-by: Dr Silvio Cesare of InfoSect <[email protected]>
Fixes: 8bdb3a2d7df48 ("uvesafb: the driver core")
Cc: [email protected]
Signed-off-by: Kees Cook <[email protected]>
CWE ID: CWE-190 | static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct uvesafb_pal_entry *entries;
int shift = 16 - dac_width;
int i, err = 0;
if (info->var.bits_per_pixel == 8) {
if (cmap->start + cmap->len > info->cmap.start +
info->cmap.len || cmap->start < info->cmap.start)
return -EINVAL;
entries = kmalloc_array(cmap->len, sizeof(*entries),
GFP_KERNEL);
if (!entries)
return -ENOMEM;
for (i = 0; i < cmap->len; i++) {
entries[i].red = cmap->red[i] >> shift;
entries[i].green = cmap->green[i] >> shift;
entries[i].blue = cmap->blue[i] >> shift;
entries[i].pad = 0;
}
err = uvesafb_setpalette(entries, cmap->len, cmap->start, info);
kfree(entries);
} else {
/*
* For modes with bpp > 8, we only set the pseudo palette in
* the fb_info struct. We rely on uvesafb_setcolreg to do all
* sanity checking.
*/
for (i = 0; i < cmap->len; i++) {
err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],
cmap->green[i], cmap->blue[i],
0, info);
}
}
return err;
}
| 169,152 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
size_t bytes)
{
struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
int read;
DEBUG("read %zu bytes, state: %d", bytes, in->common.state);
if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED)
{
DEBUG("stream suspended");
return -1;
}
/* only allow autostarting if we are in stopped or standby */
if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) ||
(in->common.state == AUDIO_A2DP_STATE_STANDBY))
{
pthread_mutex_lock(&in->common.lock);
if (start_audio_datapath(&in->common) < 0)
{
/* emulate time this write represents to avoid very fast write
failures during transition periods or remote suspend */
int us_delay = calc_audiotime(in->common.cfg, bytes);
DEBUG("emulate a2dp read delay (%d us)", us_delay);
usleep(us_delay);
pthread_mutex_unlock(&in->common.lock);
return -1;
}
pthread_mutex_unlock(&in->common.lock);
}
else if (in->common.state != AUDIO_A2DP_STATE_STARTED)
{
ERROR("stream not in stopped or standby");
return -1;
}
read = skt_read(in->common.audio_fd, buffer, bytes);
if (read == -1)
{
skt_disconnect(in->common.audio_fd);
in->common.audio_fd = AUDIO_SKT_DISCONNECTED;
in->common.state = AUDIO_A2DP_STATE_STOPPED;
} else if (read == 0) {
DEBUG("read time out - return zeros");
memset(buffer, 0, bytes);
read = bytes;
}
DEBUG("read %d bytes out of %zu bytes", read, bytes);
return read;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
size_t bytes)
{
struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
int read;
DEBUG("read %zu bytes, state: %d", bytes, in->common.state);
if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED)
{
DEBUG("stream suspended");
return -1;
}
/* only allow autostarting if we are in stopped or standby */
if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) ||
(in->common.state == AUDIO_A2DP_STATE_STANDBY))
{
pthread_mutex_lock(&in->common.lock);
if (start_audio_datapath(&in->common) < 0)
{
/* emulate time this write represents to avoid very fast write
failures during transition periods or remote suspend */
int us_delay = calc_audiotime(in->common.cfg, bytes);
DEBUG("emulate a2dp read delay (%d us)", us_delay);
TEMP_FAILURE_RETRY(usleep(us_delay));
pthread_mutex_unlock(&in->common.lock);
return -1;
}
pthread_mutex_unlock(&in->common.lock);
}
else if (in->common.state != AUDIO_A2DP_STATE_STARTED)
{
ERROR("stream not in stopped or standby");
return -1;
}
read = skt_read(in->common.audio_fd, buffer, bytes);
if (read == -1)
{
skt_disconnect(in->common.audio_fd);
in->common.audio_fd = AUDIO_SKT_DISCONNECTED;
in->common.state = AUDIO_A2DP_STATE_STOPPED;
} else if (read == 0) {
DEBUG("read time out - return zeros");
memset(buffer, 0, bytes);
read = bytes;
}
DEBUG("read %d bytes out of %zu bytes", read, bytes);
return read;
}
| 173,426 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 apparmor_setprocattr(struct task_struct *task, char *name,
void *value, size_t size)
{
char *command, *args = value;
size_t arg_size;
int error;
if (size == 0)
return -EINVAL;
/* args points to a PAGE_SIZE buffer, AppArmor requires that
* the buffer must be null terminated or have size <= PAGE_SIZE -1
* so that AppArmor can null terminate them
*/
if (args[size - 1] != '\0') {
if (size == PAGE_SIZE)
return -EINVAL;
args[size] = '\0';
}
/* task can only write its own attributes */
if (current != task)
return -EACCES;
args = value;
args = strim(args);
command = strsep(&args, " ");
if (!args)
return -EINVAL;
args = skip_spaces(args);
if (!*args)
return -EINVAL;
arg_size = size - (args - (char *) value);
if (strcmp(name, "current") == 0) {
if (strcmp(command, "changehat") == 0) {
error = aa_setprocattr_changehat(args, arg_size,
!AA_DO_TEST);
} else if (strcmp(command, "permhat") == 0) {
error = aa_setprocattr_changehat(args, arg_size,
AA_DO_TEST);
} else if (strcmp(command, "changeprofile") == 0) {
error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
!AA_DO_TEST);
} else if (strcmp(command, "permprofile") == 0) {
error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
AA_DO_TEST);
} else if (strcmp(command, "permipc") == 0) {
error = aa_setprocattr_permipc(args);
} else {
struct common_audit_data sa;
COMMON_AUDIT_DATA_INIT(&sa, NONE);
sa.aad.op = OP_SETPROCATTR;
sa.aad.info = name;
sa.aad.error = -EINVAL;
return aa_audit(AUDIT_APPARMOR_DENIED, NULL, GFP_KERNEL,
&sa, NULL);
}
} else if (strcmp(name, "exec") == 0) {
error = aa_setprocattr_changeprofile(args, AA_ONEXEC,
!AA_DO_TEST);
} else {
/* only support the "current" and "exec" process attributes */
return -EINVAL;
}
if (!error)
error = size;
return error;
}
Commit Message: AppArmor: fix oops in apparmor_setprocattr
When invalid parameters are passed to apparmor_setprocattr a NULL deref
oops occurs when it tries to record an audit message. This is because
it is passing NULL for the profile parameter for aa_audit. But aa_audit
now requires that the profile passed is not NULL.
Fix this by passing the current profile on the task that is trying to
setprocattr.
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: John Johansen <[email protected]>
Cc: [email protected]
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-20 | static int apparmor_setprocattr(struct task_struct *task, char *name,
void *value, size_t size)
{
char *command, *args = value;
size_t arg_size;
int error;
if (size == 0)
return -EINVAL;
/* args points to a PAGE_SIZE buffer, AppArmor requires that
* the buffer must be null terminated or have size <= PAGE_SIZE -1
* so that AppArmor can null terminate them
*/
if (args[size - 1] != '\0') {
if (size == PAGE_SIZE)
return -EINVAL;
args[size] = '\0';
}
/* task can only write its own attributes */
if (current != task)
return -EACCES;
args = value;
args = strim(args);
command = strsep(&args, " ");
if (!args)
return -EINVAL;
args = skip_spaces(args);
if (!*args)
return -EINVAL;
arg_size = size - (args - (char *) value);
if (strcmp(name, "current") == 0) {
if (strcmp(command, "changehat") == 0) {
error = aa_setprocattr_changehat(args, arg_size,
!AA_DO_TEST);
} else if (strcmp(command, "permhat") == 0) {
error = aa_setprocattr_changehat(args, arg_size,
AA_DO_TEST);
} else if (strcmp(command, "changeprofile") == 0) {
error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
!AA_DO_TEST);
} else if (strcmp(command, "permprofile") == 0) {
error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
AA_DO_TEST);
} else if (strcmp(command, "permipc") == 0) {
error = aa_setprocattr_permipc(args);
} else {
struct common_audit_data sa;
COMMON_AUDIT_DATA_INIT(&sa, NONE);
sa.aad.op = OP_SETPROCATTR;
sa.aad.info = name;
sa.aad.error = -EINVAL;
return aa_audit(AUDIT_APPARMOR_DENIED,
__aa_current_profile(), GFP_KERNEL,
&sa, NULL);
}
} else if (strcmp(name, "exec") == 0) {
error = aa_setprocattr_changeprofile(args, AA_ONEXEC,
!AA_DO_TEST);
} else {
/* only support the "current" and "exec" process attributes */
return -EINVAL;
}
if (!error)
error = size;
return error;
}
| 166,219 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() {
return crypto_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() {
| 170,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: SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
char *buf;
size_t buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval entry, inf;
zval *pcount, *pmembers;
spl_SplObjectStorageElement *element;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
pcount = var_tmp_var(&var_hash);
if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
while (count-- > 0) {
spl_SplObjectStorageElement *pelement;
zend_string *hash;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
/* store reference to allow cross-references between different elements */
if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {
goto outexcept;
}
if (Z_TYPE(entry) != IS_OBJECT) {
zval_ptr_dtor(&entry);
goto outexcept;
}
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {
zval_ptr_dtor(&entry);
goto outexcept;
}
} else {
ZVAL_UNDEF(&inf);
}
hash = spl_object_storage_get_hash(intern, getThis(), &entry);
if (!hash) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (pelement) {
if (!Z_ISUNDEF(pelement->inf)) {
var_push_dtor(&var_hash, &pelement->inf);
}
if (!Z_ISUNDEF(pelement->obj)) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);
var_replace(&var_hash, &entry, &element->obj);
var_replace(&var_hash, &inf, &element->inf);
zval_ptr_dtor(&entry);
ZVAL_UNDEF(&entry);
zval_ptr_dtor(&inf);
ZVAL_UNDEF(&inf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
pmembers = var_tmp_var(&var_hash);
if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {
goto outexcept;
}
/* copy members */
object_properties_load(&intern->std, Z_ARRVAL_P(pmembers));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
Commit Message: Fix bug #73257 and bug #73258 - SplObjectStorage unserialize allows use of non-object as key
CWE ID: CWE-119 | SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
char *buf;
size_t buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval entry, inf;
zval *pcount, *pmembers;
spl_SplObjectStorageElement *element;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
pcount = var_tmp_var(&var_hash);
if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
ZVAL_UNDEF(&entry);
ZVAL_UNDEF(&inf);
while (count-- > 0) {
spl_SplObjectStorageElement *pelement;
zend_string *hash;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
/* store reference to allow cross-references between different elements */
if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {
goto outexcept;
}
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {
zval_ptr_dtor(&entry);
goto outexcept;
}
}
if (Z_TYPE(entry) != IS_OBJECT) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
hash = spl_object_storage_get_hash(intern, getThis(), &entry);
if (!hash) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (pelement) {
if (!Z_ISUNDEF(pelement->inf)) {
var_push_dtor(&var_hash, &pelement->inf);
}
if (!Z_ISUNDEF(pelement->obj)) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);
var_replace(&var_hash, &entry, &element->obj);
var_replace(&var_hash, &inf, &element->inf);
zval_ptr_dtor(&entry);
ZVAL_UNDEF(&entry);
zval_ptr_dtor(&inf);
ZVAL_UNDEF(&inf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
pmembers = var_tmp_var(&var_hash);
if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {
goto outexcept;
}
/* copy members */
object_properties_load(&intern->std, Z_ARRVAL_P(pmembers));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
| 168,812 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_recv_tls(gnutls_session * session)
{
char *buf = NULL;
int rc = 0;
int len = 0;
int chunk_size = 1024;
if (session == NULL) {
return NULL;
}
buf = calloc(1, chunk_size);
while (TRUE) {
errno = 0;
rc = gnutls_record_recv(*session, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", rc, errno);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_trace("Retry");
} else if (rc == GNUTLS_E_UNEXPECTED_PACKET_LENGTH) {
crm_trace("Session disconnected");
goto bail;
} else if (rc < 0) {
crm_err("Error receiving message: %s (%d)", gnutls_strerror(rc), rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
crm_trace("Got %d more bytes", (int)rc);
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_recv_tls(gnutls_session * session)
crm_recv_tls(gnutls_session * session, size_t max_size, size_t *recv_len, int *disconnected)
{
char *buf = NULL;
int rc = 0;
size_t len = 0;
size_t chunk_size = max_size ? max_size : 1024;
size_t buf_size = 0;
size_t read_size = 0;
if (session == NULL) {
if (disconnected) {
*disconnected = 1;
}
goto done;
}
buf = calloc(1, chunk_size + 1);
buf_size = chunk_size;
while (TRUE) {
read_size = buf_size - len;
/* automatically grow the buffer when needed if max_size is not set.*/
if (!max_size && (read_size < (chunk_size / 2))) {
buf_size += chunk_size;
crm_trace("Grow buffer by %d more bytes. buf is now %d bytes", (int)chunk_size, buf_size);
buf = realloc(buf, buf_size + 1);
CRM_ASSERT(buf != NULL);
read_size = buf_size - len;
}
rc = gnutls_record_recv(*session, buf + len, read_size);
if (rc > 0) {
crm_trace("Got %d more bytes.", rc);
len += rc;
/* always null terminate buffer, the +1 to alloc always allows for this.*/
buf[len] = '\0';
}
if (max_size && (max_size == read_size)) {
crm_trace("Buffer max read size %d met" , max_size);
goto done;
}
/* process any errors. */
if (rc == GNUTLS_E_INTERRUPTED) {
crm_trace("EINTR encoutered, retry tls read");
} else if (rc == GNUTLS_E_AGAIN) {
crm_trace("non-blocking, exiting read on rc = %d", rc);
goto done;
} else if (rc <= 0) {
if (rc == 0) {
crm_debug("EOF encoutered during TLS read");
} else {
crm_debug("Error receiving message: %s (%d)", gnutls_strerror(rc), rc);
}
if (disconnected) {
*disconnected = 1;
}
goto done;
}
}
done:
if (recv_len) {
*recv_len = len;
}
if (!len) {
free(buf);
buf = NULL;
}
return buf;
}
| 166,159 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderImpl::HandleDrawArrays(
uint32 immediate_data_size, const gles2::DrawArrays& c) {
GLenum mode = static_cast<GLenum>(c.mode);
GLint first = static_cast<GLint>(c.first);
GLsizei count = static_cast<GLsizei>(c.count);
if (!validators_->draw_mode.IsValid(mode)) {
SetGLError(GL_INVALID_ENUM, "glDrawArrays: mode GL_INVALID_ENUM");
return error::kNoError;
}
if (count < 0) {
SetGLError(GL_INVALID_VALUE, "glDrawArrays: count < 0");
return error::kNoError;
}
if (!CheckFramebufferComplete("glDrawArrays")) {
return error::kNoError;
}
if (first < 0) {
SetGLError(GL_INVALID_VALUE, "glDrawArrays: first < 0");
return error::kNoError;
}
if (count == 0) {
return error::kNoError;
}
GLuint max_vertex_accessed = first + count - 1;
if (IsDrawValid(max_vertex_accessed)) {
bool simulated_attrib_0 = SimulateAttrib0(max_vertex_accessed);
bool simulated_fixed_attribs = false;
if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) {
bool textures_set = SetBlackTextureForNonRenderableTextures();
ApplyDirtyState();
glDrawArrays(mode, first, count);
if (textures_set) {
RestoreStateForNonRenderableTextures();
}
if (simulated_fixed_attribs) {
RestoreStateForSimulatedFixedAttribs();
}
}
if (simulated_attrib_0) {
RestoreStateForSimulatedAttrib0();
}
if (WasContextLost()) {
LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawArrays.";
return error::kLostContext;
}
}
return error::kNoError;
}
Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0."""
TEST=none
BUG=95625
[email protected]
Review URL: http://codereview.chromium.org/7796016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | error::Error GLES2DecoderImpl::HandleDrawArrays(
uint32 immediate_data_size, const gles2::DrawArrays& c) {
GLenum mode = static_cast<GLenum>(c.mode);
GLint first = static_cast<GLint>(c.first);
GLsizei count = static_cast<GLsizei>(c.count);
if (!validators_->draw_mode.IsValid(mode)) {
SetGLError(GL_INVALID_ENUM, "glDrawArrays: mode GL_INVALID_ENUM");
return error::kNoError;
}
if (count < 0) {
SetGLError(GL_INVALID_VALUE, "glDrawArrays: count < 0");
return error::kNoError;
}
if (!CheckFramebufferComplete("glDrawArrays")) {
return error::kNoError;
}
if (first < 0) {
SetGLError(GL_INVALID_VALUE, "glDrawArrays: first < 0");
return error::kNoError;
}
if (count == 0) {
return error::kNoError;
}
GLuint max_vertex_accessed = first + count - 1;
if (IsDrawValid(max_vertex_accessed)) {
bool simulated_attrib_0 = false;
if (!SimulateAttrib0(max_vertex_accessed, &simulated_attrib_0)) {
return error::kNoError;
}
bool simulated_fixed_attribs = false;
if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) {
bool textures_set = SetBlackTextureForNonRenderableTextures();
ApplyDirtyState();
glDrawArrays(mode, first, count);
if (textures_set) {
RestoreStateForNonRenderableTextures();
}
if (simulated_fixed_attribs) {
RestoreStateForSimulatedFixedAttribs();
}
}
if (simulated_attrib_0) {
RestoreStateForSimulatedAttrib0();
}
if (WasContextLost()) {
LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawArrays.";
return error::kLostContext;
}
}
return error::kNoError;
}
| 170,330 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const CuePoint* Cues::GetFirst() const {
if (m_cue_points == NULL)
return NULL;
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | const CuePoint* Cues::GetFirst() const {
if (m_cue_points == NULL || m_count == 0)
return NULL;
CuePoint* const* const pp = m_cue_points;
if (pp == NULL)
return NULL;
CuePoint* const pCP = pp[0];
if (pCP == NULL || pCP->GetTimeCode() < 0)
return NULL;
return pCP;
}
| 173,818 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) { // Display ID
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
} else if (id == 0x1654) { // StringUID ID
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
} else if (id == 0x33C4) { // UID ID
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (status < 0) // error
return status;
m_uid = static_cast<unsigned long long>(val);
} else if (id == 0x11) { // TimeStart ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
} else if (id == 0x12) { // TimeEnd ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) { // Display ID
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
} else if (id == 0x1654) { // StringUID ID
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
} else if (id == 0x33C4) { // UID ID
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (status < 0) // error
return status;
m_uid = static_cast<unsigned long long>(val);
} else if (id == 0x11) { // TimeStart ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
} else if (id == 0x12) { // TimeEnd ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags)
{
BYTE cmac[8];
BYTE wmac[8];
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
UINT16 len;
BYTE version, pad;
BYTE* sig;
if (stream_get_left(s) < 12)
return FALSE;
stream_read_UINT16(s, len); /* 0x10 */
stream_read_BYTE(s, version); /* 0x1 */
stream_read_BYTE(s, pad);
sig = s->p;
stream_seek(s, 8); /* signature */
length -= 12;
if (!security_fips_decrypt(s->p, length, rdp))
{
printf("FATAL: cannot decrypt\n");
return FALSE; /* TODO */
}
if (!security_fips_check_signature(s->p, length - pad, sig, rdp))
{
printf("FATAL: invalid packet signature\n");
return FALSE; /* TODO */
}
/* is this what needs adjusting? */
s->size -= pad;
return TRUE;
}
if (stream_get_left(s) < 8)
return FALSE;
stream_read(s, wmac, sizeof(wmac));
length -= sizeof(wmac);
security_decrypt(s->p, length, rdp);
if (securityFlags & SEC_SECURE_CHECKSUM)
security_salted_mac_signature(rdp, s->p, length, FALSE, cmac);
else
security_mac_signature(rdp, s->p, length, cmac);
if (memcmp(wmac, cmac, sizeof(wmac)) != 0)
{
printf("WARNING: invalid packet signature\n");
/*
* Because Standard RDP Security is totally broken,
* and cannot protect against MITM, don't treat signature
* verification failure as critical. This at least enables
* us to work with broken RDP clients and servers that
* generate invalid signatures.
*/
}
return TRUE;
}
Commit Message: security: add a NULL pointer check to fix a server crash.
CWE ID: CWE-476 | BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags)
{
BYTE cmac[8];
BYTE wmac[8];
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
UINT16 len;
BYTE version, pad;
BYTE* sig;
if (stream_get_left(s) < 12)
return FALSE;
stream_read_UINT16(s, len); /* 0x10 */
stream_read_BYTE(s, version); /* 0x1 */
stream_read_BYTE(s, pad);
sig = s->p;
stream_seek(s, 8); /* signature */
length -= 12;
if (!security_fips_decrypt(s->p, length, rdp))
{
printf("FATAL: cannot decrypt\n");
return FALSE; /* TODO */
}
if (!security_fips_check_signature(s->p, length - pad, sig, rdp))
{
printf("FATAL: invalid packet signature\n");
return FALSE; /* TODO */
}
/* is this what needs adjusting? */
s->size -= pad;
return TRUE;
}
if (stream_get_left(s) < 8)
return FALSE;
stream_read(s, wmac, sizeof(wmac));
length -= sizeof(wmac);
if (!security_decrypt(s->p, length, rdp))
return FALSE;
if (securityFlags & SEC_SECURE_CHECKSUM)
security_salted_mac_signature(rdp, s->p, length, FALSE, cmac);
else
security_mac_signature(rdp, s->p, length, cmac);
if (memcmp(wmac, cmac, sizeof(wmac)) != 0)
{
printf("WARNING: invalid packet signature\n");
/*
* Because Standard RDP Security is totally broken,
* and cannot protect against MITM, don't treat signature
* verification failure as critical. This at least enables
* us to work with broken RDP clients and servers that
* generate invalid signatures.
*/
}
return TRUE;
}
| 167,606 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 strdup_if_nonnull(char **target, char *source)
{
if (source) {
*target = kstrdup(source, GFP_KERNEL);
if (!*target)
return -ENOMEM;
} else
*target = NULL;
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | int strdup_if_nonnull(char **target, char *source)
| 168,146 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 EnsureInitializeForAndroidLayoutTests() {
CHECK(CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree));
JNIEnv* env = base::android::AttachCurrentThread();
content::NestedMessagePumpAndroid::RegisterJni(env);
content::RegisterNativesImpl(env);
bool success = base::MessageLoop::InitMessagePumpForUIFactory(
&CreateMessagePumpForUI);
CHECK(success) << "Unable to initialize the message pump for Android.";
base::FilePath files_dir(GetTestFilesDirectory(env));
base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo")));
EnsureCreateFIFO(stdout_fifo);
base::FilePath stderr_fifo(
files_dir.Append(FILE_PATH_LITERAL("stderr.fifo")));
EnsureCreateFIFO(stderr_fifo);
base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo")));
EnsureCreateFIFO(stdin_fifo);
success = base::android::RedirectStream(stdout, stdout_fifo, "w") &&
base::android::RedirectStream(stdin, stdin_fifo, "r") &&
base::android::RedirectStream(stderr, stderr_fifo, "w");
CHECK(success) << "Unable to initialize the Android FIFOs.";
}
Commit Message: Content Shell: Move shell_layout_tests_android into layout_tests/.
BUG=420994
Review URL: https://codereview.chromium.org/661743002
Cr-Commit-Position: refs/heads/master@{#299892}
CWE ID: CWE-119 | void EnsureInitializeForAndroidLayoutTests() {
JNIEnv* env = base::android::AttachCurrentThread();
content::NestedMessagePumpAndroid::RegisterJni(env);
content::RegisterNativesImpl(env);
bool success = base::MessageLoop::InitMessagePumpForUIFactory(
&CreateMessagePumpForUI);
CHECK(success) << "Unable to initialize the message pump for Android.";
base::FilePath files_dir(GetTestFilesDirectory(env));
base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo")));
EnsureCreateFIFO(stdout_fifo);
base::FilePath stderr_fifo(
files_dir.Append(FILE_PATH_LITERAL("stderr.fifo")));
EnsureCreateFIFO(stderr_fifo);
base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo")));
EnsureCreateFIFO(stdin_fifo);
success = base::android::RedirectStream(stdout, stdout_fifo, "w") &&
base::android::RedirectStream(stdin, stdin_fifo, "r") &&
base::android::RedirectStream(stderr, stderr_fifo, "w");
CHECK(success) << "Unable to initialize the Android FIFOs.";
}
| 171,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Track::Info::Copy(Info& dst) const {
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | int Track::Info::Copy(Info& dst) const {
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = SafeArrayAlloc<unsigned char>(1, codecPrivateSize);
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
| 173,802 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: local unsigned long crc32_big(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register z_crc_t c;
register const z_crc_t FAR *buf4;
c = ZSWAP32((z_crc_t)crc);
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
len--;
}
buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
buf4--;
while (len >= 32) {
DOBIG32;
len -= 32;
}
while (len >= 4) {
DOBIG4;
len -= 4;
}
buf4++;
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
} while (--len);
c = ~c;
return (unsigned long)(ZSWAP32(c));
}
Commit Message: Avoid pre-decrement of pointer in big-endian CRC calculation.
There was a small optimization for PowerPCs to pre-increment a
pointer when accessing a word, instead of post-incrementing. This
required prefacing the loop with a decrement of the pointer,
possibly pointing before the object passed. This is not compliant
with the C standard, for which decrementing a pointer before its
allocated memory is undefined. When tested on a modern PowerPC
with a modern compiler, the optimization no longer has any effect.
Due to all that, and per the recommendation of a security audit of
the zlib code by Trail of Bits and TrustInSoft, in support of the
Mozilla Foundation, this "optimization" was removed, in order to
avoid the possibility of undefined behavior.
CWE ID: CWE-189 | local unsigned long crc32_big(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register z_crc_t c;
register const z_crc_t FAR *buf4;
c = ZSWAP32((z_crc_t)crc);
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
len--;
}
buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
while (len >= 32) {
DOBIG32;
len -= 32;
}
while (len >= 4) {
DOBIG4;
len -= 4;
}
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
} while (--len);
c = ~c;
return (unsigned long)(ZSWAP32(c));
}
| 168,672 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
int count, i;
count = be32_to_cpu(aclp->acl_cnt);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
Commit Message: xfs: validate acl count
This prevents in-memory corruption and possible panics if the on-disk
ACL is badly corrupted.
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Ben Myers <[email protected]>
CWE ID: CWE-189 | xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
int count, i;
count = be32_to_cpu(aclp->acl_cnt);
if (count > XFS_ACL_MAX_ENTRIES)
return ERR_PTR(-EFSCORRUPTED);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
| 165,656 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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, delete)
{
char *fname;
size_t fname_len;
char *error;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_TRUE;
} else {
entry->is_deleted = 1;
entry->is_modified = 1;
phar_obj->archive->is_modified = 1;
}
}
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
RETURN_FALSE;
}
phar_flush(phar_obj->archive, NULL, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, delete)
{
char *fname;
size_t fname_len;
char *error;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_TRUE;
} else {
entry->is_deleted = 1;
entry->is_modified = 1;
phar_obj->archive->is_modified = 1;
}
}
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
RETURN_FALSE;
}
phar_flush(phar_obj->archive, NULL, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
| 165,063 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Utterance::Utterance(Profile* profile,
const std::string& text,
DictionaryValue* options,
Task* completion_task)
: profile_(profile),
id_(next_utterance_id_++),
text_(text),
rate_(-1.0),
pitch_(-1.0),
volume_(-1.0),
can_enqueue_(false),
completion_task_(completion_task) {
if (!options) {
options_.reset(new DictionaryValue());
return;
}
options_.reset(options->DeepCopy());
if (options->HasKey(util::kVoiceNameKey))
options->GetString(util::kVoiceNameKey, &voice_name_);
if (options->HasKey(util::kLocaleKey))
options->GetString(util::kLocaleKey, &locale_);
if (options->HasKey(util::kGenderKey))
options->GetString(util::kGenderKey, &gender_);
if (options->GetDouble(util::kRateKey, &rate_)) {
if (!base::IsFinite(rate_) || rate_ < 0.0 || rate_ > 1.0)
rate_ = -1.0;
}
if (options->GetDouble(util::kPitchKey, &pitch_)) {
if (!base::IsFinite(pitch_) || pitch_ < 0.0 || pitch_ > 1.0)
pitch_ = -1.0;
}
if (options->GetDouble(util::kVolumeKey, &volume_)) {
if (!base::IsFinite(volume_) || volume_ < 0.0 || volume_ > 1.0)
volume_ = -1.0;
}
if (options->HasKey(util::kEnqueueKey))
options->GetBoolean(util::kEnqueueKey, &can_enqueue_);
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | Utterance::Utterance(Profile* profile,
bool ExtensionTtsSpeakFunction::RunImpl() {
std::string text;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text));
if (text.size() > 32768) {
error_ = constants::kErrorUtteranceTooLong;
return false;
}
scoped_ptr<DictionaryValue> options;
if (args_->GetSize() >= 2) {
DictionaryValue* temp_options = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &temp_options));
options.reset(temp_options->DeepCopy());
}
std::string voice_name;
if (options->HasKey(constants::kVoiceNameKey)) {
EXTENSION_FUNCTION_VALIDATE(
options->GetString(constants::kVoiceNameKey, &voice_name));
}
std::string lang;
if (options->HasKey(constants::kLangKey))
EXTENSION_FUNCTION_VALIDATE(options->GetString(constants::kLangKey, &lang));
if (!lang.empty() && !l10n_util::IsValidLocaleSyntax(lang)) {
error_ = constants::kErrorInvalidLang;
return false;
}
| 170,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
{
png_infop info_ptr = *ptr_ptr;
png_debug(1, "in png_info_init_3");
if (info_ptr == NULL)
return;
if (png_sizeof(png_info) > png_info_struct_size)
{
png_destroy_struct(info_ptr);
info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
*ptr_ptr = info_ptr;
}
/* Set everything to 0 */
png_memset(info_ptr, 0, png_sizeof(png_info));
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
{
png_infop info_ptr = *ptr_ptr;
png_debug(1, "in png_info_init_3");
if (info_ptr == NULL)
return;
if (png_sizeof(png_info) > png_info_struct_size)
{
png_destroy_struct(info_ptr);
info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
*ptr_ptr = info_ptr;
if (info_ptr == NULL)
return;
}
/* Set everything to 0 */
png_memset(info_ptr, 0, png_sizeof(png_info));
}
| 172,163 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderFrameImpl::DidAddMessageToConsole(
const blink::WebConsoleMessage& message,
const blink::WebString& source_name,
unsigned source_line,
const blink::WebString& stack_trace) {
logging::LogSeverity log_severity = logging::LOG_VERBOSE;
switch (message.level) {
case blink::mojom::ConsoleMessageLevel::kVerbose:
log_severity = logging::LOG_VERBOSE;
break;
case blink::mojom::ConsoleMessageLevel::kInfo:
log_severity = logging::LOG_INFO;
break;
case blink::mojom::ConsoleMessageLevel::kWarning:
log_severity = logging::LOG_WARNING;
break;
case blink::mojom::ConsoleMessageLevel::kError:
log_severity = logging::LOG_ERROR;
break;
default:
log_severity = logging::LOG_VERBOSE;
}
if (ShouldReportDetailedMessageForSource(source_name)) {
for (auto& observer : observers_) {
observer.DetailedConsoleMessageAdded(
message.text.Utf16(), source_name.Utf16(), stack_trace.Utf16(),
source_line, static_cast<uint32_t>(log_severity));
}
}
Send(new FrameHostMsg_DidAddMessageToConsole(
routing_id_, static_cast<int32_t>(log_severity), message.text.Utf16(),
static_cast<int32_t>(source_line), source_name.Utf16()));
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416 | void RenderFrameImpl::DidAddMessageToConsole(
const blink::WebConsoleMessage& message,
const blink::WebString& source_name,
unsigned source_line,
const blink::WebString& stack_trace) {
logging::LogSeverity log_severity = logging::LOG_VERBOSE;
switch (message.level) {
case blink::mojom::ConsoleMessageLevel::kVerbose:
log_severity = logging::LOG_VERBOSE;
break;
case blink::mojom::ConsoleMessageLevel::kInfo:
log_severity = logging::LOG_INFO;
break;
case blink::mojom::ConsoleMessageLevel::kWarning:
log_severity = logging::LOG_WARNING;
break;
case blink::mojom::ConsoleMessageLevel::kError:
log_severity = logging::LOG_ERROR;
break;
default:
log_severity = logging::LOG_VERBOSE;
}
if (ShouldReportDetailedMessageForSource(source_name)) {
for (auto& observer : observers_) {
observer.DetailedConsoleMessageAdded(
message.text.Utf16(), source_name.Utf16(), stack_trace.Utf16(),
source_line, static_cast<uint32_t>(log_severity));
}
}
GetFrameHost()->DidAddMessageToConsole(message.level, message.text.Utf16(),
static_cast<int32_t>(source_line),
source_name.Utf16());
}
| 172,488 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 update_rate_histogram(struct rate_hist *hist,
const vpx_codec_enc_cfg_t *cfg,
const vpx_codec_cx_pkt_t *pkt) {
int i;
int64_t then = 0;
int64_t avg_bitrate = 0;
int64_t sum_sz = 0;
const int64_t now = pkt->data.frame.pts * 1000 *
(uint64_t)cfg->g_timebase.num /
(uint64_t)cfg->g_timebase.den;
int idx = hist->frames++ % hist->samples;
hist->pts[idx] = now;
hist->sz[idx] = (int)pkt->data.frame.sz;
if (now < cfg->rc_buf_initial_sz)
return;
then = now;
/* Sum the size over the past rc_buf_sz ms */
for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
const int i_idx = (i - 1) % hist->samples;
then = hist->pts[i_idx];
if (now - then > cfg->rc_buf_sz)
break;
sum_sz += hist->sz[i_idx];
}
if (now == then)
return;
avg_bitrate = sum_sz * 8 * 1000 / (now - then);
idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
if (idx < 0)
idx = 0;
if (idx > RATE_BINS - 1)
idx = RATE_BINS - 1;
if (hist->bucket[idx].low > avg_bitrate)
hist->bucket[idx].low = (int)avg_bitrate;
if (hist->bucket[idx].high < avg_bitrate)
hist->bucket[idx].high = (int)avg_bitrate;
hist->bucket[idx].count++;
hist->total++;
}
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 update_rate_histogram(struct rate_hist *hist,
const vpx_codec_enc_cfg_t *cfg,
const vpx_codec_cx_pkt_t *pkt) {
int i;
int64_t then = 0;
int64_t avg_bitrate = 0;
int64_t sum_sz = 0;
const int64_t now = pkt->data.frame.pts * 1000 *
(uint64_t)cfg->g_timebase.num /
(uint64_t)cfg->g_timebase.den;
int idx = hist->frames++ % hist->samples;
hist->pts[idx] = now;
hist->sz[idx] = (int)pkt->data.frame.sz;
if (now < cfg->rc_buf_initial_sz)
return;
if (!cfg->rc_target_bitrate)
return;
then = now;
/* Sum the size over the past rc_buf_sz ms */
for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
const int i_idx = (i - 1) % hist->samples;
then = hist->pts[i_idx];
if (now - then > cfg->rc_buf_sz)
break;
sum_sz += hist->sz[i_idx];
}
if (now == then)
return;
avg_bitrate = sum_sz * 8 * 1000 / (now - then);
idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
if (idx < 0)
idx = 0;
if (idx > RATE_BINS - 1)
idx = RATE_BINS - 1;
if (hist->bucket[idx].low > avg_bitrate)
hist->bucket[idx].low = (int)avg_bitrate;
if (hist->bucket[idx].high < avg_bitrate)
hist->bucket[idx].high = (int)avg_bitrate;
hist->bucket[idx].count++;
hist->total++;
}
| 174,500 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Map U+0909 and U+0993 to 3 when checking for confusables
U+0909 (उ) and U+0993 (ও) look similar to the number 3. Thic cl adds
these two characters to the mapping to 3 when determining whether to
fall back to punycode when displaying URLs.
Bug: 895885
Change-Id: I233127570c8e34e791ef5663c1ece9207d6c7bda
Reviewed-on: https://chromium-review.googlesource.com/c/1287031
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#600544}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0437 (з), U+0499 (ҙ), U+04E1 (ӡ), U+0909 (उ), U+0993 (ও),
// U+1012 (ဒ), U+10D5 (ვ), U+10DE (პ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_png_set_expand_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
* depth is at least 8 already.
*/
return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_expand_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
* depth is at least 8 already.
*/
return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
}
| 173,629 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AudioOutputAuthorizationHandlerTest() {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
thread_bundle_ = base::MakeUnique<TestBrowserThreadBundle>(
TestBrowserThreadBundle::Options::REAL_IO_THREAD);
audio_thread_ = base::MakeUnique<AudioManagerThread>();
audio_manager_.reset(new media::FakeAudioManager(
audio_thread_->task_runner(), audio_thread_->worker_task_runner(),
&log_factory_));
media_stream_manager_ =
base::MakeUnique<MediaStreamManager>(audio_manager_.get());
SyncWithAllThreads();
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | AudioOutputAuthorizationHandlerTest() {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
thread_bundle_ = base::MakeUnique<TestBrowserThreadBundle>(
TestBrowserThreadBundle::Options::REAL_IO_THREAD);
audio_thread_ = base::MakeUnique<AudioManagerThread>();
audio_manager_.reset(new media::FakeAudioManager(
audio_thread_->task_runner(), audio_thread_->worker_task_runner(),
&log_factory_));
audio_system_ = media::AudioSystemImpl::Create(audio_manager_.get());
media_stream_manager_ =
base::MakeUnique<MediaStreamManager>(audio_manager_.get());
SyncWithAllThreads();
}
| 171,983 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 generic_permission(struct inode *inode, int mask)
{
int ret;
/*
* Do the basic permission checks.
*/
ret = acl_permission_check(inode, mask);
if (ret != -EACCES)
return ret;
if (S_ISDIR(inode->i_mode)) {
/* DACs are overridable for directories */
if (inode_capable(inode, CAP_DAC_OVERRIDE))
return 0;
if (!(mask & MAY_WRITE))
if (inode_capable(inode, CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/*
* Read/write DACs are always overridable.
* Executable DACs are overridable when there is
* at least one exec bit set.
*/
if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
if (inode_capable(inode, CAP_DAC_OVERRIDE))
return 0;
/*
* Searching includes executable on directories, else just read.
*/
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (mask == MAY_READ)
if (inode_capable(inode, CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | int generic_permission(struct inode *inode, int mask)
{
int ret;
/*
* Do the basic permission checks.
*/
ret = acl_permission_check(inode, mask);
if (ret != -EACCES)
return ret;
if (S_ISDIR(inode->i_mode)) {
/* DACs are overridable for directories */
if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
return 0;
if (!(mask & MAY_WRITE))
if (capable_wrt_inode_uidgid(inode,
CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/*
* Read/write DACs are always overridable.
* Executable DACs are overridable when there is
* at least one exec bit set.
*/
if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
return 0;
/*
* Searching includes executable on directories, else just read.
*/
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (mask == MAY_READ)
if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
| 166,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr;
struct sock *sk = sock->sk;
struct l2cap_chan *chan = l2cap_pi(sk)->chan;
BT_DBG("sock %p, sk %p", sock, sk);
addr->sa_family = AF_BLUETOOTH;
*len = sizeof(struct sockaddr_l2);
if (peer) {
la->l2_psm = chan->psm;
bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst);
la->l2_cid = cpu_to_le16(chan->dcid);
} else {
la->l2_psm = chan->sport;
bacpy(&la->l2_bdaddr, &bt_sk(sk)->src);
la->l2_cid = cpu_to_le16(chan->scid);
}
return 0;
}
Commit Message: Bluetooth: L2CAP - Fix info leak via getsockname()
The L2CAP code fails to initialize the l2_bdaddr_type member of struct
sockaddr_l2 and the padding byte added for alignment. It that for leaks
two bytes kernel stack via the getsockname() syscall. Add an explicit
memset(0) before filling the structure to avoid the info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Marcel Holtmann <[email protected]>
Cc: Gustavo Padovan <[email protected]>
Cc: Johan Hedberg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr;
struct sock *sk = sock->sk;
struct l2cap_chan *chan = l2cap_pi(sk)->chan;
BT_DBG("sock %p, sk %p", sock, sk);
memset(la, 0, sizeof(struct sockaddr_l2));
addr->sa_family = AF_BLUETOOTH;
*len = sizeof(struct sockaddr_l2);
if (peer) {
la->l2_psm = chan->psm;
bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst);
la->l2_cid = cpu_to_le16(chan->dcid);
} else {
la->l2_psm = chan->sport;
bacpy(&la->l2_bdaddr, &bt_sk(sk)->src);
la->l2_cid = cpu_to_le16(chan->scid);
}
return 0;
}
| 169,899 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool mkvparser::Match(
IMkvReader* pReader,
long long& pos,
unsigned long id_,
long long& val)
{
assert(pReader);
assert(pos >= 0);
long long total, available;
const long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; //consume id
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert(size <= 8);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; //consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
assert(val >= 0);
pos += size; //consume size of payload
return true;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool mkvparser::Match(
long long total, available;
const long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; // consume id
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert(size <= 8);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; // consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
assert(val >= 0);
pos += size; // consume size of payload
return true;
}
| 174,398 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rpc_type_of_NPPVariable(int variable)
{
int type;
switch (variable) {
case NPPVpluginNameString:
case NPPVpluginDescriptionString:
case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000
type = RPC_TYPE_STRING;
break;
case NPPVpluginWindowSize:
case NPPVpluginTimerInterval:
type = RPC_TYPE_INT32;
break;
case NPPVpluginNeedsXEmbed:
case NPPVpluginWindowBool:
case NPPVpluginTransparentBool:
case NPPVjavascriptPushCallerBool:
case NPPVpluginKeepLibraryInMemory:
type = RPC_TYPE_BOOLEAN;
break;
case NPPVpluginScriptableNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264 | int rpc_type_of_NPPVariable(int variable)
{
int type;
switch (variable) {
case NPPVpluginNameString:
case NPPVpluginDescriptionString:
case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000
case NPPVpluginNativeAccessibleAtkPlugId:
type = RPC_TYPE_STRING;
break;
case NPPVpluginWindowSize:
case NPPVpluginTimerInterval:
type = RPC_TYPE_INT32;
break;
case NPPVpluginNeedsXEmbed:
case NPPVpluginWindowBool:
case NPPVpluginTransparentBool:
case NPPVjavascriptPushCallerBool:
case NPPVpluginKeepLibraryInMemory:
case NPPVpluginUrlRequestsDisplayedBool:
case NPPVpluginWantsAllNetworkStreams:
case NPPVpluginCancelSrcStream:
case NPPVSupportsAdvancedKeyHandling:
type = RPC_TYPE_BOOLEAN;
break;
case NPPVpluginScriptableNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
| 165,863 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) {
char * name = NULL;
int rtnVal = FALSE;
bool found_cred=false;
CredentialWrapper * cred = NULL;
char * owner = NULL;
const char * user = NULL;
void * data = NULL;
ReliSock * socket = (ReliSock*)stream;
if (!socket->triedAuthentication()) {
CondorError errstack;
if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) {
dprintf (D_ALWAYS, "Unable to authenticate, qutting\n");
goto EXIT;
}
}
socket->decode();
if (!socket->code(name)) {
dprintf (D_ALWAYS, "Error receiving credential name\n");
goto EXIT;
}
user = socket->getFullyQualifiedUser();
dprintf (D_ALWAYS, "Authenticated as %s\n", user);
if (strchr (name, ':')) {
owner = strdup (name);
char * pColon = strchr (owner, ':');
*pColon = '\0';
sprintf (name, (char*)(pColon+sizeof(char)));
if (strcmp (owner, user) != 0) {
dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name);
if (!isSuperUser (user)) {
dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user);
goto EXIT;
} else {
dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user);
}
}
} else {
owner = strdup (user);
}
dprintf (D_ALWAYS, "sending cred %s for user %s\n", name, owner);
credentials.Rewind();
while (credentials.Next(cred)) {
if (cred->cred->GetType() == X509_CREDENTIAL_TYPE) {
if ((strcmp(cred->cred->GetName(), name) == 0) &&
(strcmp(cred->cred->GetOwner(), owner) == 0)) {
found_cred=true;
break; // found it
}
}
}
socket->encode();
if (found_cred) {
dprintf (D_FULLDEBUG, "Found cred %s\n", cred->GetStorageName());
int data_size;
int rc = LoadData (cred->GetStorageName(), data, data_size);
dprintf (D_FULLDEBUG, "Credential::LoadData returned %d\n", rc);
if (rc == 0) {
goto EXIT;
}
socket->code (data_size);
socket->code_bytes (data, data_size);
dprintf (D_ALWAYS, "Credential name %s for owner %s returned to user %s\n",
name, owner, user);
}
else {
dprintf (D_ALWAYS, "Cannot find cred %s\n", name);
int rc = CREDD_CREDENTIAL_NOT_FOUND;
socket->code (rc);
}
rtnVal = TRUE;
EXIT:
if ( name != NULL) {
free (name);
}
if ( owner != NULL) {
free (owner);
}
if ( data != NULL) {
free (data);
}
return rtnVal;
}
Commit Message:
CWE ID: CWE-134 | get_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) {
char * name = NULL;
int rtnVal = FALSE;
bool found_cred=false;
CredentialWrapper * cred = NULL;
char * owner = NULL;
const char * user = NULL;
void * data = NULL;
ReliSock * socket = (ReliSock*)stream;
if (!socket->triedAuthentication()) {
CondorError errstack;
if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) {
dprintf (D_ALWAYS, "Unable to authenticate, qutting\n");
goto EXIT;
}
}
socket->decode();
if (!socket->code(name)) {
dprintf (D_ALWAYS, "Error receiving credential name\n");
goto EXIT;
}
user = socket->getFullyQualifiedUser();
dprintf (D_ALWAYS, "Authenticated as %s\n", user);
if (strchr (name, ':')) {
owner = strdup (name);
char * pColon = strchr (owner, ':');
*pColon = '\0';
sprintf (name, "%s", (char*)(pColon+sizeof(char)));
if (strcmp (owner, user) != 0) {
dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name);
if (!isSuperUser (user)) {
dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user);
goto EXIT;
} else {
dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user);
}
}
} else {
owner = strdup (user);
}
dprintf (D_ALWAYS, "sending cred %s for user %s\n", name, owner);
credentials.Rewind();
while (credentials.Next(cred)) {
if (cred->cred->GetType() == X509_CREDENTIAL_TYPE) {
if ((strcmp(cred->cred->GetName(), name) == 0) &&
(strcmp(cred->cred->GetOwner(), owner) == 0)) {
found_cred=true;
break; // found it
}
}
}
socket->encode();
if (found_cred) {
dprintf (D_FULLDEBUG, "Found cred %s\n", cred->GetStorageName());
int data_size;
int rc = LoadData (cred->GetStorageName(), data, data_size);
dprintf (D_FULLDEBUG, "Credential::LoadData returned %d\n", rc);
if (rc == 0) {
goto EXIT;
}
socket->code (data_size);
socket->code_bytes (data, data_size);
dprintf (D_ALWAYS, "Credential name %s for owner %s returned to user %s\n",
name, owner, user);
}
else {
dprintf (D_ALWAYS, "Cannot find cred %s\n", name);
int rc = CREDD_CREDENTIAL_NOT_FOUND;
socket->code (rc);
}
rtnVal = TRUE;
EXIT:
if ( name != NULL) {
free (name);
}
if ( owner != NULL) {
free (owner);
}
if ( data != NULL) {
free (data);
}
return rtnVal;
}
| 165,371 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_;
}
if (i == 0) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = mask_;
} else if (i == 1) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -mask_;
}
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j]))
<< "Error: 4x4 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
| 174,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlBufCreateStatic(void *mem, size_t size) {
xmlBufPtr ret;
if ((mem == NULL) || (size == 0))
return(NULL);
ret = (xmlBufPtr) xmlMalloc(sizeof(xmlBuf));
if (ret == NULL) {
xmlBufMemoryError(NULL, "creating buffer");
return(NULL);
}
if (size < INT_MAX) {
ret->compat_use = size;
ret->compat_size = size;
} else {
ret->compat_use = INT_MAX;
ret->compat_size = INT_MAX;
}
ret->use = size;
ret->size = size;
ret->alloc = XML_BUFFER_ALLOC_IMMUTABLE;
ret->content = (xmlChar *) mem;
ret->error = 0;
ret->buffer = NULL;
return(ret);
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <[email protected]>
Commit-Queue: Dominic Cooney <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787 | xmlBufCreateStatic(void *mem, size_t size) {
xmlBufPtr ret;
if (mem == NULL)
return(NULL);
ret = (xmlBufPtr) xmlMalloc(sizeof(xmlBuf));
if (ret == NULL) {
xmlBufMemoryError(NULL, "creating buffer");
return(NULL);
}
if (size < INT_MAX) {
ret->compat_use = size;
ret->compat_size = size;
} else {
ret->compat_use = INT_MAX;
ret->compat_size = INT_MAX;
}
ret->use = size;
ret->size = size;
ret->alloc = XML_BUFFER_ALLOC_IMMUTABLE;
ret->content = (xmlChar *) mem;
ret->error = 0;
ret->buffer = NULL;
return(ret);
}
| 172,949 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pcf_read_TOC( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
PCF_Toc toc = &face->toc;
PCF_Table tables;
FT_Memory memory = FT_FACE( face )->memory;
FT_UInt n;
if ( FT_STREAM_SEEK ( 0 ) ||
FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) )
return FT_THROW( Cannot_Open_Resource );
if ( toc->version != PCF_FILE_VERSION ||
toc->count > FT_ARRAY_MAX( face->toc.tables ) ||
toc->count == 0 )
return FT_THROW( Invalid_File_Format );
if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) )
return FT_THROW( Out_Of_Memory );
tables = face->toc.tables;
for ( n = 0; n < toc->count; n++ )
{
if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) )
goto Exit;
tables++;
}
/* Sort tables and check for overlaps. Because they are almost */
/* always ordered already, an in-place bubble sort with simultaneous */
/* boundary checking seems appropriate. */
tables = face->toc.tables;
for ( n = 0; n < toc->count - 1; n++ )
{
FT_UInt i, have_change;
have_change = 0;
for ( i = 0; i < toc->count - 1 - n; i++ )
{
PCF_TableRec tmp;
if ( tables[i].offset > tables[i + 1].offset )
{
tmp = tables[i];
tables[i] = tables[i + 1];
tables[i + 1] = tmp;
have_change = 1;
}
if ( ( tables[i].size > tables[i + 1].offset ) ||
( tables[i].offset > tables[i + 1].offset - tables[i].size ) )
{
error = FT_THROW( Invalid_Offset );
goto Exit;
}
}
if ( !have_change )
break;
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_TRACE4(( " %d: type=%s, format=0x%X, "
"size=%ld (0x%lX), offset=%ld (0x%lX)\n",
i, name,
tables[i].format,
tables[i].size, tables[i].size,
tables[i].offset, tables[i].offset ));
}
}
Commit Message:
CWE ID: | pcf_read_TOC( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
PCF_Toc toc = &face->toc;
PCF_Table tables;
FT_Memory memory = FT_FACE( face )->memory;
FT_UInt n;
if ( FT_STREAM_SEEK ( 0 ) ||
FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) )
return FT_THROW( Cannot_Open_Resource );
if ( toc->version != PCF_FILE_VERSION ||
toc->count > FT_ARRAY_MAX( face->toc.tables ) ||
toc->count == 0 )
return FT_THROW( Invalid_File_Format );
if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) )
return FT_THROW( Out_Of_Memory );
tables = face->toc.tables;
for ( n = 0; n < toc->count; n++ )
{
if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) )
goto Exit;
tables++;
}
/* Sort tables and check for overlaps. Because they are almost */
/* always ordered already, an in-place bubble sort with simultaneous */
/* boundary checking seems appropriate. */
tables = face->toc.tables;
for ( n = 0; n < toc->count - 1; n++ )
{
FT_UInt i, have_change;
have_change = 0;
for ( i = 0; i < toc->count - 1 - n; i++ )
{
PCF_TableRec tmp;
if ( tables[i].offset > tables[i + 1].offset )
{
tmp = tables[i];
tables[i] = tables[i + 1];
tables[i + 1] = tmp;
have_change = 1;
}
if ( ( tables[i].size > tables[i + 1].offset ) ||
( tables[i].offset > tables[i + 1].offset - tables[i].size ) )
{
error = FT_THROW( Invalid_Offset );
goto Exit;
}
}
if ( !have_change )
break;
}
/* we now check whether the `size' and `offset' values are reasonable: */
/* `offset' + `size' must not exceed the stream size */
tables = face->toc.tables;
for ( n = 0; n < toc->count; n++ )
{
/* we need two checks to avoid overflow */
if ( ( tables->size > stream->size ) ||
( tables->offset > stream->size - tables->size ) )
{
error = FT_THROW( Invalid_Table );
goto Exit;
}
tables++;
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_TRACE4(( " %d: type=%s, format=0x%X, "
"size=%ld (0x%lX), offset=%ld (0x%lX)\n",
i, name,
tables[i].format,
tables[i].size, tables[i].size,
tables[i].offset, tables[i].offset ));
}
}
| 164,843 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_png_set_background_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_byte colour_type, bit_depth;
png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
int expand;
png_color_16 back;
/* We need a background colour, because we don't know exactly what transforms
* have been set we have to supply the colour in the original file format and
* so we need to know what that is! The background colour is stored in the
* transform_display.
*/
RANDOMIZE(random_bytes);
/* Read the random value, for colour type 3 the background colour is actually
* expressed as a 24bit rgb, not an index.
*/
colour_type = that->this.colour_type;
if (colour_type == 3)
{
colour_type = PNG_COLOR_TYPE_RGB;
bit_depth = 8;
expand = 0; /* passing in an RGB not a pixel index */
}
else
{
bit_depth = that->this.bit_depth;
expand = 1;
}
image_pixel_init(&data, random_bytes, colour_type,
bit_depth, 0/*x*/, 0/*unused: palette*/);
/* Extract the background colour from this image_pixel, but make sure the
* unused fields of 'back' are garbage.
*/
RANDOMIZE(back);
if (colour_type & PNG_COLOR_MASK_COLOR)
{
back.red = (png_uint_16)data.red;
back.green = (png_uint_16)data.green;
back.blue = (png_uint_16)data.blue;
}
else
back.gray = (png_uint_16)data.red;
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# else
png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# endif
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_background_set(PNG_CONST image_transform *this,
image_transform_png_set_background_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_byte colour_type, bit_depth;
png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
int expand;
png_color_16 back;
/* We need a background colour, because we don't know exactly what transforms
* have been set we have to supply the colour in the original file format and
* so we need to know what that is! The background colour is stored in the
* transform_display.
*/
RANDOMIZE(random_bytes);
/* Read the random value, for colour type 3 the background colour is actually
* expressed as a 24bit rgb, not an index.
*/
colour_type = that->this.colour_type;
if (colour_type == 3)
{
colour_type = PNG_COLOR_TYPE_RGB;
bit_depth = 8;
expand = 0; /* passing in an RGB not a pixel index */
}
else
{
if (that->this.has_tRNS)
that->this.is_transparent = 1;
bit_depth = that->this.bit_depth;
expand = 1;
}
image_pixel_init(&data, random_bytes, colour_type,
bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
/* Extract the background colour from this image_pixel, but make sure the
* unused fields of 'back' are garbage.
*/
RANDOMIZE(back);
if (colour_type & PNG_COLOR_MASK_COLOR)
{
back.red = (png_uint_16)data.red;
back.green = (png_uint_16)data.green;
back.blue = (png_uint_16)data.blue;
}
else
back.gray = (png_uint_16)data.red;
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# else
png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,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: static void copy_fields(const FieldMatchContext *fm, AVFrame *dst,
const AVFrame *src, int field)
{
int plane;
for (plane = 0; plane < 4 && src->data[plane]; plane++)
av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1,
src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1,
get_width(fm, src, plane), get_height(fm, src, plane) / 2);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static void copy_fields(const FieldMatchContext *fm, AVFrame *dst,
const AVFrame *src, int field)
{
int plane;
for (plane = 0; plane < 4 && src->data[plane] && src->linesize[plane]; plane++)
av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1,
src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1,
get_width(fm, src, plane), get_height(fm, src, plane) / 2);
}
| 165,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_client_master_key(SSL *s)
{
int is_export, i, n, keya;
unsigned int num_encrypted_key_bytes, key_length;
unsigned long len;
unsigned char *p;
const SSL_CIPHER *cp;
const EVP_CIPHER *c;
const EVP_MD *md;
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
unsigned char decrypt_good;
size_t j;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num);
if (i < (10 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
s->init_num = 10;
if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR);
return (-1);
}
cp = ssl2_get_cipher_by_char(p);
if (cp == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH);
return (-1);
}
s->session->cipher = cp;
p += 3;
n2s(p, i);
s->s2->tmp.clear = i;
n2s(p, i);
s->s2->tmp.enc = i;
n2s(p, i);
if (i > SSL_MAX_KEY_ARG_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG);
return -1;
}
s->session->key_arg_length = i;
s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B;
}
/* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
p = (unsigned char *)s->init_buf->data;
if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
keya = s->session->key_arg_length;
len =
10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc +
(unsigned long)keya;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
if (s->msg_callback) {
/* CLIENT-MASTER-KEY */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 10;
memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]),
(unsigned int)keya);
if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY);
return (-1);
}
is_export = SSL_C_IS_EXPORT(s->session->cipher);
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (0);
}
/*
* The format of the CLIENT-MASTER-KEY message is
* 1 byte message type
* 3 bytes cipher
* 2-byte clear key length (stored in s->s2->tmp.clear)
* 2-byte encrypted key length (stored in s->s2->tmp.enc)
* 2-byte key args length (IV etc)
* clear key
* encrypted key
* key args
*
* If the cipher is an export cipher, then the encrypted key bytes
* are a fixed portion of the total key (5 or 8 bytes). The size of
* this portion is in |num_encrypted_key_bytes|. If the cipher is not an
* export cipher, then the entire key material is encrypted (i.e., clear
* key length must be zero).
*/
key_length = (unsigned int)EVP_CIPHER_key_length(c);
if (key_length > SSL_MAX_MASTER_KEY_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) {
is_export = 1;
num_encrypted_key_bytes = 8;
} else if (is_export) {
num_encrypted_key_bytes = 5;
} else {
num_encrypted_key_bytes = key_length;
}
if (s->s2->tmp.clear + num_encrypted_key_bytes != key_length) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH);
return -1;
}
/*
* The encrypted blob must decrypt to the encrypted portion of the key.
* Decryption can't be expanding, so if we don't have enough encrypted
* bytes to fit the key in the buffer, stop now.
*/
if (s->s2->tmp.enc < num_encrypted_key_bytes) {
ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT);
return -1;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
/*
* should be RAND_bytes, but we cannot work around a failure.
*/
if (RAND_pseudo_bytes(rand_premaster_secret,
(int)num_encrypted_key_bytes) <= 0)
return 0;
i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc,
&(p[s->s2->tmp.clear]),
&(p[s->s2->tmp.clear]),
(s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING :
RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* If a bad decrypt, continue with protocol but with a random master
* secret (Bleichenbacher attack)
*/
decrypt_good = constant_time_eq_int_8(i, (int)num_encrypted_key_bytes);
for (j = 0; j < num_encrypted_key_bytes; j++) {
p[s->s2->tmp.clear + j] =
constant_time_select_8(decrypt_good, p[s->s2->tmp.clear + j],
rand_premaster_secret[j]);
}
s->session->master_key_length = (int)key_length;
memcpy(s->session->master_key, p, key_length);
OPENSSL_cleanse(p, key_length);
return 1;
}
Commit Message:
CWE ID: CWE-310 | static int get_client_master_key(SSL *s)
{
int is_export, i, n, keya;
unsigned int num_encrypted_key_bytes, key_length;
unsigned long len;
unsigned char *p;
const SSL_CIPHER *cp;
const EVP_CIPHER *c;
const EVP_MD *md;
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
unsigned char decrypt_good;
size_t j;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num);
if (i < (10 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
s->init_num = 10;
if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR);
return (-1);
}
cp = ssl2_get_cipher_by_char(p);
if (cp == NULL || sk_SSL_CIPHER_find(s->session->ciphers, cp) < 0) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH);
return (-1);
}
s->session->cipher = cp;
p += 3;
n2s(p, i);
s->s2->tmp.clear = i;
n2s(p, i);
s->s2->tmp.enc = i;
n2s(p, i);
if (i > SSL_MAX_KEY_ARG_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG);
return -1;
}
s->session->key_arg_length = i;
s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B;
}
/* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
p = (unsigned char *)s->init_buf->data;
if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
keya = s->session->key_arg_length;
len =
10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc +
(unsigned long)keya;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
if (s->msg_callback) {
/* CLIENT-MASTER-KEY */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 10;
memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]),
(unsigned int)keya);
if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY);
return (-1);
}
is_export = SSL_C_IS_EXPORT(s->session->cipher);
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (0);
}
/*
* The format of the CLIENT-MASTER-KEY message is
* 1 byte message type
* 3 bytes cipher
* 2-byte clear key length (stored in s->s2->tmp.clear)
* 2-byte encrypted key length (stored in s->s2->tmp.enc)
* 2-byte key args length (IV etc)
* clear key
* encrypted key
* key args
*
* If the cipher is an export cipher, then the encrypted key bytes
* are a fixed portion of the total key (5 or 8 bytes). The size of
* this portion is in |num_encrypted_key_bytes|. If the cipher is not an
* export cipher, then the entire key material is encrypted (i.e., clear
* key length must be zero).
*/
key_length = (unsigned int)EVP_CIPHER_key_length(c);
if (key_length > SSL_MAX_MASTER_KEY_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) {
is_export = 1;
num_encrypted_key_bytes = 8;
} else if (is_export) {
num_encrypted_key_bytes = 5;
} else {
num_encrypted_key_bytes = key_length;
}
if (s->s2->tmp.clear + num_encrypted_key_bytes != key_length) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH);
return -1;
}
/*
* The encrypted blob must decrypt to the encrypted portion of the key.
* Decryption can't be expanding, so if we don't have enough encrypted
* bytes to fit the key in the buffer, stop now.
*/
if (s->s2->tmp.enc < num_encrypted_key_bytes) {
ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT);
return -1;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
/*
* should be RAND_bytes, but we cannot work around a failure.
*/
if (RAND_pseudo_bytes(rand_premaster_secret,
(int)num_encrypted_key_bytes) <= 0)
return 0;
i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc,
&(p[s->s2->tmp.clear]),
&(p[s->s2->tmp.clear]),
(s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING :
RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* If a bad decrypt, continue with protocol but with a random master
* secret (Bleichenbacher attack)
*/
decrypt_good = constant_time_eq_int_8(i, (int)num_encrypted_key_bytes);
for (j = 0; j < num_encrypted_key_bytes; j++) {
p[s->s2->tmp.clear + j] =
constant_time_select_8(decrypt_good, p[s->s2->tmp.clear + j],
rand_premaster_secret[j]);
}
s->session->master_key_length = (int)key_length;
memcpy(s->session->master_key, p, key_length);
OPENSSL_cleanse(p, key_length);
return 1;
}
| 165,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
}
Commit Message: Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-200 | usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
}
| 168,984 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_value_set_string (value, mobject->this_is_a_string);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
Commit Message:
CWE ID: CWE-264 | my_object_get_property (GObject *object,
| 165,102 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 check_line_charstring(void)
{
char *p = line;
while (isspace(*p))
p++;
return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p'));
}
Commit Message: Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.
CWE ID: CWE-119 | static int check_line_charstring(void)
{
char *p = line;
while (isspace((unsigned char) *p))
p++;
return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p'));
}
| 166,620 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 l2cap_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {
err = -EBADFD;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
if (!l2cap_pi(sk)->psm) {
bdaddr_t *src = &bt_sk(sk)->src;
u16 psm;
err = -EINVAL;
write_lock_bh(&l2cap_sk_list.lock);
for (psm = 0x1001; psm < 0x1100; psm += 2)
if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {
l2cap_pi(sk)->psm = cpu_to_le16(psm);
l2cap_pi(sk)->sport = cpu_to_le16(psm);
err = 0;
break;
}
write_unlock_bh(&l2cap_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static int l2cap_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {
err = -EBADFD;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
case L2CAP_MODE_STREAMING:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
if (!l2cap_pi(sk)->psm) {
bdaddr_t *src = &bt_sk(sk)->src;
u16 psm;
err = -EINVAL;
write_lock_bh(&l2cap_sk_list.lock);
for (psm = 0x1001; psm < 0x1100; psm += 2)
if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {
l2cap_pi(sk)->psm = cpu_to_le16(psm);
l2cap_pi(sk)->sport = cpu_to_le16(psm);
err = 0;
break;
}
write_unlock_bh(&l2cap_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
| 167,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: AP_DECLARE(int) ap_process_request_internal(request_rec *r)
{
int file_req = (r->main && r->filename);
int access_status;
core_dir_config *d;
/* Ignore embedded %2F's in path for proxy requests */
if (!r->proxyreq && r->parsed_uri.path) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->allow_encoded_slashes) {
access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes);
}
else {
access_status = ap_unescape_url(r->parsed_uri.path);
}
if (access_status) {
if (access_status == HTTP_NOT_FOUND) {
if (! d->allow_encoded_slashes) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026)
"found %%2f (encoded '/') in URI "
"(decoded='%s'), returning 404",
r->parsed_uri.path);
}
}
return access_status;
}
}
ap_getparents(r->uri); /* OK --- shrinking transformations... */
/* All file subrequests are a huge pain... they cannot bubble through the
* next several steps. Only file subrequests are allowed an empty uri,
* otherwise let translate_name kill the request.
*/
if (!file_req) {
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_if_walk(r))) {
return access_status;
}
/* Don't set per-dir loglevel if LogLevelOverride is set */
if (!r->connection->log) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->log)
r->log = d->log;
}
if ((access_status = ap_run_translate_name(r))) {
return decl_die(access_status, "translate", r);
}
}
/* Reset to the server default config prior to running map_to_storage
*/
r->per_dir_config = r->server->lookup_defaults;
if ((access_status = ap_run_map_to_storage(r))) {
/* This request wasn't in storage (e.g. TRACE) */
return access_status;
}
/* Rerun the location walk, which overrides any map_to_storage config.
*/
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_if_walk(r))) {
return access_status;
}
/* Don't set per-dir loglevel if LogLevelOverride is set */
if (!r->connection->log) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->log)
r->log = d->log;
}
if ((access_status = ap_run_post_perdir_config(r))) {
return access_status;
}
/* Only on the main request! */
if (r->main == NULL) {
if ((access_status = ap_run_header_parser(r))) {
return access_status;
}
}
/* Skip authn/authz if the parent or prior request passed the authn/authz,
* and that configuration didn't change (this requires optimized _walk()
* functions in map_to_storage that use the same merge results given
* identical input.) If the config changes, we must re-auth.
*/
if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {
r->user = r->prev->user;
r->ap_auth_type = r->prev->ap_auth_type;
}
else if (r->main && (r->main->per_dir_config == r->per_dir_config)) {
r->user = r->main->user;
r->ap_auth_type = r->main->ap_auth_type;
}
else {
switch (ap_satisfies(r)) {
case SATISFY_ALL:
case SATISFY_NOSPEC:
if ((access_status = ap_run_access_checker(r)) != OK) {
return decl_die(access_status,
"check access (with Satisfy All)", r);
}
access_status = ap_run_access_checker_ex(r);
if (access_status == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker_ex hook: %s", r->uri);
}
else if (access_status != DECLINED) {
return decl_die(access_status, "check access", r);
}
else {
if ((access_status = ap_run_check_user_id(r)) != OK) {
return decl_die(access_status, "check user", r);
}
if (r->user == NULL) {
/* don't let buggy authn module crash us in authz */
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027)
"No authentication done but request not "
"allowed without authentication for %s. "
"Authentication not configured?",
r->uri);
access_status = HTTP_INTERNAL_SERVER_ERROR;
return decl_die(access_status, "check user", r);
}
if ((access_status = ap_run_auth_checker(r)) != OK) {
return decl_die(access_status, "check authorization", r);
}
}
break;
case SATISFY_ANY:
if ((access_status = ap_run_access_checker(r)) == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker hook and 'Satisfy any': %s",
r->uri);
break;
}
access_status = ap_run_access_checker_ex(r);
if (access_status == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker_ex hook: %s", r->uri);
}
else if (access_status != DECLINED) {
return decl_die(access_status, "check access", r);
}
else {
if ((access_status = ap_run_check_user_id(r)) != OK) {
return decl_die(access_status, "check user", r);
}
if (r->user == NULL) {
/* don't let buggy authn module crash us in authz */
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028)
"No authentication done but request not "
"allowed without authentication for %s. "
"Authentication not configured?",
r->uri);
access_status = HTTP_INTERNAL_SERVER_ERROR;
return decl_die(access_status, "check user", r);
}
if ((access_status = ap_run_auth_checker(r)) != OK) {
return decl_die(access_status, "check authorization", r);
}
}
break;
}
}
/* XXX Must make certain the ap_run_type_checker short circuits mime
* in mod-proxy for r->proxyreq && r->parsed_uri.scheme
* && !strcmp(r->parsed_uri.scheme, "http")
*/
if ((access_status = ap_run_type_checker(r)) != OK) {
return decl_die(access_status, "find types", r);
}
if ((access_status = ap_run_fixups(r)) != OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s",
access_status, r->uri);
return access_status;
}
return OK;
}
Commit Message: SECURITY: CVE-2015-3183 (cve.mitre.org)
Replacement of ap_some_auth_required (unusable in Apache httpd 2.4)
with new ap_some_authn_required and ap_force_authn hook.
Submitted by: breser
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-264 | AP_DECLARE(int) ap_process_request_internal(request_rec *r)
{
int file_req = (r->main && r->filename);
int access_status;
core_dir_config *d;
/* Ignore embedded %2F's in path for proxy requests */
if (!r->proxyreq && r->parsed_uri.path) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->allow_encoded_slashes) {
access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes);
}
else {
access_status = ap_unescape_url(r->parsed_uri.path);
}
if (access_status) {
if (access_status == HTTP_NOT_FOUND) {
if (! d->allow_encoded_slashes) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026)
"found %%2f (encoded '/') in URI "
"(decoded='%s'), returning 404",
r->parsed_uri.path);
}
}
return access_status;
}
}
ap_getparents(r->uri); /* OK --- shrinking transformations... */
/* All file subrequests are a huge pain... they cannot bubble through the
* next several steps. Only file subrequests are allowed an empty uri,
* otherwise let translate_name kill the request.
*/
if (!file_req) {
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_if_walk(r))) {
return access_status;
}
/* Don't set per-dir loglevel if LogLevelOverride is set */
if (!r->connection->log) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->log)
r->log = d->log;
}
if ((access_status = ap_run_translate_name(r))) {
return decl_die(access_status, "translate", r);
}
}
/* Reset to the server default config prior to running map_to_storage
*/
r->per_dir_config = r->server->lookup_defaults;
if ((access_status = ap_run_map_to_storage(r))) {
/* This request wasn't in storage (e.g. TRACE) */
return access_status;
}
/* Rerun the location walk, which overrides any map_to_storage config.
*/
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_if_walk(r))) {
return access_status;
}
/* Don't set per-dir loglevel if LogLevelOverride is set */
if (!r->connection->log) {
d = ap_get_core_module_config(r->per_dir_config);
if (d->log)
r->log = d->log;
}
if ((access_status = ap_run_post_perdir_config(r))) {
return access_status;
}
/* Only on the main request! */
if (r->main == NULL) {
if ((access_status = ap_run_header_parser(r))) {
return access_status;
}
}
/* Skip authn/authz if the parent or prior request passed the authn/authz,
* and that configuration didn't change (this requires optimized _walk()
* functions in map_to_storage that use the same merge results given
* identical input.) If the config changes, we must re-auth.
*/
if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {
r->user = r->prev->user;
r->ap_auth_type = r->prev->ap_auth_type;
}
else if (r->main && (r->main->per_dir_config == r->per_dir_config)) {
r->user = r->main->user;
r->ap_auth_type = r->main->ap_auth_type;
}
else {
switch (ap_satisfies(r)) {
case SATISFY_ALL:
case SATISFY_NOSPEC:
if ((access_status = ap_run_access_checker(r)) != OK) {
return decl_die(access_status,
"check access (with Satisfy All)", r);
}
access_status = ap_run_access_checker_ex(r);
if (access_status == DECLINED
|| (access_status == OK && ap_run_force_authn(r) == OK)) {
if ((access_status = ap_run_check_user_id(r)) != OK) {
return decl_die(access_status, "check user", r);
}
if (r->user == NULL) {
/* don't let buggy authn module crash us in authz */
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027)
"No authentication done but request not "
"allowed without authentication for %s. "
"Authentication not configured?",
r->uri);
access_status = HTTP_INTERNAL_SERVER_ERROR;
return decl_die(access_status, "check user", r);
}
if ((access_status = ap_run_auth_checker(r)) != OK) {
return decl_die(access_status, "check authorization", r);
}
}
else if (access_status == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker_ex hook: %s", r->uri);
}
else {
return decl_die(access_status, "check access", r);
}
break;
case SATISFY_ANY:
if ((access_status = ap_run_access_checker(r)) == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker hook and 'Satisfy any': %s",
r->uri);
break;
}
access_status = ap_run_access_checker_ex(r);
if (access_status == DECLINED
|| (access_status == OK && ap_run_force_authn(r) == OK)) {
if ((access_status = ap_run_check_user_id(r)) != OK) {
return decl_die(access_status, "check user", r);
}
if (r->user == NULL) {
/* don't let buggy authn module crash us in authz */
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028)
"No authentication done but request not "
"allowed without authentication for %s. "
"Authentication not configured?",
r->uri);
access_status = HTTP_INTERNAL_SERVER_ERROR;
return decl_die(access_status, "check user", r);
}
if ((access_status = ap_run_auth_checker(r)) != OK) {
return decl_die(access_status, "check authorization", r);
}
}
else if (access_status == OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"request authorized without authentication by "
"access_checker_ex hook: %s", r->uri);
}
else {
return decl_die(access_status, "check access", r);
}
break;
}
}
/* XXX Must make certain the ap_run_type_checker short circuits mime
* in mod-proxy for r->proxyreq && r->parsed_uri.scheme
* && !strcmp(r->parsed_uri.scheme, "http")
*/
if ((access_status = ap_run_type_checker(r)) != OK) {
return decl_die(access_status, "find types", r);
}
if ((access_status = ap_run_fixups(r)) != OK) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s",
access_status, r->uri);
return access_status;
}
return OK;
}
| 166,632 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __exit xfrm6_tunnel_fini(void)
{
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
xfrm6_tunnel_spi_fini();
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static void __exit xfrm6_tunnel_fini(void)
{
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
}
| 165,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
Commit Message: Block modifier-letter-voicing character from domain names
This character (ˬ) is easy to miss between other characters. It's one of the three characters from Spacing-Modifier-Letters block that ICU lists in its recommended set in uspoof.cpp. Two of these characters (modifier-letter-turned-comma and modifier-letter-apostrophe) are already blocked in crbug/678812.
Bug: 896717
Change-Id: I24b2b591de8cc7822cd55aa005b15676be91175e
Reviewed-on: https://chromium-review.googlesource.com/c/1303037
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604128}
CWE ID: CWE-20 | void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
// Block modifier letter voicing.
allowed_set.remove(0x2ecu);
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
| 172,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119 | ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
| 166,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sp<VBRISeeker> VBRISeeker::CreateFromSource(
const sp<DataSource> &source, off64_t post_id3_pos) {
off64_t pos = post_id3_pos;
uint8_t header[4];
ssize_t n = source->readAt(pos, header, sizeof(header));
if (n < (ssize_t)sizeof(header)) {
return NULL;
}
uint32_t tmp = U32_AT(&header[0]);
size_t frameSize;
int sampleRate;
if (!GetMPEGAudioFrameSize(tmp, &frameSize, &sampleRate)) {
return NULL;
}
pos += sizeof(header) + 32;
uint8_t vbriHeader[26];
n = source->readAt(pos, vbriHeader, sizeof(vbriHeader));
if (n < (ssize_t)sizeof(vbriHeader)) {
return NULL;
}
if (memcmp(vbriHeader, "VBRI", 4)) {
return NULL;
}
size_t numFrames = U32_AT(&vbriHeader[14]);
int64_t durationUs =
numFrames * 1000000ll * (sampleRate >= 32000 ? 1152 : 576) / sampleRate;
ALOGV("duration = %.2f secs", durationUs / 1E6);
size_t numEntries = U16_AT(&vbriHeader[18]);
size_t entrySize = U16_AT(&vbriHeader[22]);
size_t scale = U16_AT(&vbriHeader[20]);
ALOGV("%zu entries, scale=%zu, size_per_entry=%zu",
numEntries,
scale,
entrySize);
size_t totalEntrySize = numEntries * entrySize;
uint8_t *buffer = new uint8_t[totalEntrySize];
n = source->readAt(pos + sizeof(vbriHeader), buffer, totalEntrySize);
if (n < (ssize_t)totalEntrySize) {
delete[] buffer;
buffer = NULL;
return NULL;
}
sp<VBRISeeker> seeker = new VBRISeeker;
seeker->mBasePos = post_id3_pos + frameSize;
if (durationUs) {
seeker->mDurationUs = durationUs;
}
off64_t offset = post_id3_pos;
for (size_t i = 0; i < numEntries; ++i) {
uint32_t numBytes;
switch (entrySize) {
case 1: numBytes = buffer[i]; break;
case 2: numBytes = U16_AT(buffer + 2 * i); break;
case 3: numBytes = U24_AT(buffer + 3 * i); break;
default:
{
CHECK_EQ(entrySize, 4u);
numBytes = U32_AT(buffer + 4 * i); break;
}
}
numBytes *= scale;
seeker->mSegments.push(numBytes);
ALOGV("entry #%zu: %u offset %#016llx", i, numBytes, (long long)offset);
offset += numBytes;
}
delete[] buffer;
buffer = NULL;
ALOGI("Found VBRI header.");
return seeker;
}
Commit Message: Make VBRISeeker more robust
Bug: 32577290
Change-Id: I9bcc9422ae7dd3ae4a38df330c9dcd7ac4941ec8
(cherry picked from commit 7fdd36418e945cf6a500018632dfb0ed8cb1a343)
CWE ID: | sp<VBRISeeker> VBRISeeker::CreateFromSource(
const sp<DataSource> &source, off64_t post_id3_pos) {
off64_t pos = post_id3_pos;
uint8_t header[4];
ssize_t n = source->readAt(pos, header, sizeof(header));
if (n < (ssize_t)sizeof(header)) {
return NULL;
}
uint32_t tmp = U32_AT(&header[0]);
size_t frameSize;
int sampleRate;
if (!GetMPEGAudioFrameSize(tmp, &frameSize, &sampleRate)) {
return NULL;
}
pos += sizeof(header) + 32;
uint8_t vbriHeader[26];
n = source->readAt(pos, vbriHeader, sizeof(vbriHeader));
if (n < (ssize_t)sizeof(vbriHeader)) {
return NULL;
}
if (memcmp(vbriHeader, "VBRI", 4)) {
return NULL;
}
size_t numFrames = U32_AT(&vbriHeader[14]);
int64_t durationUs =
numFrames * 1000000ll * (sampleRate >= 32000 ? 1152 : 576) / sampleRate;
ALOGV("duration = %.2f secs", durationUs / 1E6);
size_t numEntries = U16_AT(&vbriHeader[18]);
size_t entrySize = U16_AT(&vbriHeader[22]);
size_t scale = U16_AT(&vbriHeader[20]);
ALOGV("%zu entries, scale=%zu, size_per_entry=%zu",
numEntries,
scale,
entrySize);
if (entrySize > 4) {
ALOGE("invalid VBRI entry size: %zu", entrySize);
return NULL;
}
sp<VBRISeeker> seeker = new (std::nothrow) VBRISeeker;
if (seeker == NULL) {
ALOGW("Couldn't allocate VBRISeeker");
return NULL;
}
size_t totalEntrySize = numEntries * entrySize;
uint8_t *buffer = new (std::nothrow) uint8_t[totalEntrySize];
if (!buffer) {
ALOGW("Couldn't allocate %zu bytes", totalEntrySize);
return NULL;
}
n = source->readAt(pos + sizeof(vbriHeader), buffer, totalEntrySize);
if (n < (ssize_t)totalEntrySize) {
delete[] buffer;
buffer = NULL;
return NULL;
}
seeker->mBasePos = post_id3_pos + frameSize;
if (durationUs) {
seeker->mDurationUs = durationUs;
}
off64_t offset = post_id3_pos;
for (size_t i = 0; i < numEntries; ++i) {
uint32_t numBytes;
switch (entrySize) {
case 1: numBytes = buffer[i]; break;
case 2: numBytes = U16_AT(buffer + 2 * i); break;
case 3: numBytes = U24_AT(buffer + 3 * i); break;
default:
{
CHECK_EQ(entrySize, 4u);
numBytes = U32_AT(buffer + 4 * i); break;
}
}
numBytes *= scale;
seeker->mSegments.push(numBytes);
ALOGV("entry #%zu: %u offset %#016llx", i, numBytes, (long long)offset);
offset += numBytes;
}
delete[] buffer;
buffer = NULL;
ALOGI("Found VBRI header.");
return seeker;
}
| 174,069 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MockAudioRendererHost(base::RunLoop* auth_run_loop,
int render_process_id,
media::AudioManager* audio_manager,
AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager,
const std::string& salt)
: AudioRendererHost(render_process_id,
audio_manager,
mirroring_manager,
media_stream_manager,
salt),
shared_memory_length_(0),
auth_run_loop_(auth_run_loop) {
set_render_frame_id_validate_function_for_testing(&ValidateRenderFrameId);
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | MockAudioRendererHost(base::RunLoop* auth_run_loop,
int render_process_id,
media::AudioManager* audio_manager,
media::AudioSystem* audio_system,
AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager,
const std::string& salt)
: AudioRendererHost(render_process_id,
audio_manager,
audio_system,
mirroring_manager,
media_stream_manager,
salt),
shared_memory_length_(0),
auth_run_loop_(auth_run_loop) {
set_render_frame_id_validate_function_for_testing(&ValidateRenderFrameId);
}
| 171,986 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sk_buff *udp6_ufo_fragment(struct sk_buff *skb, u32 features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *mac_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
int offset;
__wsum csum;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
int type = skb_shinfo(skb)->gso_type;
if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY) ||
!(type & (SKB_GSO_UDP))))
goto out;
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
segs = NULL;
goto out;
}
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
offset = skb_checksum_start_offset(skb);
csum = skb_checksum(skb, offset, skb->len- offset, 0);
offset += skb->csum_offset;
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
/* Check if there is enough headroom to insert fragment header. */
if ((skb_mac_header(skb) < skb->head + frag_hdr_sz) &&
pskb_expand_head(skb, frag_hdr_sz, 0, GFP_ATOMIC))
goto out;
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = skb_network_header(skb) - skb_mac_header(skb) +
unfrag_ip6hlen;
mac_start = skb_mac_header(skb);
memmove(mac_start-frag_hdr_sz, mac_start, unfrag_len);
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
ipv6_select_ident(fptr);
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
out:
return segs;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, u32 features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *mac_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
int offset;
__wsum csum;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
int type = skb_shinfo(skb)->gso_type;
if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY) ||
!(type & (SKB_GSO_UDP))))
goto out;
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
segs = NULL;
goto out;
}
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
offset = skb_checksum_start_offset(skb);
csum = skb_checksum(skb, offset, skb->len- offset, 0);
offset += skb->csum_offset;
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
/* Check if there is enough headroom to insert fragment header. */
if ((skb_mac_header(skb) < skb->head + frag_hdr_sz) &&
pskb_expand_head(skb, frag_hdr_sz, 0, GFP_ATOMIC))
goto out;
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = skb_network_header(skb) - skb_mac_header(skb) +
unfrag_ip6hlen;
mac_start = skb_mac_header(skb);
memmove(mac_start-frag_hdr_sz, mac_start, unfrag_len);
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb));
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
out:
return segs;
}
| 165,854 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileInfo, getFileInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileInfo, getFileInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,042 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 detect_allow_debuggers(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--allow-debuggers") == 0) {
arg_allow_debuggers = 1;
break;
}
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--", 2) != 0)
break;
}
}
Commit Message: security fix
CWE ID: | static void detect_allow_debuggers(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--allow-debuggers") == 0) {
// check kernel version
struct utsname u;
int rv = uname(&u);
if (rv != 0)
errExit("uname");
int major;
int minor;
if (2 != sscanf(u.release, "%d.%d", &major, &minor)) {
fprintf(stderr, "Error: cannot extract Linux kernel version: %s\n", u.version);
exit(1);
}
if (major < 4 || (major == 4 && minor < 8)) {
fprintf(stderr, "Error: --allow-debuggers is disabled on Linux kernels prior to 4.8. "
"A bug in ptrace call allows a full bypass of the seccomp filter. "
"Your current kernel version is %d.%d.\n", major, minor);
exit(1);
}
arg_allow_debuggers = 1;
break;
}
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--", 2) != 0)
break;
}
}
| 168,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: http_splitline(struct worker *w, int fd, struct http *hp,
const struct http_conn *htc, int h1, int h2, int h3)
{
char *p, *q;
CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC);
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
/* XXX: Assert a NUL at rx.e ? */
Tcheck(htc->rxbuf);
/* Skip leading LWS */
for (p = htc->rxbuf.b ; vct_islws(*p); p++)
continue;
/* First field cannot contain SP, CRLF or CTL */
q = p;
for (; !vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h1].b = q;
hp->hd[h1].e = p;
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Second field cannot contain LWS or CTL */
q = p;
for (; !vct_islws(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h2].b = q;
hp->hd[h2].e = p;
if (!Tlen(hp->hd[h2]))
return (400);
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Third field is optional and cannot contain CTL */
q = p;
if (!vct_iscrlf(*p)) {
for (; !vct_iscrlf(*p); p++)
if (!vct_issep(*p) && vct_isctl(*p))
return (400);
}
hp->hd[h3].b = q;
hp->hd[h3].e = p;
/* Skip CRLF */
p += vct_skipcrlf(p);
*hp->hd[h1].e = '\0';
WSLH(w, fd, hp, h1);
*hp->hd[h2].e = '\0';
WSLH(w, fd, hp, h2);
if (hp->hd[h3].e != NULL) {
*hp->hd[h3].e = '\0';
WSLH(w, fd, hp, h3);
}
return (http_dissect_hdrs(w, hp, fd, p, htc));
}
Commit Message: Do not consider a CR by itself as a valid line terminator
Varnish (prior to version 4.0) was not following the standard with
regard to line separator.
Spotted and analyzed by: Régis Leroy [regilero] [email protected]
CWE ID: | http_splitline(struct worker *w, int fd, struct http *hp,
const struct http_conn *htc, int h1, int h2, int h3)
{
char *p, *q;
CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC);
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
/* XXX: Assert a NUL at rx.e ? */
Tcheck(htc->rxbuf);
/* Skip leading LWS */
for (p = htc->rxbuf.b ; vct_islws(*p); p++)
continue;
/* First field cannot contain SP, CRLF or CTL */
q = p;
for (; !vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h1].b = q;
hp->hd[h1].e = p;
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Second field cannot contain LWS or CTL */
q = p;
for (; !vct_islws(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h2].b = q;
hp->hd[h2].e = p;
if (!Tlen(hp->hd[h2]))
return (400);
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Third field is optional and cannot contain CTL */
q = p;
if (!vct_iscrlf(p)) {
for (; !vct_iscrlf(p); p++)
if (!vct_issep(*p) && vct_isctl(*p))
return (400);
}
hp->hd[h3].b = q;
hp->hd[h3].e = p;
/* Skip CRLF */
p += vct_skipcrlf(p);
*hp->hd[h1].e = '\0';
WSLH(w, fd, hp, h1);
*hp->hd[h2].e = '\0';
WSLH(w, fd, hp, h2);
if (hp->hd[h3].e != NULL) {
*hp->hd[h3].e = '\0';
WSLH(w, fd, hp, h3);
}
return (http_dissect_hdrs(w, hp, fd, p, htc));
}
| 169,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset,
const int whence,void *user_data)
{
PhotoshopProfile
*profile;
profile=(PhotoshopProfile *) user_data;
switch (whence)
{
case SEEK_SET:
default:
{
if (offset < 0)
return(-1);
profile->offset=offset;
break;
}
case SEEK_CUR:
{
if ((profile->offset+offset) < 0)
return(-1);
profile->offset+=offset;
break;
}
case SEEK_END:
{
if (((MagickOffsetType) profile->length+offset) < 0)
return(-1);
profile->offset=profile->length+offset;
break;
}
}
return(profile->offset);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1602
CWE ID: CWE-190 | static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset,
const int whence,void *user_data)
{
PhotoshopProfile
*profile;
profile=(PhotoshopProfile *) user_data;
switch (whence)
{
case SEEK_SET:
default:
{
if (offset < 0)
return(-1);
profile->offset=offset;
break;
}
case SEEK_CUR:
{
if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) ||
((offset < 0) && (profile->offset < (-SSIZE_MAX-offset))))
{
errno=EOVERFLOW;
return(-1);
}
if ((profile->offset+offset) < 0)
return(-1);
profile->offset+=offset;
break;
}
case SEEK_END:
{
if (((MagickOffsetType) profile->length+offset) < 0)
return(-1);
profile->offset=profile->length+offset;
break;
}
}
return(profile->offset);
}
| 169,620 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) {
Open(callback);
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399 | void UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) {
| 171,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response PageHandler::SetDownloadBehavior(const std::string& behavior,
Maybe<std::string> download_path) {
WebContentsImpl* web_contents = GetWebContents();
if (!web_contents)
return Response::InternalError();
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Allow &&
!download_path.isJust())
return Response::Error("downloadPath not provided");
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Default) {
DevToolsDownloadManagerHelper::RemoveFromWebContents(web_contents);
download_manager_delegate_ = nullptr;
return Response::OK();
}
content::BrowserContext* browser_context = web_contents->GetBrowserContext();
DCHECK(browser_context);
content::DownloadManager* download_manager =
content::BrowserContext::GetDownloadManager(browser_context);
download_manager_delegate_ =
DevToolsDownloadManagerDelegate::TakeOver(download_manager);
DevToolsDownloadManagerHelper::CreateForWebContents(web_contents);
DevToolsDownloadManagerHelper* download_helper =
DevToolsDownloadManagerHelper::FromWebContents(web_contents);
download_helper->SetDownloadBehavior(
DevToolsDownloadManagerHelper::DownloadBehavior::DENY);
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Allow) {
download_helper->SetDownloadBehavior(
DevToolsDownloadManagerHelper::DownloadBehavior::ALLOW);
download_helper->SetDownloadPath(download_path.fromJust());
}
return Response::OK();
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20 | Response PageHandler::SetDownloadBehavior(const std::string& behavior,
Maybe<std::string> download_path) {
if (!allow_set_download_behavior_)
return Response::Error("Not allowed.");
WebContentsImpl* web_contents = GetWebContents();
if (!web_contents)
return Response::InternalError();
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Allow &&
!download_path.isJust())
return Response::Error("downloadPath not provided");
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Default) {
DevToolsDownloadManagerHelper::RemoveFromWebContents(web_contents);
download_manager_delegate_ = nullptr;
return Response::OK();
}
content::BrowserContext* browser_context = web_contents->GetBrowserContext();
DCHECK(browser_context);
content::DownloadManager* download_manager =
content::BrowserContext::GetDownloadManager(browser_context);
download_manager_delegate_ =
DevToolsDownloadManagerDelegate::TakeOver(download_manager);
DevToolsDownloadManagerHelper::CreateForWebContents(web_contents);
DevToolsDownloadManagerHelper* download_helper =
DevToolsDownloadManagerHelper::FromWebContents(web_contents);
download_helper->SetDownloadBehavior(
DevToolsDownloadManagerHelper::DownloadBehavior::DENY);
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Allow) {
download_helper->SetDownloadBehavior(
DevToolsDownloadManagerHelper::DownloadBehavior::ALLOW);
download_helper->SetDownloadPath(download_path.fromJust());
}
return Response::OK();
}
| 172,608 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol ^ net_hash_mix(net),
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
{
u32 hash, id;
/* Note the following code is not safe, but this is okay. */
if (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key)))
get_random_bytes(&net->ipv4.ip_id_key,
sizeof(net->ipv4.ip_id_key));
hash = siphash_3u32((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol,
&net->ipv4.ip_id_key);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
| 169,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
struct cifs_tcon *tcon, const struct nls_table *cp)
{
struct smb2_tree_connect_req *req;
struct smb2_tree_connect_rsp *rsp = NULL;
struct kvec iov[2];
int rc = 0;
int resp_buftype;
int unc_path_len;
struct TCP_Server_Info *server;
__le16 *unc_path = NULL;
cifs_dbg(FYI, "TCON\n");
if ((ses->server) && tree)
server = ses->server;
else
return -EIO;
if (tcon && tcon->bad_network_name)
return -ENOENT;
unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
if (unc_path == NULL)
return -ENOMEM;
unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
unc_path_len *= 2;
if (unc_path_len < 2) {
kfree(unc_path);
return -EINVAL;
}
rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
if (rc) {
kfree(unc_path);
return rc;
}
if (tcon == NULL) {
/* since no tcon, smb2_init can not do this, so do here */
req->hdr.SessionId = ses->Suid;
/* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
}
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for pad */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/* Testing shows that buffer offset must be at location of Buffer[0] */
req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
- 1 /* pad */ - 4 /* do not count rfc1001 len field */);
req->PathLength = cpu_to_le16(unc_path_len - 2);
iov[1].iov_base = unc_path;
iov[1].iov_len = unc_path_len;
inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
if (rc != 0) {
if (tcon) {
cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
tcon->need_reconnect = true;
}
goto tcon_error_exit;
}
if (tcon == NULL) {
ses->ipc_tid = rsp->hdr.TreeId;
goto tcon_exit;
}
if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
cifs_dbg(FYI, "connection to disk share\n");
else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
tcon->ipc = true;
cifs_dbg(FYI, "connection to pipe share\n");
} else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
tcon->print = true;
cifs_dbg(FYI, "connection to printer\n");
} else {
cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
rc = -EOPNOTSUPP;
goto tcon_error_exit;
}
tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
tcon->tidStatus = CifsGood;
tcon->need_reconnect = false;
tcon->tid = rsp->hdr.TreeId;
strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
init_copy_chunk_defaults(tcon);
if (tcon->ses->server->ops->validate_negotiate)
rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
tcon_exit:
free_rsp_buf(resp_buftype, rsp);
kfree(unc_path);
return rc;
tcon_error_exit:
if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
tcon->bad_network_name = true;
}
goto tcon_exit;
}
Commit Message: [CIFS] Possible null ptr deref in SMB2_tcon
As Raphael Geissert pointed out, tcon_error_exit can dereference tcon
and there is one path in which tcon can be null.
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]> # v3.7+
Reported-by: Raphael Geissert <[email protected]>
CWE ID: CWE-399 | SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
struct cifs_tcon *tcon, const struct nls_table *cp)
{
struct smb2_tree_connect_req *req;
struct smb2_tree_connect_rsp *rsp = NULL;
struct kvec iov[2];
int rc = 0;
int resp_buftype;
int unc_path_len;
struct TCP_Server_Info *server;
__le16 *unc_path = NULL;
cifs_dbg(FYI, "TCON\n");
if ((ses->server) && tree)
server = ses->server;
else
return -EIO;
if (tcon && tcon->bad_network_name)
return -ENOENT;
unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
if (unc_path == NULL)
return -ENOMEM;
unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
unc_path_len *= 2;
if (unc_path_len < 2) {
kfree(unc_path);
return -EINVAL;
}
rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
if (rc) {
kfree(unc_path);
return rc;
}
if (tcon == NULL) {
/* since no tcon, smb2_init can not do this, so do here */
req->hdr.SessionId = ses->Suid;
/* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
}
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for pad */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/* Testing shows that buffer offset must be at location of Buffer[0] */
req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
- 1 /* pad */ - 4 /* do not count rfc1001 len field */);
req->PathLength = cpu_to_le16(unc_path_len - 2);
iov[1].iov_base = unc_path;
iov[1].iov_len = unc_path_len;
inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
if (rc != 0) {
if (tcon) {
cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
tcon->need_reconnect = true;
}
goto tcon_error_exit;
}
if (tcon == NULL) {
ses->ipc_tid = rsp->hdr.TreeId;
goto tcon_exit;
}
if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
cifs_dbg(FYI, "connection to disk share\n");
else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
tcon->ipc = true;
cifs_dbg(FYI, "connection to pipe share\n");
} else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
tcon->print = true;
cifs_dbg(FYI, "connection to printer\n");
} else {
cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
rc = -EOPNOTSUPP;
goto tcon_error_exit;
}
tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
tcon->tidStatus = CifsGood;
tcon->need_reconnect = false;
tcon->tid = rsp->hdr.TreeId;
strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
init_copy_chunk_defaults(tcon);
if (tcon->ses->server->ops->validate_negotiate)
rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
tcon_exit:
free_rsp_buf(resp_buftype, rsp);
kfree(unc_path);
return rc;
tcon_error_exit:
if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
if (tcon)
tcon->bad_network_name = true;
}
goto tcon_exit;
}
| 166,261 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FeatureInfo::EnableOESTextureHalfFloatLinear() {
if (!oes_texture_half_float_linear_available_)
return;
AddExtensionString("GL_OES_texture_half_float_linear");
feature_flags_.enable_texture_half_float_linear = true;
feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16);
}
Commit Message: gpu: Disallow use of IOSurfaces for half-float format with swiftshader.
[email protected]
Bug: 998038
Change-Id: Ic31d28938ef205b36657fc7bd297fe8a63d08543
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1798052
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#695826}
CWE ID: CWE-125 | void FeatureInfo::EnableOESTextureHalfFloatLinear() {
if (!oes_texture_half_float_linear_available_)
return;
AddExtensionString("GL_OES_texture_half_float_linear");
feature_flags_.enable_texture_half_float_linear = true;
// TODO(capn) : Re-enable this once we have ANGLE+SwiftShader supporting
// IOSurfaces.
if (workarounds_.disable_half_float_for_gmb)
return;
feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16);
}
| 172,387 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ttusbdecfe_dvbs_diseqc_send_master_cmd(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd *cmd)
{
struct ttusbdecfe_state* state = (struct ttusbdecfe_state*) fe->demodulator_priv;
u8 b[] = { 0x00, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00 };
memcpy(&b[4], cmd->msg, cmd->msg_len);
state->config->send_command(fe, 0x72,
sizeof(b) - (6 - cmd->msg_len), b,
NULL, NULL);
return 0;
}
Commit Message: [media] ttusb-dec: buffer overflow in ioctl
We need to add a limit check here so we don't overflow the buffer.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int ttusbdecfe_dvbs_diseqc_send_master_cmd(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd *cmd)
{
struct ttusbdecfe_state* state = (struct ttusbdecfe_state*) fe->demodulator_priv;
u8 b[] = { 0x00, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00 };
if (cmd->msg_len > sizeof(b) - 4)
return -EINVAL;
memcpy(&b[4], cmd->msg, cmd->msg_len);
state->config->send_command(fe, 0x72,
sizeof(b) - (6 - cmd->msg_len), b,
NULL, NULL);
return 0;
}
| 166,241 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += numcols;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += numcols;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec
that was caused by a buffer being allocated with a size that was too small
in some cases.
Added a new regression test case.
CWE ID: CWE-119 | void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, numcols, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += numcols;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += numcols;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
| 169,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int aacDecoder_drcExtractAndMap (
HANDLE_AAC_DRC self,
HANDLE_FDK_BITSTREAM hBs,
CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
UCHAR pceInstanceTag,
UCHAR channelMapping[], /* Channel mapping translating drcChannel index to canonical channel index */
int validChannels )
{
CDrcPayload threadBs[MAX_DRC_THREADS];
CDrcPayload *validThreadBs[MAX_DRC_THREADS];
CDrcParams *pParams;
UINT backupBsPosition;
int i, thread, validThreads = 0;
int numExcludedChns[MAX_DRC_THREADS];
FDK_ASSERT(self != NULL);
FDK_ASSERT(hBs != NULL);
FDK_ASSERT(pAacDecoderStaticChannelInfo != NULL);
pParams = &self->params;
self->numThreads = 0;
backupBsPosition = FDKgetValidBits(hBs);
for (i = 0; i < self->numPayloads && self->numThreads < MAX_DRC_THREADS; i++) {
int bitsParsed;
/* Init payload data chunk. The memclear is very important because it initializes
the most values. Without it the module wouldn't work properly or crash. */
FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
threadBs[self->numThreads].channelData.bandTop[0] = (1024 >> 2) - 1;
/* Extract payload */
bitsParsed = aacDecoder_drcParse( hBs,
&threadBs[self->numThreads],
self->drcPayloadPosition[i] );
if (bitsParsed > 0) {
self->numThreads++;
}
}
self->numPayloads = 0;
if (self->dvbAncDataAvailable)
{ /* Append a DVB heavy compression payload thread if available. */
int bitsParsed;
/* Init payload data chunk. The memclear is very important because it initializes
the most values. Without it the module wouldn't work properly or crash. */
FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
threadBs[self->numThreads].channelData.bandTop[0] = (1024 >> 2) - 1;
/* Extract payload */
bitsParsed = aacDecoder_drcReadCompression( hBs,
&threadBs[self->numThreads],
self->dvbAncDataPosition );
if (bitsParsed > 0) {
self->numThreads++;
}
}
self->dvbAncDataAvailable = 0;
/* Reset the bitbufffer */
FDKpushBiDirectional(hBs, FDKgetValidBits(hBs) - backupBsPosition);
/* calculate number of valid bits in excl_chn_mask */
/* coupling channels not supported */
/* check for valid threads */
for (thread = 0; thread < self->numThreads; thread++) {
CDrcPayload *pThreadBs = &threadBs[thread];
int numExclChns = 0;
switch ((AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType) {
default:
continue;
case MPEG_DRC_EXT_DATA:
case DVB_DRC_ANC_DATA:
break;
}
if (pThreadBs->pceInstanceTag >= 0) { /* if PCE tag present */
if (pThreadBs->pceInstanceTag != pceInstanceTag) {
continue; /* don't accept */
}
}
/* calculate number of excluded channels */
if (pThreadBs->excludedChnsMask > 0) {
INT exclMask = pThreadBs->excludedChnsMask;
int ch;
for (ch = 0; ch < validChannels; ch++) {
numExclChns += exclMask & 0x1;
exclMask >>= 1;
}
}
if (numExclChns < validChannels) {
validThreadBs[validThreads] = pThreadBs;
numExcludedChns[validThreads] = numExclChns;
validThreads++;
}
}
if (validThreads > 1) {
int ch;
/* check consistency of excl_chn_mask amongst valid DRC threads */
for (ch = 0; ch < validChannels; ch++) {
int present = 0;
for (thread = 0; thread < validThreads; thread++) {
CDrcPayload *pThreadBs = validThreadBs[thread];
/* thread applies to this channel */
if ( (pThreadBs->channelData.drcDataType == MPEG_DRC_EXT_DATA)
&& ( (numExcludedChns[thread] == 0)
|| (!(pThreadBs->excludedChnsMask & (1<<ch))) ) ) {
present++;
}
}
if (present > 1) {
return -1;
}
}
}
/* map DRC bitstream information onto DRC channel information */
for (thread = 0; thread < validThreads; thread++)
{
CDrcPayload *pThreadBs = validThreadBs[thread];
INT exclMask = pThreadBs->excludedChnsMask;
AACDEC_DRC_PAYLOAD_TYPE drcPayloadType = (AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType;
int ch;
/* last progRefLevel transmitted is the one that is used
* (but it should really only be transmitted once per block!)
*/
if (pThreadBs->progRefLevel >= 0) {
self->progRefLevel = pThreadBs->progRefLevel;
self->progRefLevelPresent = 1;
self->prlExpiryCount = 0; /* Got a new value -> Reset counter */
}
if (drcPayloadType == DVB_DRC_ANC_DATA) {
/* Announce the presentation mode of this valid thread. */
self->presMode = pThreadBs->presMode;
}
/* SCE, CPE and LFE */
for (ch = 0; ch < validChannels; ch++) {
int mapedChannel = channelMapping[ch];
if ( ((exclMask & (1<<mapedChannel)) == 0)
&& ( (drcPayloadType == MPEG_DRC_EXT_DATA)
|| ((drcPayloadType == DVB_DRC_ANC_DATA) && self->params.applyHeavyCompression)
) ) {
/* copy thread to channel */
pAacDecoderStaticChannelInfo[ch]->drcData = pThreadBs->channelData;
}
}
/* CCEs not supported by now */
}
/* Increment and check expiry counter for the program reference level: */
if ( (pParams->expiryFrame > 0)
&& (self->prlExpiryCount++ > pParams->expiryFrame) )
{ /* The program reference level is too old, so set it back to the target level. */
self->progRefLevelPresent = 0;
self->progRefLevel = pParams->targetRefLevel;
self->prlExpiryCount = 0;
}
return 0;
}
Commit Message: Fix stack corruption happening in aacDecoder_drcExtractAndMap()
In the aacDecoder_drcExtractAndMap() function, self->numThreads
can be used after having exceeded its intended max value,
MAX_DRC_THREADS, causing memory to be cleared after the
threadBs[MAX_DRC_THREADS] array.
The crash is prevented by never using self->numThreads with
a value equal to or greater than MAX_DRC_THREADS.
A proper fix will be required as there seems to be an issue as
to which entry in the threadBs array is meant to be initialized
and used.
Bug 26751339
Change-Id: I655cc40c35d4206ab72e83b2bdb751be2fe52b5a
CWE ID: CWE-119 | static int aacDecoder_drcExtractAndMap (
HANDLE_AAC_DRC self,
HANDLE_FDK_BITSTREAM hBs,
CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
UCHAR pceInstanceTag,
UCHAR channelMapping[], /* Channel mapping translating drcChannel index to canonical channel index */
int validChannels )
{
CDrcPayload threadBs[MAX_DRC_THREADS];
CDrcPayload *validThreadBs[MAX_DRC_THREADS];
CDrcParams *pParams;
UINT backupBsPosition;
int i, thread, validThreads = 0;
int numExcludedChns[MAX_DRC_THREADS];
FDK_ASSERT(self != NULL);
FDK_ASSERT(hBs != NULL);
FDK_ASSERT(pAacDecoderStaticChannelInfo != NULL);
pParams = &self->params;
self->numThreads = 0;
backupBsPosition = FDKgetValidBits(hBs);
for (i = 0; i < self->numPayloads && self->numThreads < MAX_DRC_THREADS; i++) {
int bitsParsed;
/* Init payload data chunk. The memclear is very important because it initializes
the most values. Without it the module wouldn't work properly or crash. */
FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
threadBs[self->numThreads].channelData.bandTop[0] = (1024 >> 2) - 1;
/* Extract payload */
bitsParsed = aacDecoder_drcParse( hBs,
&threadBs[self->numThreads],
self->drcPayloadPosition[i] );
if (bitsParsed > 0) {
self->numThreads++;
}
}
self->numPayloads = 0;
if (self->numThreads >= MAX_DRC_THREADS) {
self->numThreads = MAX_DRC_THREADS - 1;
}
if (self->dvbAncDataAvailable)
{ /* Append a DVB heavy compression payload thread if available. */
int bitsParsed;
/* Init payload data chunk. The memclear is very important because it initializes
the most values. Without it the module wouldn't work properly or crash. */
FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
threadBs[self->numThreads].channelData.bandTop[0] = (1024 >> 2) - 1;
/* Extract payload */
bitsParsed = aacDecoder_drcReadCompression( hBs,
&threadBs[self->numThreads],
self->dvbAncDataPosition );
if (bitsParsed > 0) {
self->numThreads++;
}
}
self->dvbAncDataAvailable = 0;
/* Reset the bitbufffer */
FDKpushBiDirectional(hBs, FDKgetValidBits(hBs) - backupBsPosition);
/* calculate number of valid bits in excl_chn_mask */
/* coupling channels not supported */
if (self->numThreads >= MAX_DRC_THREADS) {
self->numThreads = MAX_DRC_THREADS - 1;
}
/* check for valid threads */
for (thread = 0; thread < self->numThreads; thread++) {
CDrcPayload *pThreadBs = &threadBs[thread];
int numExclChns = 0;
switch ((AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType) {
default:
continue;
case MPEG_DRC_EXT_DATA:
case DVB_DRC_ANC_DATA:
break;
}
if (pThreadBs->pceInstanceTag >= 0) { /* if PCE tag present */
if (pThreadBs->pceInstanceTag != pceInstanceTag) {
continue; /* don't accept */
}
}
/* calculate number of excluded channels */
if (pThreadBs->excludedChnsMask > 0) {
INT exclMask = pThreadBs->excludedChnsMask;
int ch;
for (ch = 0; ch < validChannels; ch++) {
numExclChns += exclMask & 0x1;
exclMask >>= 1;
}
}
if (numExclChns < validChannels) {
validThreadBs[validThreads] = pThreadBs;
numExcludedChns[validThreads] = numExclChns;
validThreads++;
}
}
if (validThreads > 1) {
int ch;
/* check consistency of excl_chn_mask amongst valid DRC threads */
for (ch = 0; ch < validChannels; ch++) {
int present = 0;
for (thread = 0; thread < validThreads; thread++) {
CDrcPayload *pThreadBs = validThreadBs[thread];
/* thread applies to this channel */
if ( (pThreadBs->channelData.drcDataType == MPEG_DRC_EXT_DATA)
&& ( (numExcludedChns[thread] == 0)
|| (!(pThreadBs->excludedChnsMask & (1<<ch))) ) ) {
present++;
}
}
if (present > 1) {
return -1;
}
}
}
/* map DRC bitstream information onto DRC channel information */
for (thread = 0; thread < validThreads; thread++)
{
CDrcPayload *pThreadBs = validThreadBs[thread];
INT exclMask = pThreadBs->excludedChnsMask;
AACDEC_DRC_PAYLOAD_TYPE drcPayloadType = (AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType;
int ch;
/* last progRefLevel transmitted is the one that is used
* (but it should really only be transmitted once per block!)
*/
if (pThreadBs->progRefLevel >= 0) {
self->progRefLevel = pThreadBs->progRefLevel;
self->progRefLevelPresent = 1;
self->prlExpiryCount = 0; /* Got a new value -> Reset counter */
}
if (drcPayloadType == DVB_DRC_ANC_DATA) {
/* Announce the presentation mode of this valid thread. */
self->presMode = pThreadBs->presMode;
}
/* SCE, CPE and LFE */
for (ch = 0; ch < validChannels; ch++) {
int mapedChannel = channelMapping[ch];
if ( ((exclMask & (1<<mapedChannel)) == 0)
&& ( (drcPayloadType == MPEG_DRC_EXT_DATA)
|| ((drcPayloadType == DVB_DRC_ANC_DATA) && self->params.applyHeavyCompression)
) ) {
/* copy thread to channel */
pAacDecoderStaticChannelInfo[ch]->drcData = pThreadBs->channelData;
}
}
/* CCEs not supported by now */
}
/* Increment and check expiry counter for the program reference level: */
if ( (pParams->expiryFrame > 0)
&& (self->prlExpiryCount++ > pParams->expiryFrame) )
{ /* The program reference level is too old, so set it back to the target level. */
self->progRefLevelPresent = 0;
self->progRefLevel = pParams->targetRefLevel;
self->prlExpiryCount = 0;
}
return 0;
}
| 173,889 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 u64 __skb_get_nlattr(u64 ctx, u64 A, u64 X, u64 r4, u64 r5)
{
struct sk_buff *skb = (struct sk_buff *)(long) ctx;
struct nlattr *nla;
if (skb_is_nonlinear(skb))
return 0;
if (A > skb->len - sizeof(struct nlattr))
return 0;
nla = nla_find((struct nlattr *) &skb->data[A], skb->len - A, X);
if (nla)
return (void *) nla - (void *) skb->data;
return 0;
}
Commit Message: filter: prevent nla extensions to peek beyond the end of the message
The BPF_S_ANC_NLATTR and BPF_S_ANC_NLATTR_NEST extensions fail to check
for a minimal message length before testing the supplied offset to be
within the bounds of the message. This allows the subtraction of the nla
header to underflow and therefore -- as the data type is unsigned --
allowing far to big offset and length values for the search of the
netlink attribute.
The remainder calculation for the BPF_S_ANC_NLATTR_NEST extension is
also wrong. It has the minuend and subtrahend mixed up, therefore
calculates a huge length value, allowing to overrun the end of the
message while looking for the netlink attribute.
The following three BPF snippets will trigger the bugs when attached to
a UNIX datagram socket and parsing a message with length 1, 2 or 3.
,-[ PoC for missing size check in BPF_S_ANC_NLATTR ]--
| ld #0x87654321
| ldx #42
| ld #nla
| ret a
`---
,-[ PoC for the same bug in BPF_S_ANC_NLATTR_NEST ]--
| ld #0x87654321
| ldx #42
| ld #nlan
| ret a
`---
,-[ PoC for wrong remainder calculation in BPF_S_ANC_NLATTR_NEST ]--
| ; (needs a fake netlink header at offset 0)
| ld #0
| ldx #42
| ld #nlan
| ret a
`---
Fix the first issue by ensuring the message length fulfills the minimal
size constrains of a nla header. Fix the second bug by getting the math
for the remainder calculation right.
Fixes: 4738c1db15 ("[SKFILTER]: Add SKF_ADF_NLATTR instruction")
Fixes: d214c7537b ("filter: add SKF_AD_NLATTR_NEST to look for nested..")
Cc: Patrick McHardy <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189 | static u64 __skb_get_nlattr(u64 ctx, u64 A, u64 X, u64 r4, u64 r5)
{
struct sk_buff *skb = (struct sk_buff *)(long) ctx;
struct nlattr *nla;
if (skb_is_nonlinear(skb))
return 0;
if (skb->len < sizeof(struct nlattr))
return 0;
if (A > skb->len - sizeof(struct nlattr))
return 0;
nla = nla_find((struct nlattr *) &skb->data[A], skb->len - A, X);
if (nla)
return (void *) nla - (void *) skb->data;
return 0;
}
| 166,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: iperf_on_connect(struct iperf_test *test)
{
time_t now_secs;
const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT";
char now_str[100];
char ipr[INET6_ADDRSTRLEN];
int port;
struct sockaddr_storage sa;
struct sockaddr_in *sa_inP;
struct sockaddr_in6 *sa_in6P;
socklen_t len;
int opt;
now_secs = time((time_t*) 0);
(void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs));
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s timesecs: %d", now_str, (int64_t) now_secs));
else if (test->verbose)
iprintf(test, report_time, now_str);
if (test->role == 'c') {
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port));
else {
iprintf(test, report_connecting, test->server_hostname, test->server_port);
if (test->reverse)
iprintf(test, report_reverse, test->server_hostname);
}
} else {
len = sizeof(sa);
getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len);
if (getsockdomain(test->ctrl_sck) == AF_INET) {
sa_inP = (struct sockaddr_in *) &sa;
inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr));
port = ntohs(sa_inP->sin_port);
} else {
sa_in6P = (struct sockaddr_in6 *) &sa;
inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr));
port = ntohs(sa_in6P->sin6_port);
}
mapped_v4_to_regular_v4(ipr);
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port));
else
iprintf(test, report_accepted, ipr, port);
}
if (test->json_output) {
cJSON_AddStringToObject(test->json_start, "cookie", test->cookie);
if (test->protocol->id == SOCK_STREAM) {
if (test->settings->mss)
cJSON_AddIntToObject(test->json_start, "tcp_mss", test->settings->mss);
else {
len = sizeof(opt);
getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
cJSON_AddIntToObject(test->json_start, "tcp_mss_default", opt);
}
}
} else if (test->verbose) {
iprintf(test, report_cookie, test->cookie);
if (test->protocol->id == SOCK_STREAM) {
if (test->settings->mss)
iprintf(test, " TCP MSS: %d\n", test->settings->mss);
else {
len = sizeof(opt);
getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
iprintf(test, " TCP MSS: %d (default)\n", opt);
}
}
}
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | iperf_on_connect(struct iperf_test *test)
{
time_t now_secs;
const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT";
char now_str[100];
char ipr[INET6_ADDRSTRLEN];
int port;
struct sockaddr_storage sa;
struct sockaddr_in *sa_inP;
struct sockaddr_in6 *sa_in6P;
socklen_t len;
int opt;
now_secs = time((time_t*) 0);
(void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs));
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s timesecs: %d", now_str, (int64_t) now_secs));
else if (test->verbose)
iprintf(test, report_time, now_str);
if (test->role == 'c') {
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port));
else {
iprintf(test, report_connecting, test->server_hostname, test->server_port);
if (test->reverse)
iprintf(test, report_reverse, test->server_hostname);
}
} else {
len = sizeof(sa);
getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len);
if (getsockdomain(test->ctrl_sck) == AF_INET) {
sa_inP = (struct sockaddr_in *) &sa;
inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr));
port = ntohs(sa_inP->sin_port);
} else {
sa_in6P = (struct sockaddr_in6 *) &sa;
inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr));
port = ntohs(sa_in6P->sin6_port);
}
mapped_v4_to_regular_v4(ipr);
if (test->json_output)
cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port));
else
iprintf(test, report_accepted, ipr, port);
}
if (test->json_output) {
cJSON_AddStringToObject(test->json_start, "cookie", test->cookie);
if (test->protocol->id == SOCK_STREAM) {
if (test->settings->mss)
cJSON_AddNumberToObject(test->json_start, "tcp_mss", test->settings->mss);
else {
len = sizeof(opt);
getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
cJSON_AddNumberToObject(test->json_start, "tcp_mss_default", opt);
}
}
} else if (test->verbose) {
iprintf(test, report_cookie, test->cookie);
if (test->protocol->id == SOCK_STREAM) {
if (test->settings->mss)
iprintf(test, " TCP MSS: %d\n", test->settings->mss);
else {
len = sizeof(opt);
getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
iprintf(test, " TCP MSS: %d (default)\n", opt);
}
}
}
}
| 167,315 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PaymentRequest::Complete(mojom::PaymentComplete result) {
if (!client_.is_bound())
return;
if (result == mojom::PaymentComplete::FAIL) {
delegate_->ShowErrorMessage();
} else {
DCHECK(!has_recorded_completion_);
journey_logger_.SetCompleted();
has_recorded_completion_ = true;
delegate_->GetPrefService()->SetBoolean(kPaymentsFirstTransactionCompleted,
true);
client_->OnComplete();
state_->RecordUseStats();
}
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189 | void PaymentRequest::Complete(mojom::PaymentComplete result) {
if (!IsInitialized()) {
log_.Error("Attempted complete without initialization");
OnConnectionTerminated();
return;
}
if (!IsThisPaymentRequestShowing()) {
log_.Error("Attempted complete without show");
OnConnectionTerminated();
return;
}
if (result == mojom::PaymentComplete::FAIL) {
delegate_->ShowErrorMessage();
} else {
DCHECK(!has_recorded_completion_);
journey_logger_.SetCompleted();
has_recorded_completion_ = true;
delegate_->GetPrefService()->SetBoolean(kPaymentsFirstTransactionCompleted,
true);
client_->OnComplete();
state_->RecordUseStats();
}
}
| 173,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: http_splitheader(struct http *hp, int req)
{
char *p, *q, **hh;
int n;
char buf[20];
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
if (req) {
memset(hp->req, 0, sizeof hp->req);
hh = hp->req;
} else {
memset(hp->resp, 0, sizeof hp->resp);
hh = hp->resp;
}
n = 0;
p = hp->rxbuf;
/* REQ/PROTO */
while (vct_islws(*p))
p++;
hh[n++] = p;
while (!vct_islws(*p))
p++;
assert(!vct_iscrlf(*p));
*p++ = '\0';
/* URL/STATUS */
while (vct_issp(*p)) /* XXX: H space only */
p++;
assert(!vct_iscrlf(*p));
hh[n++] = p;
while (!vct_islws(*p))
p++;
if (vct_iscrlf(*p)) {
hh[n++] = NULL;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
} else {
*p++ = '\0';
/* PROTO/MSG */
while (vct_issp(*p)) /* XXX: H space only */
p++;
hh[n++] = p;
while (!vct_iscrlf(*p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
assert(n == 3);
while (*p != '\0') {
assert(n < MAX_HDR);
if (vct_iscrlf(*p))
break;
hh[n++] = p++;
while (*p != '\0' && !vct_iscrlf(*p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
p += vct_skipcrlf(p);
assert(*p == '\0');
for (n = 0; n < 3 || hh[n] != NULL; n++) {
sprintf(buf, "http[%2d] ", n);
vtc_dump(hp->vl, 4, buf, hh[n], -1);
}
}
Commit Message: Do not consider a CR by itself as a valid line terminator
Varnish (prior to version 4.0) was not following the standard with
regard to line separator.
Spotted and analyzed by: Régis Leroy [regilero] [email protected]
CWE ID: | http_splitheader(struct http *hp, int req)
{
char *p, *q, **hh;
int n;
char buf[20];
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
if (req) {
memset(hp->req, 0, sizeof hp->req);
hh = hp->req;
} else {
memset(hp->resp, 0, sizeof hp->resp);
hh = hp->resp;
}
n = 0;
p = hp->rxbuf;
/* REQ/PROTO */
while (vct_islws(*p))
p++;
hh[n++] = p;
while (!vct_islws(*p))
p++;
assert(!vct_iscrlf(p));
*p++ = '\0';
/* URL/STATUS */
while (vct_issp(*p)) /* XXX: H space only */
p++;
assert(!vct_iscrlf(p));
hh[n++] = p;
while (!vct_islws(*p))
p++;
if (vct_iscrlf(p)) {
hh[n++] = NULL;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
} else {
*p++ = '\0';
/* PROTO/MSG */
while (vct_issp(*p)) /* XXX: H space only */
p++;
hh[n++] = p;
while (!vct_iscrlf(p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
assert(n == 3);
while (*p != '\0') {
assert(n < MAX_HDR);
if (vct_iscrlf(p))
break;
hh[n++] = p++;
while (*p != '\0' && !vct_iscrlf(p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
p += vct_skipcrlf(p);
assert(*p == '\0');
for (n = 0; n < 3 || hh[n] != NULL; n++) {
sprintf(buf, "http[%2d] ", n);
vtc_dump(hp->vl, 4, buf, hh[n], -1);
}
}
| 170,000 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mark_trusted_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | mark_trusted_task_done (GObject *source_object,
mark_desktop_file_executable_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
| 167,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem(
uint32_t id,
const download::DownloadCreateInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!base::ContainsKey(downloads_, id));
download::DownloadItemImpl* download =
item_factory_->CreateActiveItem(this, id, info);
downloads_[id] = base::WrapUnique(download);
downloads_by_guid_[download->GetGuid()] = download;
DownloadItemUtils::AttachInfo(
download, GetBrowserContext(),
WebContentsImpl::FromRenderFrameHostID(info.render_process_id,
info.render_frame_id));
return download;
}
Commit Message: Early return if a download Id is already used when creating a download
This is protect against download Id overflow and use-after-free
issue.
BUG=958533
Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485
Reviewed-by: Xing Liu <[email protected]>
Commit-Queue: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#656910}
CWE ID: CWE-416 | download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem(
uint32_t id,
const download::DownloadCreateInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (base::ContainsKey(downloads_, id))
return nullptr;
download::DownloadItemImpl* download =
item_factory_->CreateActiveItem(this, id, info);
downloads_[id] = base::WrapUnique(download);
downloads_by_guid_[download->GetGuid()] = download;
DownloadItemUtils::AttachInfo(
download, GetBrowserContext(),
WebContentsImpl::FromRenderFrameHostID(info.render_process_id,
info.render_frame_id));
return download;
}
| 172,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
q = (const uint8_t *)(const void *)
((const char *)(const void *)p +
CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t);
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%d) id=%x type=%x offs=%x,%d\n", i, inp[i].pi_id,
inp[i].pi_type, q - p, CDF_GETUINT32(p, (i << 1) + 1)));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %d\n", nelements));
for (j = 0; j < nelements; j++, i++) {
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %d, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
l = 4 + (uint32_t)CDF_ROUND(l, sizeof(l));
o += l >> 2;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
goto out;
}
}
return 0;
out:
free(*info);
return -1;
}
Commit Message: add more check found by cert's fuzzer.
CWE ID: CWE-119 | cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
q = (const uint8_t *)(const void *)
((const char *)(const void *)p +
CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t);
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%d) id=%x type=%x offs=%x,%d\n", i, inp[i].pi_id,
inp[i].pi_type, q - p, CDF_GETUINT32(p, (i << 1) + 1)));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %d\n", nelements));
for (j = 0; j < nelements; j++, i++) {
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %d, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
l = 4 + (uint32_t)CDF_ROUND(l, sizeof(l));
o += l >> 2;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
goto out;
}
}
return 0;
out:
free(*info);
return -1;
}
| 169,882 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
{
/* Absolute error permitted in linear values - affected by the bit depth of
* the calculations.
*/
if (pm->assume_16_bit_calculations ||
(pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxabs16;
else
return pm->maxabs8;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
static double abserr(const png_modifier *pm, int in_depth, int out_depth)
{
/* Absolute error permitted in linear values - affected by the bit depth of
* the calculations.
*/
if (pm->assume_16_bit_calculations ||
(pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxabs16;
else
return pm->maxabs8;
}
| 173,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftAMRNBEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->nBitRate = mBitRate;
amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + 1);
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
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_ChannelCF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = kSampleRate;
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 SoftAMRNBEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (!isValidOMXParam(amrParams)) {
return OMX_ErrorBadParameter;
}
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->nBitRate = mBitRate;
amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + 1);
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
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_ChannelCF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = kSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 v9fs_walk(void *opaque)
{
int name_idx;
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
pdu_complete(pdu, err);
return ;
}
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
for (i = 0; i < nwnames; i++) {
err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
if (err < 0) {
goto out_nofid;
}
if (name_is_illegal(wnames[i].data)) {
err = -ENOENT;
goto out_nofid;
}
offset += err;
}
} else if (nwnames > P9_MAXWELEM) {
err = -EINVAL;
goto out_nofid;
}
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_path_init(&dpath);
v9fs_path_init(&path);
/*
* Both dpath and path initially poin to fidp.
* Needed to handle request with nwnames == 0
*/
v9fs_path_copy(&dpath, &fidp->path);
err = -ENOENT;
goto out_nofid;
}
Commit Message:
CWE ID: CWE-22 | static void v9fs_walk(void *opaque)
{
int name_idx;
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
pdu_complete(pdu, err);
return ;
}
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
V9fsQID qid;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
for (i = 0; i < nwnames; i++) {
err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
if (err < 0) {
goto out_nofid;
}
if (name_is_illegal(wnames[i].data)) {
err = -ENOENT;
goto out_nofid;
}
offset += err;
}
} else if (nwnames > P9_MAXWELEM) {
err = -EINVAL;
goto out_nofid;
}
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_path_init(&dpath);
v9fs_path_init(&path);
/*
* Both dpath and path initially poin to fidp.
* Needed to handle request with nwnames == 0
*/
v9fs_path_copy(&dpath, &fidp->path);
err = -ENOENT;
goto out_nofid;
}
| 164,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.ExposeCapability("gpu",
service_manager::Manifest::InterfaceList<
metrics::mojom::CallStackProfileCollector>())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
chrome::mojom::AvailableOfflineContentProvider,
chrome::mojom::CacheStatsRecorder,
chrome::mojom::NetBenchmarking,
data_reduction_proxy::mojom::DataReductionProxy,
metrics::mojom::CallStackProfileCollector,
#if defined(OS_WIN)
mojom::ModuleEventSink,
#endif
rappor::mojom::RapporRecorder,
safe_browsing::mojom::SafeBrowsing>())
.RequireCapability("ash", "system_ui")
.RequireCapability("ash", "test")
.RequireCapability("ash", "display")
.RequireCapability("assistant", "assistant")
.RequireCapability("assistant_audio_decoder", "assistant:audio_decoder")
.RequireCapability("chrome", "input_device_controller")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("cups_ipp_parser", "ipp_parser")
.RequireCapability("device", "device:fingerprint")
.RequireCapability("device", "device:geolocation_config")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("device", "device:ip_geolocator")
.RequireCapability("ime", "input_engine")
.RequireCapability("mirroring", "mirroring")
.RequireCapability("nacl_broker", "browser")
.RequireCapability("nacl_loader", "browser")
.RequireCapability("noop", "noop")
.RequireCapability("patch", "patch_file")
.RequireCapability("preferences", "pref_client")
.RequireCapability("preferences", "pref_control")
.RequireCapability("profile_import", "import")
.RequireCapability("removable_storage_writer",
"removable_storage_writer")
.RequireCapability("secure_channel", "secure_channel")
.RequireCapability("ui", "ime_registrar")
.RequireCapability("ui", "input_device_controller")
.RequireCapability("ui", "window_manager")
.RequireCapability("unzip", "unzip_file")
.RequireCapability("util_win", "util_win")
.RequireCapability("xr_device_service", "xr_device_provider")
.RequireCapability("xr_device_service", "xr_device_test_hook")
#if defined(OS_CHROMEOS)
.RequireCapability("multidevice_setup", "multidevice_setup")
#endif
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
autofill::mojom::AutofillDriver,
autofill::mojom::PasswordManagerDriver,
chrome::mojom::OfflinePageAutoFetcher,
#if defined(OS_CHROMEOS)
chromeos_camera::mojom::CameraAppHelper,
chromeos::cellular_setup::mojom::CellularSetup,
chromeos::crostini_installer::mojom::PageHandlerFactory,
chromeos::crostini_upgrader::mojom::PageHandlerFactory,
chromeos::ime::mojom::InputEngineManager,
chromeos::machine_learning::mojom::PageHandler,
chromeos::media_perception::mojom::MediaPerception,
chromeos::multidevice_setup::mojom::MultiDeviceSetup,
chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter,
chromeos::network_config::mojom::CrosNetworkConfig,
cros::mojom::CameraAppDeviceProvider,
#endif
contextual_search::mojom::ContextualSearchJsApiService,
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::KeepAlive,
#endif
media::mojom::MediaEngagementScoreDetailsProvider,
media_router::mojom::MediaRouter,
page_load_metrics::mojom::PageLoadMetrics,
translate::mojom::ContentTranslateDriver,
downloads::mojom::PageHandlerFactory,
feed_internals::mojom::PageHandler,
new_tab_page::mojom::PageHandlerFactory,
#if defined(OS_ANDROID)
explore_sites_internals::mojom::PageHandler,
#else
app_management::mojom::PageHandlerFactory,
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
defined(OS_CHROMEOS)
discards::mojom::DetailsProvider, discards::mojom::GraphDump,
#endif
#if defined(OS_CHROMEOS)
add_supervision::mojom::AddSupervisionHandler,
#endif
mojom::BluetoothInternalsHandler,
mojom::InterventionsInternalsPageHandler,
mojom::OmniboxPageHandler, mojom::ResetPasswordHandler,
mojom::SiteEngagementDetailsProvider,
mojom::UsbInternalsPageHandler,
snippets_internals::mojom::PageHandlerFactory>())
.PackageService(prefs::GetManifest())
#if defined(OS_CHROMEOS)
.PackageService(chromeos::multidevice_setup::GetManifest())
#endif // defined(OS_CHROMEOS)
.Build()
};
return *manifest;
}
Commit Message: Revert "Creates a WebUI-based Crostini Upgrader"
This reverts commit 29c8bb394dd8b8c03e006efb39ec77fc42f96900.
Reason for revert:
Findit (https://goo.gl/kROfz5) identified CL at revision 717476 as the
culprit for failures in the build cycles as shown on:
https://analysis.chromium.org/waterfall/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyRAsSDVdmU3VzcGVjdGVkQ0wiMWNocm9taXVtLzI5YzhiYjM5NGRkOGI4YzAzZTAwNmVmYjM5ZWM3N2ZjNDJmOTY5MDAM
Sample Failed Build: https://ci.chromium.org/b/8896211200981346592
Sample Failed Step: compile
Original change's description:
> Creates a WebUI-based Crostini Upgrader
>
> The UI is behind the new crostini-webui-upgrader flag
> (currently disabled by default)
>
> The main areas for review are
>
> calamity@:
> html/js - chrome/browser/chromeos/crostini_upgrader/
> mojo and webui glue classes - chrome/browser/ui/webui/crostini_upgrader/
>
> davidmunro@
> crostini business logic - chrome/browser/chromeos/crostini/
>
> In this CL, the optional container backup stage is stubbed, and will be
> in a subsequent CL.
>
> A suite of unit/browser tests are also currently lacking. I intend them for
> follow-up CLs.
>
>
> Bug: 930901
> Change-Id: Ic52c5242e6c57232ffa6be5d6af65aaff5e8f4ff
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1900520
> Commit-Queue: Nicholas Verne <[email protected]>
> Reviewed-by: Sam McNally <[email protected]>
> Reviewed-by: calamity <[email protected]>
> Reviewed-by: Ken Rockot <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#717476}
Change-Id: I704f549216a7d1dc21942fbf6cf4ab9a1d600380
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 930901
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1928159
Cr-Commit-Position: refs/heads/master@{#717481}
CWE ID: CWE-20 | const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.ExposeCapability("gpu",
service_manager::Manifest::InterfaceList<
metrics::mojom::CallStackProfileCollector>())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
chrome::mojom::AvailableOfflineContentProvider,
chrome::mojom::CacheStatsRecorder,
chrome::mojom::NetBenchmarking,
data_reduction_proxy::mojom::DataReductionProxy,
metrics::mojom::CallStackProfileCollector,
#if defined(OS_WIN)
mojom::ModuleEventSink,
#endif
rappor::mojom::RapporRecorder,
safe_browsing::mojom::SafeBrowsing>())
.RequireCapability("ash", "system_ui")
.RequireCapability("ash", "test")
.RequireCapability("ash", "display")
.RequireCapability("assistant", "assistant")
.RequireCapability("assistant_audio_decoder", "assistant:audio_decoder")
.RequireCapability("chrome", "input_device_controller")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("cups_ipp_parser", "ipp_parser")
.RequireCapability("device", "device:fingerprint")
.RequireCapability("device", "device:geolocation_config")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("device", "device:ip_geolocator")
.RequireCapability("ime", "input_engine")
.RequireCapability("mirroring", "mirroring")
.RequireCapability("nacl_broker", "browser")
.RequireCapability("nacl_loader", "browser")
.RequireCapability("noop", "noop")
.RequireCapability("patch", "patch_file")
.RequireCapability("preferences", "pref_client")
.RequireCapability("preferences", "pref_control")
.RequireCapability("profile_import", "import")
.RequireCapability("removable_storage_writer",
"removable_storage_writer")
.RequireCapability("secure_channel", "secure_channel")
.RequireCapability("ui", "ime_registrar")
.RequireCapability("ui", "input_device_controller")
.RequireCapability("ui", "window_manager")
.RequireCapability("unzip", "unzip_file")
.RequireCapability("util_win", "util_win")
.RequireCapability("xr_device_service", "xr_device_provider")
.RequireCapability("xr_device_service", "xr_device_test_hook")
#if defined(OS_CHROMEOS)
.RequireCapability("multidevice_setup", "multidevice_setup")
#endif
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
autofill::mojom::AutofillDriver,
autofill::mojom::PasswordManagerDriver,
chrome::mojom::OfflinePageAutoFetcher,
#if defined(OS_CHROMEOS)
chromeos_camera::mojom::CameraAppHelper,
chromeos::cellular_setup::mojom::CellularSetup,
chromeos::crostini_installer::mojom::PageHandlerFactory,
chromeos::ime::mojom::InputEngineManager,
chromeos::machine_learning::mojom::PageHandler,
chromeos::media_perception::mojom::MediaPerception,
chromeos::multidevice_setup::mojom::MultiDeviceSetup,
chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter,
chromeos::network_config::mojom::CrosNetworkConfig,
cros::mojom::CameraAppDeviceProvider,
#endif
contextual_search::mojom::ContextualSearchJsApiService,
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::KeepAlive,
#endif
media::mojom::MediaEngagementScoreDetailsProvider,
media_router::mojom::MediaRouter,
page_load_metrics::mojom::PageLoadMetrics,
translate::mojom::ContentTranslateDriver,
downloads::mojom::PageHandlerFactory,
feed_internals::mojom::PageHandler,
new_tab_page::mojom::PageHandlerFactory,
#if defined(OS_ANDROID)
explore_sites_internals::mojom::PageHandler,
#else
app_management::mojom::PageHandlerFactory,
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
defined(OS_CHROMEOS)
discards::mojom::DetailsProvider, discards::mojom::GraphDump,
#endif
#if defined(OS_CHROMEOS)
add_supervision::mojom::AddSupervisionHandler,
#endif
mojom::BluetoothInternalsHandler,
mojom::InterventionsInternalsPageHandler,
mojom::OmniboxPageHandler, mojom::ResetPasswordHandler,
mojom::SiteEngagementDetailsProvider,
mojom::UsbInternalsPageHandler,
snippets_internals::mojom::PageHandlerFactory>())
.PackageService(prefs::GetManifest())
#if defined(OS_CHROMEOS)
.PackageService(chromeos::multidevice_setup::GetManifest())
#endif // defined(OS_CHROMEOS)
.Build()
};
return *manifest;
}
| 172,350 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_video::allocate_input_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned i = 0;
DEBUG_PRINT_HIGH("allocate_input_buffer()::");
if (bytes != m_sInPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]",
(unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_inp_mem_ptr) {
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual);
m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \
calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual);
if (m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr");
return OMX_ErrorInsufficientResources;
}
DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr);
m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual);
if (m_pInput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual);
if (m_pInput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
m_pInput_pmem[i].fd = -1;
#ifdef USE_ION
m_pInput_ion[i].ion_device_fd =-1;
m_pInput_ion[i].fd_ion_data.fd =-1;
m_pInput_ion[i].ion_alloc_data.handle = 0;
#endif
}
}
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_inp_bm_count,i)) {
break;
}
}
if (i < m_sInPortDef.nBufferCountActual) {
*bufferHdr = (m_inp_mem_ptr + i);
(*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION;
(*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize;
(*bufferHdr)->pAppPrivate = appData;
(*bufferHdr)->nInputPortIndex = PORT_INDEX_IN;
(*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i];
#ifdef USE_ION
#ifdef _MSM8974_
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,0);
#else
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pInput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd;
#else
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pInput_pmem[i].fd == 0) {
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pInput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pInput_pmem[i].size = m_sInPortDef.nBufferSize;
m_pInput_pmem[i].offset = 0;
m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pInput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pInput_pmem[i].fd,0);
if (m_pInput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno);
close(m_pInput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
} else {
m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
}
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer;
DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer);
BITMASK_SET(&m_inp_bm_count,i);
if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call"
"for index [%d]", i);
eRet = OMX_ErrorInsufficientResources;
}
return eRet;
}
Commit Message: DO NOT MERGE Fix wrong nAllocLen
Set nAllocLen to the size of the opaque handle itself.
Bug: 28816964
Bug: 28816827
Change-Id: Id410e324bee291d4a0018dddb97eda9bbcded099
CWE ID: CWE-119 | OMX_ERRORTYPE omx_video::allocate_input_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned i = 0;
DEBUG_PRINT_HIGH("allocate_input_buffer()::");
if (bytes != m_sInPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]",
(unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_inp_mem_ptr) {
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual);
m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \
calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual);
if (m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr");
return OMX_ErrorInsufficientResources;
}
DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr);
m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual);
if (m_pInput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual);
if (m_pInput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
m_pInput_pmem[i].fd = -1;
#ifdef USE_ION
m_pInput_ion[i].ion_device_fd =-1;
m_pInput_ion[i].fd_ion_data.fd =-1;
m_pInput_ion[i].ion_alloc_data.handle = 0;
#endif
}
}
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_inp_bm_count,i)) {
break;
}
}
if (i < m_sInPortDef.nBufferCountActual) {
*bufferHdr = (m_inp_mem_ptr + i);
(*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION;
(*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize;
(*bufferHdr)->pAppPrivate = appData;
(*bufferHdr)->nInputPortIndex = PORT_INDEX_IN;
(*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i];
#ifdef USE_ION
#ifdef _MSM8974_
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,0);
#else
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pInput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd;
#else
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pInput_pmem[i].fd == 0) {
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pInput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pInput_pmem[i].size = m_sInPortDef.nBufferSize;
m_pInput_pmem[i].offset = 0;
m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pInput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pInput_pmem[i].fd,0);
if (m_pInput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno);
close(m_pInput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
} else {
m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
(*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*);
}
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer;
DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer);
BITMASK_SET(&m_inp_bm_count,i);
if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call"
"for index [%d]", i);
eRet = OMX_ErrorInsufficientResources;
}
return eRet;
}
| 173,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: static Browser_Window *window_create(const char *url)
{
Browser_Window *app_data = malloc(sizeof(Browser_Window));
if (!app_data) {
info("ERROR: could not create browser window.\n");
return NULL;
}
/* Create window */
app_data->window = elm_win_add(NULL, "minibrowser-window", ELM_WIN_BASIC);
elm_win_title_set(app_data->window, APP_NAME);
evas_object_smart_callback_add(app_data->window, "delete,request", on_window_deletion, &app_data);
/* Create window background */
Evas_Object *bg = elm_bg_add(app_data->window);
elm_bg_color_set(bg, 193, 192, 191);
evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_win_resize_object_add(app_data->window, bg);
evas_object_show(bg);
/* Create vertical layout */
Evas_Object *vertical_layout = elm_box_add(app_data->window);
elm_box_padding_set(vertical_layout, 0, 2);
evas_object_size_hint_weight_set(vertical_layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_win_resize_object_add(app_data->window, vertical_layout);
evas_object_show(vertical_layout);
/* Create horizontal layout for top bar */
Evas_Object *horizontal_layout = elm_box_add(app_data->window);
elm_box_horizontal_set(horizontal_layout, EINA_TRUE);
evas_object_size_hint_weight_set(horizontal_layout, EVAS_HINT_EXPAND, 0.0);
evas_object_size_hint_align_set(horizontal_layout, EVAS_HINT_FILL, 0.0);
elm_box_pack_end(vertical_layout, horizontal_layout);
evas_object_show(horizontal_layout);
/* Create Back button */
app_data->back_button = create_toolbar_button(app_data->window, "arrow_left");
evas_object_smart_callback_add(app_data->back_button, "clicked", on_back_button_clicked, app_data);
elm_object_disabled_set(app_data->back_button, EINA_TRUE);
evas_object_size_hint_weight_set(app_data->back_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->back_button, 0.0, 0.5);
elm_box_pack_end(horizontal_layout, app_data->back_button);
evas_object_show(app_data->back_button);
/* Create Forward button */
app_data->forward_button = create_toolbar_button(app_data->window, "arrow_right");
evas_object_smart_callback_add(app_data->forward_button, "clicked", on_forward_button_clicked, app_data);
elm_object_disabled_set(app_data->forward_button, EINA_TRUE);
evas_object_size_hint_weight_set(app_data->forward_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->forward_button, 0.0, 0.5);
elm_box_pack_end(horizontal_layout, app_data->forward_button);
evas_object_show(app_data->forward_button);
/* Create URL bar */
app_data->url_bar = elm_entry_add(app_data->window);
elm_entry_scrollable_set(app_data->url_bar, EINA_TRUE);
elm_entry_scrollbar_policy_set(app_data->url_bar, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_OFF);
elm_entry_single_line_set(app_data->url_bar, EINA_TRUE);
elm_entry_cnp_mode_set(app_data->url_bar, ELM_CNP_MODE_PLAINTEXT);
elm_entry_text_style_user_push(app_data->url_bar, "DEFAULT='font_size=18'");
evas_object_smart_callback_add(app_data->url_bar, "activated", on_url_bar_activated, app_data);
evas_object_smart_callback_add(app_data->url_bar, "clicked", on_url_bar_clicked, app_data);
evas_object_size_hint_weight_set(app_data->url_bar, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->url_bar, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_box_pack_end(horizontal_layout, app_data->url_bar);
evas_object_show(app_data->url_bar);
/* Create Refresh button */
Evas_Object *refresh_button = create_toolbar_button(app_data->window, "refresh");
evas_object_smart_callback_add(refresh_button, "clicked", on_refresh_button_clicked, app_data);
evas_object_size_hint_weight_set(refresh_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(refresh_button, 1.0, 0.5);
elm_box_pack_end(horizontal_layout, refresh_button);
evas_object_show(refresh_button);
/* Create Home button */
Evas_Object *home_button = create_toolbar_button(app_data->window, "home");
evas_object_smart_callback_add(home_button, "clicked", on_home_button_clicked, app_data);
evas_object_size_hint_weight_set(home_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(home_button, 1.0, 0.5);
elm_box_pack_end(horizontal_layout, home_button);
evas_object_show(home_button);
/* Create webview */
Ewk_View_Smart_Class *ewkViewClass = miniBrowserViewSmartClass();
ewkViewClass->run_javascript_alert = on_javascript_alert;
ewkViewClass->run_javascript_confirm = on_javascript_confirm;
ewkViewClass->run_javascript_prompt = on_javascript_prompt;
Evas *evas = evas_object_evas_get(app_data->window);
Evas_Smart *smart = evas_smart_class_new(&ewkViewClass->sc);
app_data->webview = ewk_view_smart_add(evas, smart, ewk_context_default_get());
ewk_view_theme_set(app_data->webview, THEME_DIR "/default.edj");
Ewk_Settings *settings = ewk_view_settings_get(app_data->webview);
ewk_settings_file_access_from_file_urls_allowed_set(settings, EINA_TRUE);
ewk_settings_frame_flattening_enabled_set(settings, frame_flattening_enabled);
ewk_settings_developer_extras_enabled_set(settings, EINA_TRUE);
evas_object_smart_callback_add(app_data->webview, "authentication,request", on_authentication_request, app_data);
evas_object_smart_callback_add(app_data->webview, "close,window", on_close_window, app_data);
evas_object_smart_callback_add(app_data->webview, "create,window", on_new_window, app_data);
evas_object_smart_callback_add(app_data->webview, "download,failed", on_download_failed, app_data);
evas_object_smart_callback_add(app_data->webview, "download,finished", on_download_finished, app_data);
evas_object_smart_callback_add(app_data->webview, "download,request", on_download_request, app_data);
evas_object_smart_callback_add(app_data->webview, "file,chooser,request", on_file_chooser_request, app_data);
evas_object_smart_callback_add(app_data->webview, "icon,changed", on_view_icon_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "load,error", on_error, app_data);
evas_object_smart_callback_add(app_data->webview, "load,progress", on_progress, app_data);
evas_object_smart_callback_add(app_data->webview, "title,changed", on_title_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "url,changed", on_url_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "back,forward,list,changed", on_back_forward_list_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "tooltip,text,set", on_tooltip_text_set, app_data);
evas_object_smart_callback_add(app_data->webview, "tooltip,text,unset", on_tooltip_text_unset, app_data);
evas_object_event_callback_add(app_data->webview, EVAS_CALLBACK_KEY_DOWN, on_key_down, app_data);
evas_object_event_callback_add(app_data->webview, EVAS_CALLBACK_MOUSE_DOWN, on_mouse_down, app_data);
evas_object_size_hint_weight_set(app_data->webview, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->webview, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_box_pack_end(vertical_layout, app_data->webview);
evas_object_show(app_data->webview);
if (url)
ewk_view_url_set(app_data->webview, url);
evas_object_resize(app_data->window, DEFAULT_WIDTH, DEFAULT_HEIGHT);
evas_object_show(app_data->window);
view_focus_set(app_data, EINA_TRUE);
return app_data;
}
Commit Message: [EFL][WK2] Add --window-size command line option to EFL MiniBrowser
https://bugs.webkit.org/show_bug.cgi?id=100942
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-11-05
Reviewed by Kenneth Rohde Christiansen.
Added window-size (-s) command line option to EFL MiniBrowser.
* MiniBrowser/efl/main.c:
(window_create):
(parse_window_size):
(elm_main):
git-svn-id: svn://svn.chromium.org/blink/trunk@133450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static Browser_Window *window_create(const char *url)
{
Browser_Window *app_data = malloc(sizeof(Browser_Window));
if (!app_data) {
info("ERROR: could not create browser window.\n");
return NULL;
}
/* Create window */
app_data->window = elm_win_add(NULL, "minibrowser-window", ELM_WIN_BASIC);
elm_win_title_set(app_data->window, APP_NAME);
evas_object_smart_callback_add(app_data->window, "delete,request", on_window_deletion, &app_data);
/* Create window background */
Evas_Object *bg = elm_bg_add(app_data->window);
elm_bg_color_set(bg, 193, 192, 191);
evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_win_resize_object_add(app_data->window, bg);
evas_object_show(bg);
/* Create vertical layout */
Evas_Object *vertical_layout = elm_box_add(app_data->window);
elm_box_padding_set(vertical_layout, 0, 2);
evas_object_size_hint_weight_set(vertical_layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_win_resize_object_add(app_data->window, vertical_layout);
evas_object_show(vertical_layout);
/* Create horizontal layout for top bar */
Evas_Object *horizontal_layout = elm_box_add(app_data->window);
elm_box_horizontal_set(horizontal_layout, EINA_TRUE);
evas_object_size_hint_weight_set(horizontal_layout, EVAS_HINT_EXPAND, 0.0);
evas_object_size_hint_align_set(horizontal_layout, EVAS_HINT_FILL, 0.0);
elm_box_pack_end(vertical_layout, horizontal_layout);
evas_object_show(horizontal_layout);
/* Create Back button */
app_data->back_button = create_toolbar_button(app_data->window, "arrow_left");
evas_object_smart_callback_add(app_data->back_button, "clicked", on_back_button_clicked, app_data);
elm_object_disabled_set(app_data->back_button, EINA_TRUE);
evas_object_size_hint_weight_set(app_data->back_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->back_button, 0.0, 0.5);
elm_box_pack_end(horizontal_layout, app_data->back_button);
evas_object_show(app_data->back_button);
/* Create Forward button */
app_data->forward_button = create_toolbar_button(app_data->window, "arrow_right");
evas_object_smart_callback_add(app_data->forward_button, "clicked", on_forward_button_clicked, app_data);
elm_object_disabled_set(app_data->forward_button, EINA_TRUE);
evas_object_size_hint_weight_set(app_data->forward_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->forward_button, 0.0, 0.5);
elm_box_pack_end(horizontal_layout, app_data->forward_button);
evas_object_show(app_data->forward_button);
/* Create URL bar */
app_data->url_bar = elm_entry_add(app_data->window);
elm_entry_scrollable_set(app_data->url_bar, EINA_TRUE);
elm_entry_scrollbar_policy_set(app_data->url_bar, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_OFF);
elm_entry_single_line_set(app_data->url_bar, EINA_TRUE);
elm_entry_cnp_mode_set(app_data->url_bar, ELM_CNP_MODE_PLAINTEXT);
elm_entry_text_style_user_push(app_data->url_bar, "DEFAULT='font_size=18'");
evas_object_smart_callback_add(app_data->url_bar, "activated", on_url_bar_activated, app_data);
evas_object_smart_callback_add(app_data->url_bar, "clicked", on_url_bar_clicked, app_data);
evas_object_size_hint_weight_set(app_data->url_bar, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->url_bar, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_box_pack_end(horizontal_layout, app_data->url_bar);
evas_object_show(app_data->url_bar);
/* Create Refresh button */
Evas_Object *refresh_button = create_toolbar_button(app_data->window, "refresh");
evas_object_smart_callback_add(refresh_button, "clicked", on_refresh_button_clicked, app_data);
evas_object_size_hint_weight_set(refresh_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(refresh_button, 1.0, 0.5);
elm_box_pack_end(horizontal_layout, refresh_button);
evas_object_show(refresh_button);
/* Create Home button */
Evas_Object *home_button = create_toolbar_button(app_data->window, "home");
evas_object_smart_callback_add(home_button, "clicked", on_home_button_clicked, app_data);
evas_object_size_hint_weight_set(home_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(home_button, 1.0, 0.5);
elm_box_pack_end(horizontal_layout, home_button);
evas_object_show(home_button);
/* Create webview */
Ewk_View_Smart_Class *ewkViewClass = miniBrowserViewSmartClass();
ewkViewClass->run_javascript_alert = on_javascript_alert;
ewkViewClass->run_javascript_confirm = on_javascript_confirm;
ewkViewClass->run_javascript_prompt = on_javascript_prompt;
Evas *evas = evas_object_evas_get(app_data->window);
Evas_Smart *smart = evas_smart_class_new(&ewkViewClass->sc);
app_data->webview = ewk_view_smart_add(evas, smart, ewk_context_default_get());
ewk_view_theme_set(app_data->webview, THEME_DIR "/default.edj");
Ewk_Settings *settings = ewk_view_settings_get(app_data->webview);
ewk_settings_file_access_from_file_urls_allowed_set(settings, EINA_TRUE);
ewk_settings_frame_flattening_enabled_set(settings, frame_flattening_enabled);
ewk_settings_developer_extras_enabled_set(settings, EINA_TRUE);
evas_object_smart_callback_add(app_data->webview, "authentication,request", on_authentication_request, app_data);
evas_object_smart_callback_add(app_data->webview, "close,window", on_close_window, app_data);
evas_object_smart_callback_add(app_data->webview, "create,window", on_new_window, app_data);
evas_object_smart_callback_add(app_data->webview, "download,failed", on_download_failed, app_data);
evas_object_smart_callback_add(app_data->webview, "download,finished", on_download_finished, app_data);
evas_object_smart_callback_add(app_data->webview, "download,request", on_download_request, app_data);
evas_object_smart_callback_add(app_data->webview, "file,chooser,request", on_file_chooser_request, app_data);
evas_object_smart_callback_add(app_data->webview, "icon,changed", on_view_icon_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "load,error", on_error, app_data);
evas_object_smart_callback_add(app_data->webview, "load,progress", on_progress, app_data);
evas_object_smart_callback_add(app_data->webview, "title,changed", on_title_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "url,changed", on_url_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "back,forward,list,changed", on_back_forward_list_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "tooltip,text,set", on_tooltip_text_set, app_data);
evas_object_smart_callback_add(app_data->webview, "tooltip,text,unset", on_tooltip_text_unset, app_data);
evas_object_event_callback_add(app_data->webview, EVAS_CALLBACK_KEY_DOWN, on_key_down, app_data);
evas_object_event_callback_add(app_data->webview, EVAS_CALLBACK_MOUSE_DOWN, on_mouse_down, app_data);
evas_object_size_hint_weight_set(app_data->webview, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->webview, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_box_pack_end(vertical_layout, app_data->webview);
evas_object_show(app_data->webview);
if (url)
ewk_view_url_set(app_data->webview, url);
evas_object_resize(app_data->window, window_width, window_height);
evas_object_show(app_data->window);
view_focus_set(app_data, EINA_TRUE);
return app_data;
}
| 170,910 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
struct ring_buffer *buf;
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&tr->max_lock);
buf = tr->trace_buffer.buffer;
tr->trace_buffer.buffer = tr->max_buffer.buffer;
tr->max_buffer.buffer = buf;
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&tr->max_lock);
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787 | update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&tr->max_lock);
swap(tr->trace_buffer.buffer, tr->max_buffer.buffer);
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&tr->max_lock);
}
| 169,185 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if ((int)shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1 || vstart + vdaux < vstart) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Commit Message: Fix #8764 a 3rd time since 2nd time is UB and can be optimized away
CWE ID: CWE-476 | static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if ((int)shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
size_t vstart_off = i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1 || shdr->sh_size - vstart_off < vdaux) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
vstart_off += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
vstart_off += aux.vda_next;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
| 170,014 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mk_request_error(int http_status, struct client_session *cs,
struct session_request *sr) {
int ret, fd;
mk_ptr_t message, *page = 0;
struct error_page *entry;
struct mk_list *head;
struct file_info finfo;
mk_header_set_http_status(sr, http_status);
/*
* We are nice sending error pages for clients who at least respect
* the especification
*/
if (http_status != MK_CLIENT_LENGTH_REQUIRED &&
http_status != MK_CLIENT_BAD_REQUEST &&
http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) {
/* Lookup a customized error page */
mk_list_foreach(head, &sr->host_conf->error_pages) {
entry = mk_list_entry(head, struct error_page, _head);
if (entry->status != http_status) {
continue;
}
/* validate error file */
ret = mk_file_get_info(entry->real_path, &finfo);
if (ret == -1) {
break;
}
/* open file */
fd = open(entry->real_path, config->open_flags);
if (fd == -1) {
break;
}
sr->fd_file = fd;
sr->bytes_to_send = finfo.size;
sr->headers.content_length = finfo.size;
sr->headers.real_length = finfo.size;
memcpy(&sr->file_info, &finfo, sizeof(struct file_info));
mk_header_send(cs->socket, cs, sr);
return mk_http_send_file(cs, sr);
}
}
mk_ptr_reset(&message);
switch (http_status) {
case MK_CLIENT_BAD_REQUEST:
page = mk_request_set_default_page("Bad Request",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_FORBIDDEN:
page = mk_request_set_default_page("Forbidden",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_NOT_FOUND:
mk_string_build(&message.data, &message.len,
"The requested URL was not found on this server.");
page = mk_request_set_default_page("Not Found",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE:
mk_string_build(&message.data, &message.len,
"The request entity is too large.");
page = mk_request_set_default_page("Entity too large",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_METHOD_NOT_ALLOWED:
page = mk_request_set_default_page("Method Not Allowed",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_REQUEST_TIMEOUT:
case MK_CLIENT_LENGTH_REQUIRED:
break;
case MK_SERVER_NOT_IMPLEMENTED:
page = mk_request_set_default_page("Method Not Implemented",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_INTERNAL_ERROR:
page = mk_request_set_default_page("Internal Server Error",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_HTTP_VERSION_UNSUP:
mk_ptr_reset(&message);
page = mk_request_set_default_page("HTTP Version Not Supported",
message,
sr->host_conf->host_signature);
break;
}
if (page) {
sr->headers.content_length = page->len;
}
sr->headers.location = NULL;
sr->headers.cgi = SH_NOCGI;
sr->headers.pconnections_left = 0;
sr->headers.last_modified = -1;
if (!page) {
mk_ptr_reset(&sr->headers.content_type);
}
else {
mk_ptr_set(&sr->headers.content_type, "text/html\r\n");
}
mk_header_send(cs->socket, cs, sr);
if (page) {
if (sr->method != MK_HTTP_METHOD_HEAD)
mk_socket_send(cs->socket, page->data, page->len);
mk_ptr_free(page);
mk_mem_free(page);
}
/* Turn off TCP_CORK */
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return EXIT_ERROR;
}
Commit Message: Request: new request session flag to mark those files opened by FDT
This patch aims to fix a potential DDoS problem that can be caused
in the server quering repetitive non-existent resources.
When serving a static file, the core use Vhost FDT mechanism, but if
it sends a static error page it does a direct open(2). When closing
the resources for the same request it was just calling mk_vhost_close()
which did not clear properly the file descriptor.
This patch adds a new field on the struct session_request called 'fd_is_fdt',
which contains MK_TRUE or MK_FALSE depending of how fd_file was opened.
Thanks to Matthew Daley <[email protected]> for report and troubleshoot this
problem.
Signed-off-by: Eduardo Silva <[email protected]>
CWE ID: CWE-20 | int mk_request_error(int http_status, struct client_session *cs,
struct session_request *sr) {
int ret, fd;
mk_ptr_t message, *page = 0;
struct error_page *entry;
struct mk_list *head;
struct file_info finfo;
mk_header_set_http_status(sr, http_status);
/*
* We are nice sending error pages for clients who at least respect
* the especification
*/
if (http_status != MK_CLIENT_LENGTH_REQUIRED &&
http_status != MK_CLIENT_BAD_REQUEST &&
http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) {
/* Lookup a customized error page */
mk_list_foreach(head, &sr->host_conf->error_pages) {
entry = mk_list_entry(head, struct error_page, _head);
if (entry->status != http_status) {
continue;
}
/* validate error file */
ret = mk_file_get_info(entry->real_path, &finfo);
if (ret == -1) {
break;
}
/* open file */
fd = open(entry->real_path, config->open_flags);
if (fd == -1) {
break;
}
sr->fd_file = fd;
sr->fd_is_fdt = MK_FALSE;
sr->bytes_to_send = finfo.size;
sr->headers.content_length = finfo.size;
sr->headers.real_length = finfo.size;
memcpy(&sr->file_info, &finfo, sizeof(struct file_info));
mk_header_send(cs->socket, cs, sr);
return mk_http_send_file(cs, sr);
}
}
mk_ptr_reset(&message);
switch (http_status) {
case MK_CLIENT_BAD_REQUEST:
page = mk_request_set_default_page("Bad Request",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_FORBIDDEN:
page = mk_request_set_default_page("Forbidden",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_NOT_FOUND:
mk_string_build(&message.data, &message.len,
"The requested URL was not found on this server.");
page = mk_request_set_default_page("Not Found",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE:
mk_string_build(&message.data, &message.len,
"The request entity is too large.");
page = mk_request_set_default_page("Entity too large",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_METHOD_NOT_ALLOWED:
page = mk_request_set_default_page("Method Not Allowed",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_REQUEST_TIMEOUT:
case MK_CLIENT_LENGTH_REQUIRED:
break;
case MK_SERVER_NOT_IMPLEMENTED:
page = mk_request_set_default_page("Method Not Implemented",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_INTERNAL_ERROR:
page = mk_request_set_default_page("Internal Server Error",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_HTTP_VERSION_UNSUP:
mk_ptr_reset(&message);
page = mk_request_set_default_page("HTTP Version Not Supported",
message,
sr->host_conf->host_signature);
break;
}
if (page) {
sr->headers.content_length = page->len;
}
sr->headers.location = NULL;
sr->headers.cgi = SH_NOCGI;
sr->headers.pconnections_left = 0;
sr->headers.last_modified = -1;
if (!page) {
mk_ptr_reset(&sr->headers.content_type);
}
else {
mk_ptr_set(&sr->headers.content_type, "text/html\r\n");
}
mk_header_send(cs->socket, cs, sr);
if (page) {
if (sr->method != MK_HTTP_METHOD_HEAD)
mk_socket_send(cs->socket, page->data, page->len);
mk_ptr_free(page);
mk_mem_free(page);
}
/* Turn off TCP_CORK */
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return EXIT_ERROR;
}
| 166,276 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
struct Curl_easy *data = connssl->data;
const char *nickname = connssl->client_nickname;
if(connssl->obj_clicert) {
/* use the cert/key provided by PEM reader */
static const char pem_slotname[] = "PEM Token #1";
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
struct CERTCertificateStr *cert;
struct SECKEYPrivateKeyStr *key;
PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
if(NULL == slot) {
failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
return SECFailure;
}
if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
return SECFailure;
}
cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
SECITEM_FreeItem(&cert_der, PR_FALSE);
if(NULL == cert) {
failf(data, "NSS: client certificate from file not found");
PK11_FreeSlot(slot);
return SECFailure;
}
key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
PK11_FreeSlot(slot);
if(NULL == key) {
failf(data, "NSS: private key from file not found");
CERT_DestroyCertificate(cert);
return SECFailure;
}
infof(data, "NSS: client certificate from file\n");
display_cert_info(data, cert);
*pRetCert = cert;
*pRetKey = key;
return SECSuccess;
}
/* use the default NSS hook */
if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
pRetCert, pRetKey)
|| NULL == *pRetCert) {
if(NULL == nickname)
failf(data, "NSS: client certificate not found (nickname not "
"specified)");
else
failf(data, "NSS: client certificate not found: %s", nickname);
return SECFailure;
}
/* get certificate nickname if any */
nickname = (*pRetCert)->nickname;
if(NULL == nickname)
nickname = "[unknown]";
if(NULL == *pRetKey) {
failf(data, "NSS: private key not found for certificate: %s", nickname);
return SECFailure;
}
infof(data, "NSS: using client certificate: %s\n", nickname);
display_cert_info(data, *pRetCert);
return SECSuccess;
}
Commit Message: nss: refuse previously loaded certificate from file
... when we are not asked to use a certificate from file
CWE ID: CWE-287 | static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
struct Curl_easy *data = connssl->data;
const char *nickname = connssl->client_nickname;
static const char pem_slotname[] = "PEM Token #1";
if(connssl->obj_clicert) {
/* use the cert/key provided by PEM reader */
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
struct CERTCertificateStr *cert;
struct SECKEYPrivateKeyStr *key;
PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
if(NULL == slot) {
failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
return SECFailure;
}
if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
return SECFailure;
}
cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
SECITEM_FreeItem(&cert_der, PR_FALSE);
if(NULL == cert) {
failf(data, "NSS: client certificate from file not found");
PK11_FreeSlot(slot);
return SECFailure;
}
key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
PK11_FreeSlot(slot);
if(NULL == key) {
failf(data, "NSS: private key from file not found");
CERT_DestroyCertificate(cert);
return SECFailure;
}
infof(data, "NSS: client certificate from file\n");
display_cert_info(data, cert);
*pRetCert = cert;
*pRetKey = key;
return SECSuccess;
}
/* use the default NSS hook */
if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
pRetCert, pRetKey)
|| NULL == *pRetCert) {
if(NULL == nickname)
failf(data, "NSS: client certificate not found (nickname not "
"specified)");
else
failf(data, "NSS: client certificate not found: %s", nickname);
return SECFailure;
}
/* get certificate nickname if any */
nickname = (*pRetCert)->nickname;
if(NULL == nickname)
nickname = "[unknown]";
if(!strncmp(nickname, pem_slotname, sizeof(pem_slotname) - 1U)) {
failf(data, "NSS: refusing previously loaded certificate from file: %s",
nickname);
return SECFailure;
}
if(NULL == *pRetKey) {
failf(data, "NSS: private key not found for certificate: %s", nickname);
return SECFailure;
}
infof(data, "NSS: using client certificate: %s\n", nickname);
display_cert_info(data, *pRetCert);
return SECSuccess;
}
| 166,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PageRequestSummary::UpdateOrAddToOrigins(
const GURL& url,
const content::mojom::CommonNetworkInfoPtr& network_info) {
GURL origin = url.GetOrigin();
if (!origin.is_valid())
return;
auto it = origins.find(origin);
if (it == origins.end()) {
OriginRequestSummary summary;
summary.origin = origin;
summary.first_occurrence = origins.size();
it = origins.insert({origin, summary}).first;
}
it->second.always_access_network |= network_info->always_access_network;
it->second.accessed_network |= network_info->network_accessed;
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | void PageRequestSummary::UpdateOrAddToOrigins(
const url::Origin& origin,
const content::mojom::CommonNetworkInfoPtr& network_info) {
if (origin.opaque())
return;
auto it = origins.find(origin);
if (it == origins.end()) {
OriginRequestSummary summary;
summary.origin = origin;
summary.first_occurrence = origins.size();
it = origins.insert({origin, summary}).first;
}
it->second.always_access_network |= network_info->always_access_network;
it->second.accessed_network |= network_info->network_accessed;
}
| 172,368 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: FrameView::FrameView(LocalFrame* frame)
: m_frame(frame)
, m_canHaveScrollbars(true)
, m_slowRepaintObjectCount(0)
, m_hasPendingLayout(false)
, m_layoutSubtreeRoot(0)
, m_inSynchronousPostLayout(false)
, m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
, m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
, m_isTransparent(false)
, m_baseBackgroundColor(Color::white)
, m_mediaType("screen")
, m_overflowStatusDirty(true)
, m_viewportRenderer(0)
, m_wasScrolledByUser(false)
, m_inProgrammaticScroll(false)
, m_safeToPropagateScrollToParent(true)
, m_isTrackingPaintInvalidations(false)
, m_scrollCorner(nullptr)
, m_hasSoftwareFilters(false)
, m_visibleContentScaleFactor(1)
, m_inputEventsScaleFactorForEmulation(1)
, m_layoutSizeFixedToFrameSize(true)
, m_didScrollTimer(this, &FrameView::didScrollTimerFired)
{
ASSERT(m_frame);
init();
if (!m_frame->isMainFrame())
return;
ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
[email protected]
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416 | FrameView::FrameView(LocalFrame* frame)
: m_frame(frame)
, m_canHaveScrollbars(true)
, m_slowRepaintObjectCount(0)
, m_hasPendingLayout(false)
, m_layoutSubtreeRoot(0)
, m_inSynchronousPostLayout(false)
, m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
, m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
, m_isTransparent(false)
, m_baseBackgroundColor(Color::white)
, m_mediaType("screen")
, m_overflowStatusDirty(true)
, m_viewportRenderer(0)
, m_wasScrolledByUser(false)
, m_inProgrammaticScroll(false)
, m_safeToPropagateScrollToParent(true)
, m_isTrackingPaintInvalidations(false)
, m_scrollCorner(nullptr)
, m_hasSoftwareFilters(false)
, m_visibleContentScaleFactor(1)
, m_inputEventsScaleFactorForEmulation(1)
, m_layoutSizeFixedToFrameSize(true)
, m_didScrollTimer(this, &FrameView::didScrollTimerFired)
, m_needsUpdateWidgetPositions(false)
{
ASSERT(m_frame);
init();
if (!m_frame->isMainFrame())
return;
ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
}
| 171,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms)
return NULL;
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125 | struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) {
return NULL;
}
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
}
| 169,225 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: apprentice_load(struct magic_set *ms, const char *fn, int action)
{
int errs = 0;
uint32_t i, j;
size_t files = 0, maxfiles = 0;
char **filearr = NULL;
struct stat st;
struct magic_map *map;
struct magic_entry_set mset[MAGIC_SETS];
php_stream *dir;
php_stream_dirent d;
TSRMLS_FETCH();
memset(mset, 0, sizeof(mset));
ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
{
file_oomem(ms, sizeof(*map));
return NULL;
}
/* print silly verbose header for USG compat. */
if (action == FILE_CHECK)
(void)fprintf(stderr, "%s\n", usg_hdr);
/* load directory or file */
/* FIXME: Read file names and sort them to prevent
non-determinism. See Debian bug #488562. */
if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
int mflen;
char mfn[MAXPATHLEN];
dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
if (!dir) {
errs++;
goto out;
}
while (php_stream_readdir(dir, &d)) {
if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
file_oomem(ms,
strlen(fn) + strlen(d.d_name) + 2);
errs++;
php_stream_closedir(dir);
goto out;
}
if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
continue;
}
if (files >= maxfiles) {
size_t mlen;
maxfiles = (maxfiles + 1) * 2;
mlen = maxfiles * sizeof(*filearr);
if ((filearr = CAST(char **,
erealloc(filearr, mlen))) == NULL) {
file_oomem(ms, mlen);
efree(mfn);
php_stream_closedir(dir);
errs++;
goto out;
goto out;
}
}
filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
}
php_stream_closedir(dir);
qsort(filearr, files, sizeof(*filearr), cmpstrp);
for (i = 0; i < files; i++) {
load_1(ms, action, filearr[i], &errs, mset);
efree(filearr[i]);
}
efree(filearr);
} else
load_1(ms, action, fn, &errs, mset);
if (errs)
goto out;
for (j = 0; j < MAGIC_SETS; j++) {
/* Set types of tests */
for (i = 0; i < mset[j].count; ) {
if (mset[j].me[i].mp->cont_level != 0) {
i++;
continue;
}
i = set_text_binary(ms, mset[j].me, mset[j].count, i);
}
qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
apprentice_sort);
/*
* Make sure that any level 0 "default" line is last
* (if one exists).
*/
set_last_default(ms, mset[j].me, mset[j].count);
/* coalesce per file arrays into a single one */
if (coalesce_entries(ms, mset[j].me, mset[j].count,
&map->magic[j], &map->nmagic[j]) == -1) {
errs++;
goto out;
}
}
out:
for (j = 0; j < MAGIC_SETS; j++)
magic_entry_free(mset[j].me, mset[j].count);
if (errs) {
for (j = 0; j < MAGIC_SETS; j++) {
if (map->magic[j])
efree(map->magic[j]);
}
efree(map);
return NULL;
}
return map;
}
Commit Message:
CWE ID: CWE-17 | apprentice_load(struct magic_set *ms, const char *fn, int action)
{
int errs = 0;
uint32_t i, j;
size_t files = 0, maxfiles = 0;
char **filearr = NULL;
struct stat st;
struct magic_map *map;
struct magic_entry_set mset[MAGIC_SETS];
php_stream *dir;
php_stream_dirent d;
TSRMLS_FETCH();
memset(mset, 0, sizeof(mset));
ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
{
file_oomem(ms, sizeof(*map));
return NULL;
}
/* print silly verbose header for USG compat. */
if (action == FILE_CHECK)
(void)fprintf(stderr, "%s\n", usg_hdr);
/* load directory or file */
/* FIXME: Read file names and sort them to prevent
non-determinism. See Debian bug #488562. */
if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
int mflen;
char mfn[MAXPATHLEN];
dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
if (!dir) {
errs++;
goto out;
}
while (php_stream_readdir(dir, &d)) {
if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
file_oomem(ms,
strlen(fn) + strlen(d.d_name) + 2);
errs++;
php_stream_closedir(dir);
goto out;
}
if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
continue;
}
if (files >= maxfiles) {
size_t mlen;
maxfiles = (maxfiles + 1) * 2;
mlen = maxfiles * sizeof(*filearr);
if ((filearr = CAST(char **,
erealloc(filearr, mlen))) == NULL) {
file_oomem(ms, mlen);
php_stream_closedir(dir);
errs++;
goto out;
goto out;
}
}
filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
}
php_stream_closedir(dir);
qsort(filearr, files, sizeof(*filearr), cmpstrp);
for (i = 0; i < files; i++) {
load_1(ms, action, filearr[i], &errs, mset);
efree(filearr[i]);
}
efree(filearr);
} else
load_1(ms, action, fn, &errs, mset);
if (errs)
goto out;
for (j = 0; j < MAGIC_SETS; j++) {
/* Set types of tests */
for (i = 0; i < mset[j].count; ) {
if (mset[j].me[i].mp->cont_level != 0) {
i++;
continue;
}
i = set_text_binary(ms, mset[j].me, mset[j].count, i);
}
qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
apprentice_sort);
/*
* Make sure that any level 0 "default" line is last
* (if one exists).
*/
set_last_default(ms, mset[j].me, mset[j].count);
/* coalesce per file arrays into a single one */
if (coalesce_entries(ms, mset[j].me, mset[j].count,
&map->magic[j], &map->nmagic[j]) == -1) {
errs++;
goto out;
}
}
out:
for (j = 0; j < MAGIC_SETS; j++)
magic_entry_free(mset[j].me, mset[j].count);
if (errs) {
for (j = 0; j < MAGIC_SETS; j++) {
if (map->magic[j])
efree(map->magic[j]);
}
efree(map);
return NULL;
}
return map;
}
| 164,882 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if ((temp_buffer & 0xffffff00) != 0x100)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer < 0x120)
VO++;
else if (temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
}
Commit Message: m4vdec: Check for non-startcode 00 00 00 sequences in probe
This makes the m4v detection less trigger-happy.
Bug-Id: 949
Signed-off-by: Diego Biurrun <[email protected]>
CWE ID: CWE-476 | static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if (temp_buffer & 0xfffffe00)
continue;
if (temp_buffer < 2)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer >= 0x100 && temp_buffer < 0x120)
VO++;
else if (temp_buffer >= 0x120 && temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
}
| 168,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bool shouldSetStrutOnBlock(const LayoutBlockFlow& block, const RootInlineBox& lineBox, LayoutUnit lineLogicalOffset, int lineIndex, LayoutUnit remainingLogicalHeight)
{
bool wantsStrutOnBlock = false;
if (!block.style()->hasAutoOrphans() && block.style()->orphans() >= lineIndex) {
wantsStrutOnBlock = true;
} else if (lineBox == block.firstRootBox() && lineLogicalOffset == block.borderAndPaddingBefore()) {
LayoutUnit lineHeight = lineBox.lineBottomWithLeading() - lineBox.lineTopWithLeading();
LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, lineLogicalOffset);
LayoutUnit pageLogicalHeightAtNewOffset = block.pageLogicalHeightForOffset(lineLogicalOffset + remainingLogicalHeight);
if (totalLogicalHeight < pageLogicalHeightAtNewOffset)
wantsStrutOnBlock = true;
}
if (!wantsStrutOnBlock || block.isOutOfFlowPositioned())
return false;
LayoutBlock* containingBlock = block.containingBlock();
return containingBlock && containingBlock->isLayoutBlockFlow();
}
Commit Message: Consistently check if a block can handle pagination strut propagation.
https://codereview.chromium.org/1360753002 got it right for inline child
layout, but did nothing for block child layout.
BUG=329421
[email protected],[email protected]
Review URL: https://codereview.chromium.org/1387553002
Cr-Commit-Position: refs/heads/master@{#352429}
CWE ID: CWE-22 | static inline bool shouldSetStrutOnBlock(const LayoutBlockFlow& block, const RootInlineBox& lineBox, LayoutUnit lineLogicalOffset, int lineIndex, LayoutUnit remainingLogicalHeight)
{
bool wantsStrutOnBlock = false;
if (!block.style()->hasAutoOrphans() && block.style()->orphans() >= lineIndex) {
wantsStrutOnBlock = true;
} else if (lineBox == block.firstRootBox() && lineLogicalOffset == block.borderAndPaddingBefore()) {
LayoutUnit lineHeight = lineBox.lineBottomWithLeading() - lineBox.lineTopWithLeading();
LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, lineLogicalOffset);
LayoutUnit pageLogicalHeightAtNewOffset = block.pageLogicalHeightForOffset(lineLogicalOffset + remainingLogicalHeight);
if (totalLogicalHeight < pageLogicalHeightAtNewOffset)
wantsStrutOnBlock = true;
}
return wantsStrutOnBlock && block.allowsPaginationStrut();
}
| 171,694 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hash_foreach_stringify (gpointer key, gpointer val, gpointer user_data)
{
const char *keystr = key;
const GValue *value = val;
GValue *sval;
GHashTable *ret = user_data;
sval = g_new0 (GValue, 1);
g_value_init (sval, G_TYPE_STRING);
if (!g_value_transform (value, sval))
g_assert_not_reached ();
g_hash_table_insert (ret, g_strdup (keystr), sval);
}
Commit Message:
CWE ID: CWE-264 | hash_foreach_stringify (gpointer key, gpointer val, gpointer user_data)
| 165,087 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ShellWindowFrameView::Layout() {
gfx::Size close_size = close_button_->GetPreferredSize();
int closeButtonOffsetY =
(kCaptionHeight - close_size.height()) / 2;
int closeButtonOffsetX = closeButtonOffsetY;
close_button_->SetBounds(
width() - closeButtonOffsetX - close_size.width(),
closeButtonOffsetY,
close_size.width(),
close_size.height());
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | void ShellWindowFrameView::Layout() {
if (is_frameless_)
return;
gfx::Size close_size = close_button_->GetPreferredSize();
int closeButtonOffsetY =
(kCaptionHeight - close_size.height()) / 2;
int closeButtonOffsetX = closeButtonOffsetY;
close_button_->SetBounds(
width() - closeButtonOffsetX - close_size.width(),
closeButtonOffsetY,
close_size.width(),
close_size.height());
}
| 170,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) {
base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (url_scheme.empty())
return base::string16();
wchar_t out_buffer[1024];
DWORD buffer_size = arraysize(out_buffer);
HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL,
ASSOCSTR_FRIENDLYAPPNAME,
url_scheme.c_str(),
NULL,
out_buffer,
&buffer_size);
if (FAILED(hr)) {
DLOG(WARNING) << "AssocQueryString failed!";
return base::string16();
}
return base::string16(out_buffer);
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597611}
CWE ID: CWE-20 | base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) {
const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (!IsValidCustomProtocol(url_scheme))
return base::string16();
wchar_t out_buffer[1024];
DWORD buffer_size = arraysize(out_buffer);
HRESULT hr =
AssocQueryString(ASSOCF_IS_PROTOCOL, ASSOCSTR_FRIENDLYAPPNAME,
url_scheme.c_str(), NULL, out_buffer, &buffer_size);
if (FAILED(hr)) {
DLOG(WARNING) << "AssocQueryString failed!";
return base::string16();
}
return base::string16(out_buffer);
}
| 172,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CtcpHandler::parse(Message::Type messageType, const QString &prefix, const QString &target, const QByteArray &message) {
QByteArray ctcp;
QByteArray dequotedMessage = lowLevelDequote(message);
CtcpType ctcptype = messageType == Message::Notice
? CtcpReply
: CtcpQuery;
Message::Flags flags = (messageType == Message::Notice && !network()->isChannelName(target))
? Message::Redirected
: Message::None;
int xdelimPos = -1;
int xdelimEndPos = -1;
int spacePos = -1;
while((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) {
if(xdelimPos > 0)
displayMsg(messageType, target, userDecode(target, dequotedMessage.left(xdelimPos)), prefix, flags);
xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1);
if(xdelimEndPos == -1) {
xdelimEndPos = dequotedMessage.count();
}
ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);
QString ctcpcmd = userDecode(target, ctcp.left(spacePos));
QString ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
spacePos = ctcp.indexOf(' ');
if(spacePos != -1) {
ctcpcmd = userDecode(target, ctcp.left(spacePos));
ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
} else {
ctcpcmd = userDecode(target, ctcp);
ctcpparam = QString();
ctcpparam = QString();
}
handle(ctcpcmd, Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam));
}
if(!dequotedMessage.isEmpty())
void CtcpHandler::query(const QString &bufname, const QString &ctcpTag, const QString &message) {
QList<QByteArray> params;
params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
emit putCmd("PRIVMSG", params);
}
void CtcpHandler::reply(const QString &bufname, const QString &ctcpTag, const QString &message) {
QList<QByteArray> params;
params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
emit putCmd("NOTICE", params);
}
void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(ctcptype)
emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix);
}
emit putCmd("NOTICE", params);
}
Commit Message:
CWE ID: CWE-399 | void CtcpHandler::parse(Message::Type messageType, const QString &prefix, const QString &target, const QByteArray &message) {
QByteArray ctcp;
QByteArray dequotedMessage = lowLevelDequote(message);
CtcpType ctcptype = messageType == Message::Notice
? CtcpReply
: CtcpQuery;
Message::Flags flags = (messageType == Message::Notice && !network()->isChannelName(target))
? Message::Redirected
: Message::None;
int xdelimPos = -1;
int xdelimEndPos = -1;
int spacePos = -1;
QList<QByteArray> replies;
while((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) {
if(xdelimPos > 0)
displayMsg(messageType, target, userDecode(target, dequotedMessage.left(xdelimPos)), prefix, flags);
xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1);
if(xdelimEndPos == -1) {
xdelimEndPos = dequotedMessage.count();
}
ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);
QString ctcpcmd = userDecode(target, ctcp.left(spacePos));
QString ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
spacePos = ctcp.indexOf(' ');
if(spacePos != -1) {
ctcpcmd = userDecode(target, ctcp.left(spacePos));
ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
} else {
ctcpcmd = userDecode(target, ctcp);
ctcpparam = QString();
ctcpparam = QString();
}
if(!_ignoreListManager->ctcpMatch(prefix, network()->networkName(), ctcpcmd.toUpper())) {
QString reply_;
handle(ctcpcmd, Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam), Q_ARG(QString, reply_));
if(ctcptype == CtcpQuery && !reply_.isNull()) {
replies << lowLevelQuote(pack(serverEncode(ctcpcmd), userEncode(nickFromMask(prefix), reply_)));
}
}
}
if(ctcptype == CtcpQuery && !replies.isEmpty()) {
packedReply(nickFromMask(prefix), replies);
}
if(!dequotedMessage.isEmpty())
void CtcpHandler::query(const QString &bufname, const QString &ctcpTag, const QString &message) {
QList<QByteArray> params;
params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
emit putCmd("PRIVMSG", params);
}
void CtcpHandler::reply(const QString &bufname, const QString &ctcpTag, const QString &message) {
QList<QByteArray> params;
params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
emit putCmd("NOTICE", params);
}
void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(ctcptype)
emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix);
}
emit putCmd("NOTICE", params);
}
| 164,881 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
| 167,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_data(void)
{
FILE *file = fopen (dump_file, "w");
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
dump_file, errno, strerror(errno));
return;
}
dump_data_vrrp(file);
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_data(void)
{
FILE *file = fopen_safe(dump_file, "w");
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
dump_file, errno, strerror(errno));
return;
}
dump_data_vrrp(file);
fclose(file);
}
| 168,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void *buf, void *end)
{
void *p = buf;
char *dbuf;
char *ticket_buf;
u8 reply_struct_v;
u32 num;
int ret;
dbuf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS);
if (!dbuf)
return -ENOMEM;
ret = -ENOMEM;
ticket_buf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS);
if (!ticket_buf)
goto out_dbuf;
ceph_decode_8_safe(&p, end, reply_struct_v, bad);
if (reply_struct_v != 1)
return -EINVAL;
ceph_decode_32_safe(&p, end, num, bad);
dout("%d tickets\n", num);
while (num--) {
ret = process_one_ticket(ac, secret, &p, end,
dbuf, ticket_buf);
if (ret)
goto out;
}
ret = 0;
out:
kfree(ticket_buf);
out_dbuf:
kfree(dbuf);
return ret;
bad:
ret = -EINVAL;
goto out;
}
Commit Message: libceph: do not hard code max auth ticket len
We hard code cephx auth ticket buffer size to 256 bytes. This isn't
enough for any moderate setups and, in case tickets themselves are not
encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but
ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the
buffer is allocated dynamically anyway, allocated it a bit later, at
the point where we know how much is going to be needed.
Fixes: http://tracker.ceph.com/issues/8979
Cc: [email protected]
Signed-off-by: Ilya Dryomov <[email protected]>
Reviewed-by: Sage Weil <[email protected]>
CWE ID: CWE-399 | static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void *buf, void *end)
{
void *p = buf;
u8 reply_struct_v;
u32 num;
int ret;
ceph_decode_8_safe(&p, end, reply_struct_v, bad);
if (reply_struct_v != 1)
return -EINVAL;
ceph_decode_32_safe(&p, end, num, bad);
dout("%d tickets\n", num);
while (num--) {
ret = process_one_ticket(ac, secret, &p, end);
if (ret)
return ret;
}
return 0;
bad:
return -EINVAL;
}
| 166,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: void AutoFillMetrics::Log(QualityMetric metric) const {
DCHECK(metric < NUM_QUALITY_METRICS);
UMA_HISTOGRAM_ENUMERATION("AutoFill.Quality", metric,
NUM_QUALITY_METRICS);
}
Commit Message: Add support for autofill server experiments
BUG=none
TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId
Review URL: http://codereview.chromium.org/6260027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AutoFillMetrics::Log(QualityMetric metric) const {
void AutoFillMetrics::Log(QualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_QUALITY_METRICS);
std::string histogram_name = "AutoFill.Quality";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
UMA_HISTOGRAM_ENUMERATION(histogram_name, metric, NUM_QUALITY_METRICS);
}
| 170,652 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftMPEG4Encoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline ||
h263type->eLevel != OMX_VIDEO_H263Level45 ||
(h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
h263type->bPLUSPTYPEAllowed != OMX_FALSE ||
h263type->bForceRoundingTypeToZero != OMX_FALSE ||
h263type->nPictureHeaderRepetition != 0 ||
h263type->nGOBHeaderInterval != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore ||
mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 ||
(mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
mpeg4type->nBFrames != 0 ||
mpeg4type->nIDCVLCThreshold != 0 ||
mpeg4type->bACPred != OMX_TRUE ||
mpeg4type->nMaxPacketSize != 256 ||
mpeg4type->nTimeIncRes != 1000 ||
mpeg4type->nHeaderExtension != 0 ||
mpeg4type->bReversibleVLC != OMX_FALSE) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (!isValidOMXParam(h263type)) {
return OMX_ErrorBadParameter;
}
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline ||
h263type->eLevel != OMX_VIDEO_H263Level45 ||
(h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
h263type->bPLUSPTYPEAllowed != OMX_FALSE ||
h263type->bForceRoundingTypeToZero != OMX_FALSE ||
h263type->nPictureHeaderRepetition != 0 ||
h263type->nGOBHeaderInterval != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (!isValidOMXParam(mpeg4type)) {
return OMX_ErrorBadParameter;
}
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore ||
mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 ||
(mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
mpeg4type->nBFrames != 0 ||
mpeg4type->nIDCVLCThreshold != 0 ||
mpeg4type->bACPred != OMX_TRUE ||
mpeg4type->nMaxPacketSize != 256 ||
mpeg4type->nTimeIncRes != 1000 ||
mpeg4type->nHeaderExtension != 0 ||
mpeg4type->bReversibleVLC != OMX_FALSE) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
| 174,210 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GrantActiveTab(const GURL& url) {
APIPermissionSet tab_api_permissions;
tab_api_permissions.insert(APIPermission::kTab);
URLPatternSet tab_hosts;
tab_hosts.AddOrigin(UserScript::ValidUserScriptSchemes(),
url::Origin::Create(url).GetURL());
PermissionSet tab_permissions(std::move(tab_api_permissions),
ManifestPermissionSet(), tab_hosts,
tab_hosts);
active_tab_->permissions_data()->UpdateTabSpecificPermissions(
kTabId, tab_permissions);
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20 | void GrantActiveTab(const GURL& url) {
void GrantActiveTab(const Extension& extension, const GURL& url) {
APIPermissionSet tab_api_permissions;
tab_api_permissions.insert(APIPermission::kTab);
URLPatternSet tab_hosts;
tab_hosts.AddOrigin(UserScript::ValidUserScriptSchemes(),
url::Origin::Create(url).GetURL());
PermissionSet tab_permissions(std::move(tab_api_permissions),
ManifestPermissionSet(), tab_hosts,
tab_hosts);
extension.permissions_data()->UpdateTabSpecificPermissions(kTabId,
tab_permissions);
}
| 173,009 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
{
if (expr == NULL) {
*pred_rtrn = MATCH_ANY_OR_NONE;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
*pred_rtrn = MATCH_EXACTLY;
if (expr->expr.op == EXPR_ACTION_DECL) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);
if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {
log_err(info->ctx,
"Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
return false;
}
expr = expr->action.args;
}
else if (expr->expr.op == EXPR_IDENT) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);
if (pred_txt && istreq(pred_txt, "any")) {
*pred_rtrn = MATCH_ANY;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
}
return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,
mods_rtrn);
}
Commit Message: xkbcomp: Don't crash on no-op modmask expressions
If we have an expression of the form 'l1' in an interp section, we
unconditionally try to dereference its args, even if it has none.
Signed-off-by: Daniel Stone <[email protected]>
CWE ID: CWE-476 | ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
{
if (expr == NULL) {
*pred_rtrn = MATCH_ANY_OR_NONE;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
*pred_rtrn = MATCH_EXACTLY;
if (expr->expr.op == EXPR_ACTION_DECL) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);
if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) ||
!expr->action.args) {
log_err(info->ctx,
"Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
return false;
}
expr = expr->action.args;
}
else if (expr->expr.op == EXPR_IDENT) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);
if (pred_txt && istreq(pred_txt, "any")) {
*pred_rtrn = MATCH_ANY;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
}
return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,
mods_rtrn);
}
| 169,088 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
Commit Message:
CWE ID: CWE-119 | parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
string_count = FT_MIN( 64, string_count );
p += sizeof ( short );
for ( i = 0; i < string_count; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= string_count )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
| 164,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 trigger_fpga_config(void)
{
int ret = 0;
/* if the FPGA is already configured, we do not want to
* reconfigure it */
skip = 0;
if (fpga_done()) {
printf("PCIe FPGA config: skipped\n");
skip = 1;
return 0;
}
if (check_boco2()) {
/* we have a BOCO2, this has to be triggered here */
/* make sure the FPGA_can access the EEPROM */
ret = boco_clear_bits(SPI_REG, CFG_EEPROM);
if (ret)
return ret;
/* trigger the config start */
ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B);
if (ret)
return ret;
/* small delay for the pulse */
udelay(10);
/* up signal for pulse end */
ret = boco_set_bits(SPI_REG, FPGA_PROG);
if (ret)
return ret;
/* finally, raise INIT_B to remove the config delay */
ret = boco_set_bits(SPI_REG, FPGA_INIT_B);
if (ret)
return ret;
} else {
/* we do it the old way, with the gpio pin */
kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1);
kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0);
/* small delay for the pulse */
udelay(10);
kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN);
}
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | int trigger_fpga_config(void)
{
int ret = 0;
skip = 0;
#ifndef CONFIG_KM_FPGA_FORCE_CONFIG
/* if the FPGA is already configured, we do not want to
* reconfigure it */
skip = 0;
if (fpga_done()) {
printf("PCIe FPGA config: skipped\n");
skip = 1;
return 0;
}
#endif /* CONFIG_KM_FPGA_FORCE_CONFIG */
if (check_boco2()) {
/* we have a BOCO2, this has to be triggered here */
/* make sure the FPGA_can access the EEPROM */
ret = boco_clear_bits(SPI_REG, CFG_EEPROM);
if (ret)
return ret;
/* trigger the config start */
ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B);
if (ret)
return ret;
/* small delay for the pulse */
udelay(10);
/* up signal for pulse end */
ret = boco_set_bits(SPI_REG, FPGA_PROG);
if (ret)
return ret;
/* finally, raise INIT_B to remove the config delay */
ret = boco_set_bits(SPI_REG, FPGA_INIT_B);
if (ret)
return ret;
} else {
/* we do it the old way, with the gpio pin */
kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1);
kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0);
/* small delay for the pulse */
udelay(10);
kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN);
}
return 0;
}
| 169,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: int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int err;
u32 tsk_portid = cb->args[0];
u32 last_publ = cb->args[1];
u32 done = cb->args[2];
struct net *net = sock_net(skb->sk);
struct tipc_sock *tsk;
if (!tsk_portid) {
struct nlattr **attrs;
struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
err = tipc_nlmsg_parse(cb->nlh, &attrs);
if (err)
return err;
err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
attrs[TIPC_NLA_SOCK],
tipc_nl_sock_policy);
if (err)
return err;
if (!sock[TIPC_NLA_SOCK_REF])
return -EINVAL;
tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
}
if (done)
return 0;
tsk = tipc_sk_lookup(net, tsk_portid);
if (!tsk)
return -EINVAL;
lock_sock(&tsk->sk);
err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
if (!err)
done = 1;
release_sock(&tsk->sk);
sock_put(&tsk->sk);
cb->args[0] = tsk_portid;
cb->args[1] = last_publ;
cb->args[2] = done;
return skb->len;
}
Commit Message: tipc: check nl sock before parsing nested attributes
Make sure the socket for which the user is listing publication exists
before parsing the socket netlink attributes.
Prior to this patch a call without any socket caused a NULL pointer
dereference in tipc_nl_publ_dump().
Tested-and-reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Richard Alpe <[email protected]>
Acked-by: Jon Maloy <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int err;
u32 tsk_portid = cb->args[0];
u32 last_publ = cb->args[1];
u32 done = cb->args[2];
struct net *net = sock_net(skb->sk);
struct tipc_sock *tsk;
if (!tsk_portid) {
struct nlattr **attrs;
struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
err = tipc_nlmsg_parse(cb->nlh, &attrs);
if (err)
return err;
if (!attrs[TIPC_NLA_SOCK])
return -EINVAL;
err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
attrs[TIPC_NLA_SOCK],
tipc_nl_sock_policy);
if (err)
return err;
if (!sock[TIPC_NLA_SOCK_REF])
return -EINVAL;
tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
}
if (done)
return 0;
tsk = tipc_sk_lookup(net, tsk_portid);
if (!tsk)
return -EINVAL;
lock_sock(&tsk->sk);
err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
if (!err)
done = 1;
release_sock(&tsk->sk);
sock_put(&tsk->sk);
cb->args[0] = tsk_portid;
cb->args[1] = last_publ;
cb->args[2] = done;
return skb->len;
}
| 167,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::resolveURLInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
const KURL& fileSystemURL,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
fileSystem()->resolveURL(fileSystemURL, callbacks->release());
}
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::resolveURLInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
const KURL& fileSystemURL,
CallbackWrapper* callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
fileSystem()->resolveURL(fileSystemURL, callbacks->release());
}
| 171,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
xmlHaltParser(ctxt);
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
Commit Message: DO NOT MERGE: Add validation for eternal enities
https://bugzilla.gnome.org/show_bug.cgi?id=780691
Bug: 36556310
Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648
(cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049)
CWE ID: CWE-611 | xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
((ctxt->options & XML_PARSE_DTDLOAD) == 0) &&
((ctxt->options & XML_PARSE_DTDATTR) == 0) &&
(ctxt->replaceEntities == 0) &&
(ctxt->validate == 0))
return;
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
xmlHaltParser(ctxt);
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
| 174,120 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NavigatorImpl::DidNavigate(
RenderFrameHostImpl* render_frame_host,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
std::unique_ptr<NavigationHandleImpl> navigation_handle) {
FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible();
bool is_navigation_within_page = controller_->IsURLInPageNavigation(
params.url, params.origin, params.was_within_same_document,
render_frame_host);
if (is_navigation_within_page &&
render_frame_host !=
render_frame_host->frame_tree_node()
->render_manager()
->current_frame_host()) {
bad_message::ReceivedBadMessage(render_frame_host->GetProcess(),
bad_message::NI_IN_PAGE_NAVIGATION);
is_navigation_within_page = false;
}
if (ui::PageTransitionIsMainFrame(params.transition)) {
if (delegate_) {
if (delegate_->CanOverscrollContent()) {
if (!params.was_within_same_document)
controller_->TakeScreenshot();
}
delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
}
if (!oopifs_possible)
frame_tree->root()->render_manager()->DidNavigateFrame(
render_frame_host, params.gesture == NavigationGestureUser);
}
render_frame_host->frame_tree_node()->SetCurrentOrigin(
params.origin, params.has_potentially_trustworthy_unique_origin);
render_frame_host->frame_tree_node()->SetInsecureRequestPolicy(
params.insecure_request_policy);
if (!is_navigation_within_page) {
render_frame_host->ResetContentSecurityPolicies();
render_frame_host->frame_tree_node()->ResetCspHeaders();
render_frame_host->frame_tree_node()->ResetFeaturePolicyHeader();
}
if (oopifs_possible) {
FrameTreeNode* frame = render_frame_host->frame_tree_node();
frame->render_manager()->DidNavigateFrame(
render_frame_host, params.gesture == NavigationGestureUser);
}
SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
if (!site_instance->HasSite() && ShouldAssignSiteForURL(params.url) &&
!params.url_is_unreachable) {
site_instance->SetSite(params.url);
}
if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
delegate_->SetMainFrameMimeType(params.contents_mime_type);
int old_entry_count = controller_->GetEntryCount();
LoadCommittedDetails details;
bool did_navigate = controller_->RendererDidNavigate(
render_frame_host, params, &details, is_navigation_within_page,
navigation_handle.get());
if (old_entry_count != controller_->GetEntryCount() ||
details.previous_entry_index !=
controller_->GetLastCommittedEntryIndex()) {
frame_tree->root()->render_manager()->SendPageMessage(
new PageMsg_SetHistoryOffsetAndLength(
MSG_ROUTING_NONE, controller_->GetLastCommittedEntryIndex(),
controller_->GetEntryCount()),
site_instance);
}
render_frame_host->frame_tree_node()->SetCurrentURL(params.url);
render_frame_host->SetLastCommittedOrigin(params.origin);
if (!params.url_is_unreachable)
render_frame_host->set_last_successful_url(params.url);
if (did_navigate && !is_navigation_within_page)
render_frame_host->ResetFeaturePolicy();
if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
DCHECK_EQ(!render_frame_host->GetParent(),
did_navigate ? details.is_main_frame : false);
navigation_handle->DidCommitNavigation(params, did_navigate,
details.did_replace_entry,
details.previous_url, details.type,
render_frame_host);
navigation_handle.reset();
}
if (!did_navigate)
return; // No navigation happened.
RecordNavigationMetrics(details, params, site_instance);
if (delegate_) {
if (details.is_main_frame) {
delegate_->DidNavigateMainFramePostCommit(render_frame_host,
details, params);
}
delegate_->DidNavigateAnyFramePostCommit(
render_frame_host, details, params);
}
}
Commit Message: Correctly reset FP in RFHI whenever origin changes
Bug: 713364
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
Reviewed-on: https://chromium-review.googlesource.com/482380
Commit-Queue: Ian Clelland <[email protected]>
Reviewed-by: Charles Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#466778}
CWE ID: CWE-254 | void NavigatorImpl::DidNavigate(
RenderFrameHostImpl* render_frame_host,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
std::unique_ptr<NavigationHandleImpl> navigation_handle) {
FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible();
bool is_navigation_within_page = controller_->IsURLInPageNavigation(
params.url, params.origin, params.was_within_same_document,
render_frame_host);
if (is_navigation_within_page &&
render_frame_host !=
render_frame_host->frame_tree_node()
->render_manager()
->current_frame_host()) {
bad_message::ReceivedBadMessage(render_frame_host->GetProcess(),
bad_message::NI_IN_PAGE_NAVIGATION);
is_navigation_within_page = false;
}
if (ui::PageTransitionIsMainFrame(params.transition)) {
if (delegate_) {
if (delegate_->CanOverscrollContent()) {
if (!params.was_within_same_document)
controller_->TakeScreenshot();
}
delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
}
if (!oopifs_possible)
frame_tree->root()->render_manager()->DidNavigateFrame(
render_frame_host, params.gesture == NavigationGestureUser);
}
render_frame_host->frame_tree_node()->SetCurrentOrigin(
params.origin, params.has_potentially_trustworthy_unique_origin);
render_frame_host->frame_tree_node()->SetInsecureRequestPolicy(
params.insecure_request_policy);
if (!is_navigation_within_page) {
render_frame_host->ResetContentSecurityPolicies();
render_frame_host->frame_tree_node()->ResetCspHeaders();
render_frame_host->frame_tree_node()->ResetFeaturePolicyHeader();
}
if (oopifs_possible) {
FrameTreeNode* frame = render_frame_host->frame_tree_node();
frame->render_manager()->DidNavigateFrame(
render_frame_host, params.gesture == NavigationGestureUser);
}
SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
if (!site_instance->HasSite() && ShouldAssignSiteForURL(params.url) &&
!params.url_is_unreachable) {
site_instance->SetSite(params.url);
}
if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
delegate_->SetMainFrameMimeType(params.contents_mime_type);
int old_entry_count = controller_->GetEntryCount();
LoadCommittedDetails details;
bool did_navigate = controller_->RendererDidNavigate(
render_frame_host, params, &details, is_navigation_within_page,
navigation_handle.get());
if (old_entry_count != controller_->GetEntryCount() ||
details.previous_entry_index !=
controller_->GetLastCommittedEntryIndex()) {
frame_tree->root()->render_manager()->SendPageMessage(
new PageMsg_SetHistoryOffsetAndLength(
MSG_ROUTING_NONE, controller_->GetLastCommittedEntryIndex(),
controller_->GetEntryCount()),
site_instance);
}
render_frame_host->frame_tree_node()->SetCurrentURL(params.url);
render_frame_host->SetLastCommittedOrigin(params.origin);
if (!params.url_is_unreachable)
render_frame_host->set_last_successful_url(params.url);
if (!is_navigation_within_page)
render_frame_host->ResetFeaturePolicy();
if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
DCHECK_EQ(!render_frame_host->GetParent(),
did_navigate ? details.is_main_frame : false);
navigation_handle->DidCommitNavigation(params, did_navigate,
details.did_replace_entry,
details.previous_url, details.type,
render_frame_host);
navigation_handle.reset();
}
if (!did_navigate)
return; // No navigation happened.
RecordNavigationMetrics(details, params, site_instance);
if (delegate_) {
if (details.is_main_frame) {
delegate_->DidNavigateMainFramePostCommit(render_frame_host,
details, params);
}
delegate_->DidNavigateAnyFramePostCommit(
render_frame_host, details, params);
}
}
| 171,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
xmlDefaultSAXHandlerInit();
xmlDetectSAX2(ctxt);
GROW;
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
*/
GROW;
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = 0;
ctxt->loadsubset = 0;
ctxt->depth = 0;
xmlParseContent(ctxt);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
if (! ctxt->wellFormed) return(-1);
return(0);
}
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 | xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
xmlDefaultSAXHandlerInit();
xmlDetectSAX2(ctxt);
GROW;
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
*/
GROW;
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = 0;
ctxt->loadsubset = 0;
ctxt->depth = 0;
xmlParseContent(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
if (! ctxt->wellFormed) return(-1);
return(0);
}
| 171,291 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *input_file;
jpg_dest_t dest_mgr_buf;
jpg_dest_t *dest_mgr = &dest_mgr_buf;
JDIMENSION num_scanlines;
jas_image_t *image;
int ret;
jpg_dec_importopts_t opts;
size_t size;
if (jpg_dec_parseopts(optstr, &opts)) {
goto error;
}
memset(&cinfo, 0, sizeof(struct jpeg_decompress_struct));
memset(dest_mgr, 0, sizeof(jpg_dest_t));
dest_mgr->data = 0;
image = 0;
input_file = 0;
if (!(input_file = tmpfile())) {
jas_eprintf("cannot make temporary file\n");
goto error;
}
if (jpg_copystreamtofile(input_file, in)) {
jas_eprintf("cannot copy stream\n");
goto error;
}
rewind(input_file);
/* Allocate and initialize a JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_std_error(%p)\n", &jerr));
cinfo.err = jpeg_std_error(&jerr);
JAS_DBGLOG(10, ("jpeg_create_decompress(%p)\n", &cinfo));
jpeg_create_decompress(&cinfo);
/* Specify the data source for decompression. */
JAS_DBGLOG(10, ("jpeg_stdio_src(%p, %p)\n", &cinfo, input_file));
jpeg_stdio_src(&cinfo, input_file);
/* Read the file header to obtain the image information. */
JAS_DBGLOG(10, ("jpeg_read_header(%p, TRUE)\n", &cinfo));
ret = jpeg_read_header(&cinfo, TRUE);
JAS_DBGLOG(10, ("jpeg_read_header return value %d\n", ret));
if (ret != JPEG_HEADER_OK) {
jas_eprintf("jpeg_read_header did not return JPEG_HEADER_OK\n");
}
JAS_DBGLOG(10, (
"header: image_width %d; image_height %d; num_components %d\n",
cinfo.image_width, cinfo.image_height, cinfo.num_components)
);
/* Start the decompressor. */
JAS_DBGLOG(10, ("jpeg_start_decompress(%p)\n", &cinfo));
ret = jpeg_start_decompress(&cinfo);
JAS_DBGLOG(10, ("jpeg_start_decompress return value %d\n", ret));
JAS_DBGLOG(10, (
"header: output_width %d; output_height %d; output_components %d\n",
cinfo.output_width, cinfo.output_height, cinfo.output_components)
);
if (opts.max_size) {
if (!jas_safe_size_mul(cinfo.output_width, cinfo.output_height,
&size) ||
!jas_safe_size_mul(size, cinfo.output_components, &size)) {
goto error;
}
if (size > opts.max_size) {
jas_eprintf("image is too large\n");
goto error;
}
}
/* Create an image object to hold the decoded data. */
if (!(image = jpg_mkimage(&cinfo))) {
jas_eprintf("jpg_mkimage failed\n");
goto error;
}
/* Initialize the data sink object. */
dest_mgr->image = image;
if (!(dest_mgr->data = jas_matrix_create(1, cinfo.output_width))) {
jas_eprintf("jas_matrix_create failed\n");
goto error;
}
dest_mgr->start_output = jpg_start_output;
dest_mgr->put_pixel_rows = jpg_put_pixel_rows;
dest_mgr->finish_output = jpg_finish_output;
dest_mgr->buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE,
cinfo.output_width * cinfo.output_components, (JDIMENSION) 1);
dest_mgr->buffer_height = 1;
dest_mgr->error = 0;
/* Process the compressed data. */
(*dest_mgr->start_output)(&cinfo, dest_mgr);
while (cinfo.output_scanline < cinfo.output_height) {
JAS_DBGLOG(10, ("jpeg_read_scanlines(%p, %p, %lu)\n", &cinfo,
dest_mgr->buffer, JAS_CAST(unsigned long, dest_mgr->buffer_height)));
num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
dest_mgr->buffer_height);
JAS_DBGLOG(10, ("jpeg_read_scanlines return value %lu\n",
JAS_CAST(unsigned long, num_scanlines)));
(*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines);
}
(*dest_mgr->finish_output)(&cinfo, dest_mgr);
/* Complete the decompression process. */
JAS_DBGLOG(10, ("jpeg_finish_decompress(%p)\n", &cinfo));
jpeg_finish_decompress(&cinfo);
/* Destroy the JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_destroy_decompress(%p)\n", &cinfo));
jpeg_destroy_decompress(&cinfo);
jas_matrix_destroy(dest_mgr->data);
JAS_DBGLOG(10, ("fclose(%p)\n", input_file));
fclose(input_file);
input_file = 0;
if (dest_mgr->error) {
jas_eprintf("error during decoding\n");
goto error;
}
return image;
error:
if (dest_mgr->data) {
jas_matrix_destroy(dest_mgr->data);
}
if (image) {
jas_image_destroy(image);
}
if (input_file) {
fclose(input_file);
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *input_file;
jpg_dest_t dest_mgr_buf;
jpg_dest_t *dest_mgr = &dest_mgr_buf;
JDIMENSION num_scanlines;
jas_image_t *image;
int ret;
jpg_dec_importopts_t opts;
size_t num_samples;
JAS_DBGLOG(100, ("jpg_decode(%p, \"%s\")\n", in, optstr));
if (jpg_dec_parseopts(optstr, &opts)) {
goto error;
}
memset(&cinfo, 0, sizeof(struct jpeg_decompress_struct));
memset(dest_mgr, 0, sizeof(jpg_dest_t));
dest_mgr->data = 0;
image = 0;
input_file = 0;
if (!(input_file = tmpfile())) {
jas_eprintf("cannot make temporary file\n");
goto error;
}
if (jpg_copystreamtofile(input_file, in)) {
jas_eprintf("cannot copy stream\n");
goto error;
}
rewind(input_file);
/* Allocate and initialize a JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_std_error(%p)\n", &jerr));
cinfo.err = jpeg_std_error(&jerr);
JAS_DBGLOG(10, ("jpeg_create_decompress(%p)\n", &cinfo));
jpeg_create_decompress(&cinfo);
/* Specify the data source for decompression. */
JAS_DBGLOG(10, ("jpeg_stdio_src(%p, %p)\n", &cinfo, input_file));
jpeg_stdio_src(&cinfo, input_file);
/* Read the file header to obtain the image information. */
JAS_DBGLOG(10, ("jpeg_read_header(%p, TRUE)\n", &cinfo));
ret = jpeg_read_header(&cinfo, TRUE);
JAS_DBGLOG(10, ("jpeg_read_header return value %d\n", ret));
if (ret != JPEG_HEADER_OK) {
jas_eprintf("jpeg_read_header did not return JPEG_HEADER_OK\n");
}
JAS_DBGLOG(10, (
"header: image_width %d; image_height %d; num_components %d\n",
cinfo.image_width, cinfo.image_height, cinfo.num_components)
);
if (opts.max_samples > 0) {
if (!jas_safe_size_mul3(cinfo.image_width, cinfo.image_height,
cinfo.num_components, &num_samples)) {
goto error;
}
if (num_samples > opts.max_samples) {
jas_eprintf("image is too large (%zu > %zu)\n", num_samples,
opts.max_samples);
goto error;
}
}
/* Start the decompressor. */
JAS_DBGLOG(10, ("jpeg_start_decompress(%p)\n", &cinfo));
ret = jpeg_start_decompress(&cinfo);
JAS_DBGLOG(10, ("jpeg_start_decompress return value %d\n", ret));
JAS_DBGLOG(10, (
"header: output_width %d; output_height %d; output_components %d\n",
cinfo.output_width, cinfo.output_height, cinfo.output_components)
);
/* Create an image object to hold the decoded data. */
if (!(image = jpg_mkimage(&cinfo))) {
jas_eprintf("jpg_mkimage failed\n");
goto error;
}
/* Initialize the data sink object. */
dest_mgr->image = image;
if (!(dest_mgr->data = jas_matrix_create(1, cinfo.output_width))) {
jas_eprintf("jas_matrix_create failed\n");
goto error;
}
dest_mgr->start_output = jpg_start_output;
dest_mgr->put_pixel_rows = jpg_put_pixel_rows;
dest_mgr->finish_output = jpg_finish_output;
dest_mgr->buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE,
cinfo.output_width * cinfo.output_components, (JDIMENSION) 1);
dest_mgr->buffer_height = 1;
dest_mgr->error = 0;
/* Process the compressed data. */
(*dest_mgr->start_output)(&cinfo, dest_mgr);
while (cinfo.output_scanline < cinfo.output_height) {
JAS_DBGLOG(10, ("jpeg_read_scanlines(%p, %p, %lu)\n", &cinfo,
dest_mgr->buffer, JAS_CAST(unsigned long, dest_mgr->buffer_height)));
num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
dest_mgr->buffer_height);
JAS_DBGLOG(10, ("jpeg_read_scanlines return value %lu\n",
JAS_CAST(unsigned long, num_scanlines)));
(*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines);
}
(*dest_mgr->finish_output)(&cinfo, dest_mgr);
/* Complete the decompression process. */
JAS_DBGLOG(10, ("jpeg_finish_decompress(%p)\n", &cinfo));
jpeg_finish_decompress(&cinfo);
/* Destroy the JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_destroy_decompress(%p)\n", &cinfo));
jpeg_destroy_decompress(&cinfo);
jas_matrix_destroy(dest_mgr->data);
JAS_DBGLOG(10, ("fclose(%p)\n", input_file));
fclose(input_file);
input_file = 0;
if (dest_mgr->error) {
jas_eprintf("error during decoding\n");
goto error;
}
return image;
error:
if (dest_mgr->data) {
jas_matrix_destroy(dest_mgr->data);
}
if (image) {
jas_image_destroy(image);
}
if (input_file) {
fclose(input_file);
}
return 0;
}
| 168,722 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.